mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-04 08:56:59 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b37ab78451 | ||
|
|
6e3d2c335e | ||
|
|
14b6df7bce |
No files matched your search
Generated
+4
-4
@@ -3518,7 +3518,7 @@ checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-cli"
|
||||
version = "1.4.0"
|
||||
version = "1.6.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap 4.6.4",
|
||||
@@ -3533,7 +3533,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-core"
|
||||
version = "1.4.0"
|
||||
version = "1.6.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"directories",
|
||||
@@ -3554,7 +3554,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-fuse"
|
||||
version = "1.4.0"
|
||||
version = "1.6.0"
|
||||
dependencies = [
|
||||
"fuser",
|
||||
"futures",
|
||||
@@ -3571,7 +3571,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-gui"
|
||||
version = "1.4.0"
|
||||
version = "1.6.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-channel",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/pdfs-core", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.4.0"
|
||||
version = "1.6.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
authors = ["Nils Pukropp <contact@narl.io>"]
|
||||
|
||||
@@ -27,6 +27,80 @@ A fast, unofficial Proton Drive client for Linux. This client features an advanc
|
||||
|
||||
The prompt stays resident after its first launch, so invoking the shortcut again reuses and resets the existing window. Drive folders open from the mount. Audio and video results also open through FUSE, allowing media players to seek and request ranges without downloading the entire file first; ordinary Drive files are materialized into the local cache before opening.
|
||||
|
||||
### Using your own launcher (fuzzel, rofi, wofi, …)
|
||||
|
||||
`pdfs-prompt --dmenu` runs the same search through an external dmenu-style
|
||||
launcher instead of the built-in window, so the HUD matches the rest of a
|
||||
tiling-WM desktop:
|
||||
|
||||
```bash
|
||||
pdfs-prompt --dmenu # fuzzel/rofi/wofi/tofi/bemenu/dmenu, whichever is installed
|
||||
pdfs-prompt --dmenu --menu 'fuzzel --dmenu --width 60'
|
||||
pdfs-prompt --dmenu --query invoice # skip straight to a search
|
||||
```
|
||||
|
||||
A launcher filters a fixed list — it cannot ask for a new one per keystroke — so
|
||||
searching takes two steps, and the prompt says which step you are on:
|
||||
|
||||
- `Search Drive ›` lists your pinned files. Type anything that isn't one of them
|
||||
and press Enter to search for it.
|
||||
- `Drive: invoice ›` lists the results. Enter opens one; typing something else
|
||||
and pressing Enter searches again. Escape closes.
|
||||
|
||||
`--query` skips the first step. fuzzel and rofi also get file-type icons.
|
||||
|
||||
To make an existing keybinding use it without re-binding, and to pin the
|
||||
launcher command, set them in `config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"prompt": {
|
||||
"mode": "dmenu",
|
||||
"menu": ["fuzzel", "--dmenu", "--width", "60"],
|
||||
"menu_limit": 50
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`--gtk` overrides `"mode": "dmenu"` for one invocation. A `{prompt}` token
|
||||
anywhere in `menu` is replaced by the prompt text; without one, the launcher's
|
||||
own prompt flag is appended.
|
||||
|
||||
## Choosing How Files Open
|
||||
|
||||
By default every result is handed to `xdg-open`. An `open_with` block in
|
||||
`config.json` overrides that per file type — for instance opening text in
|
||||
Neovim inside Alacritty, while everything else still goes to the desktop:
|
||||
|
||||
```json
|
||||
{
|
||||
"open_with": {
|
||||
"terminal": ["alacritty", "-e"],
|
||||
"rules": [
|
||||
{ "match": ["@text"], "command": ["nvim"], "terminal": true },
|
||||
{ "match": ["*.png", "*.jpg"], "command": ["imv"] }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `match` takes file-name globs (`*.md`, `notes-*.txt`) or the classes `@dir`,
|
||||
`@text`, `@document`, `@image`, `@media`, `@any`. First matching rule wins.
|
||||
- `command` is argv, not a shell line. A `{}` token is replaced by the path;
|
||||
without one the path is appended. `$VAR` tokens expand from the environment,
|
||||
so `["$EDITOR"]` follows your editor.
|
||||
- `"terminal": true` wraps the command in `terminal`. When that is unset, the
|
||||
terminal comes from `$PDFS_TERMINAL`, then `$TERMINAL`, then the first known
|
||||
emulator on `PATH`; a bare name like `TERMINAL=alacritty` gains the right
|
||||
"run this" flag automatically.
|
||||
- `"default": [...]` replaces `xdg-open` for everything unmatched.
|
||||
|
||||
The rules apply to the prompt (both front ends) and to the GTK browser, so a
|
||||
file opens the same way wherever it was picked. Patterns are matched against the
|
||||
Drive name — a downloaded file is stored in the cache under its content hash,
|
||||
which says nothing about its type, so matching that would send everything to
|
||||
`xdg-open`.
|
||||
|
||||
## Selective Sync (`.pdfsignore`)
|
||||
|
||||
Two-way synced folders skip paths matched by ignore rules, so syncing a project
|
||||
|
||||
@@ -102,6 +102,16 @@ pub struct Pin {
|
||||
/// file. Defaulted so a legacy `pins.json` (file pins only) still parses.
|
||||
#[serde(default)]
|
||||
pub recursive: bool,
|
||||
/// Whether the pinned node is a folder, when the node cache knows.
|
||||
///
|
||||
/// `recursive` is pin *policy*, not node kind: a folder pinned
|
||||
/// non-recursively has `recursive: false`, and a front-end reading it as
|
||||
/// "this is a file" draws a file icon and sends an invalid `OpenFile`. This
|
||||
/// is resolved from the `nodes` row at list time, so it is `None` for a pin
|
||||
/// whose node is not cached — and absent from an older daemon's reply,
|
||||
/// which is why it is defaulted.
|
||||
#[serde(default)]
|
||||
pub is_dir: Option<bool>,
|
||||
}
|
||||
|
||||
/// The legacy JSON pin registry, kept only to import a pre-P5 `pins.json` into
|
||||
@@ -1348,10 +1358,11 @@ impl ContentCache {
|
||||
.pin_list()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(uid, path, recursive)| Pin {
|
||||
uid,
|
||||
path,
|
||||
recursive,
|
||||
.map(|row| Pin {
|
||||
uid: row.uid,
|
||||
path: row.path,
|
||||
recursive: row.recursive,
|
||||
is_dir: row.is_dir,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::menu::PromptConfig;
|
||||
use crate::opener::OpenWith;
|
||||
use crate::syncignore::DEFAULT_IGNORE_PATTERNS;
|
||||
|
||||
/// Proton requires `external-drive-{name}@{semver}-{channel}` (channel ∈
|
||||
@@ -106,6 +108,17 @@ pub struct AppConfig {
|
||||
/// the field, and overridable at runtime via [`CONFLICT_SWEEP_ENV`].
|
||||
#[serde(default)]
|
||||
pub conflict_sweep: Option<SweepMode>,
|
||||
/// How files opened from the prompt/browser are launched. `None` means
|
||||
/// "hand everything to `xdg-open`", which is what the client did before
|
||||
/// this existed. See [`crate::opener`]. Defaulted for configs predating the
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub open_with: Option<OpenWith>,
|
||||
/// `pdfs-prompt` behaviour, including the external launcher used by
|
||||
/// `--dmenu`. See [`crate::menu`]. Defaulted for configs predating the
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub prompt: Option<PromptConfig>,
|
||||
}
|
||||
|
||||
impl Default for AppConfig {
|
||||
@@ -118,6 +131,8 @@ impl Default for AppConfig {
|
||||
ignore_patterns: None,
|
||||
device_uid: None,
|
||||
conflict_sweep: None,
|
||||
open_with: None,
|
||||
prompt: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,6 +144,18 @@ impl AppConfig {
|
||||
self.cache_budget.unwrap_or(DEFAULT_CACHE_BUDGET_BYTES)
|
||||
}
|
||||
|
||||
/// The effective opener policy: the user's rules, or the all-`xdg-open`
|
||||
/// default. Cloned rather than borrowed because callers hold it for the
|
||||
/// life of a window, long after the config value is gone.
|
||||
pub fn resolved_open_with(&self) -> OpenWith {
|
||||
self.open_with.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The effective prompt settings, defaulted when the section is absent.
|
||||
pub fn resolved_prompt(&self) -> PromptConfig {
|
||||
self.prompt.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The effective conflict-sweep mode: the [`CONFLICT_SWEEP_ENV`] override if
|
||||
/// it parses, then the user's stored choice, then [`SweepMode::default`].
|
||||
///
|
||||
@@ -448,6 +475,8 @@ mod tests {
|
||||
ignore_patterns: Some(vec!["build/".to_string()]),
|
||||
device_uid: Some("dev-uid".to_string()),
|
||||
conflict_sweep: Some(SweepMode::Enforce),
|
||||
open_with: None,
|
||||
prompt: None,
|
||||
};
|
||||
let json = serde_json::to_string(&config).unwrap();
|
||||
let decoded: AppConfig = serde_json::from_str(&json).unwrap();
|
||||
|
||||
@@ -120,7 +120,18 @@ pub enum Request {
|
||||
/// Download a Drive file's full content into the cache; replies with the
|
||||
/// on-disk path so the front-end can open it with the default app. `path`
|
||||
/// is mountpoint-relative.
|
||||
OpenFile { path: String },
|
||||
///
|
||||
/// `uid` addresses the same node directly and is preferred when present: a
|
||||
/// search hit's path comes from the metadata index, which also indexes
|
||||
/// nodes the primary mount's tree does not expose (an on-demand sync
|
||||
/// folder, a mirror), and walking such a path from the mount root fails
|
||||
/// with "no such file or folder". Defaulted for wire-compat with clients
|
||||
/// predating the field; the daemon falls back to `path` without it.
|
||||
OpenFile {
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
uid: Option<String>,
|
||||
},
|
||||
/// Full-text search node names against the daemon's local metadata index.
|
||||
/// `limit` caps the number of hits returned. Replies with [`Response::SearchResults`].
|
||||
Search { query: String, limit: usize },
|
||||
@@ -2173,6 +2184,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_file_accepts_a_request_from_a_client_predating_the_uid_field() {
|
||||
let legacy = r#"{"OpenFile":{"path":"Documents/ONBOARDING.md"}}"#;
|
||||
let Request::OpenFile { path, uid } = serde_json::from_str::<Request>(legacy).unwrap()
|
||||
else {
|
||||
panic!("decoded into the wrong variant");
|
||||
};
|
||||
assert_eq!(path, "Documents/ONBOARDING.md");
|
||||
assert_eq!(uid, None);
|
||||
|
||||
let with_uid = serde_json::to_string(&Request::OpenFile {
|
||||
path: "Documents/ONBOARDING.md".into(),
|
||||
uid: Some("vol~link".into()),
|
||||
})
|
||||
.unwrap();
|
||||
assert!(with_uid.contains("vol~link"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_daemons_reject_new_by_uid_variants() {
|
||||
#[allow(dead_code)]
|
||||
|
||||
@@ -182,16 +182,36 @@ impl Db {
|
||||
if !terms.is_empty()
|
||||
&& let Some(first) = query.chars().next()
|
||||
{
|
||||
let prefix = format!("{}%", like_escape(&first.to_string()));
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT path, name, is_dir, size, mtime FROM local_files
|
||||
WHERE name COLLATE NOCASE LIKE ?1 ESCAPE '\\'
|
||||
ORDER BY name COLLATE NOCASE LIMIT ?2",
|
||||
)?;
|
||||
let fallback = stmt
|
||||
.query_map(params![prefix, lane_limit as i64], local_hit)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?;
|
||||
for hit in fallback {
|
||||
// Trigram rank says nothing about how well a name *starts* with the
|
||||
// query, so on a home directory full of dependency trees the pool
|
||||
// fills with vendored files before the obvious answer is reached
|
||||
// (measured: 73% of the 500 best-ranked candidates for "test" came
|
||||
// from one Go module cache). Give whole-query prefix matches their
|
||||
// own lane, newest first, and keep the single-character lane —
|
||||
// which recovers a typo that destroyed every trigram — behind it.
|
||||
let mut lanes = vec![(
|
||||
format!("{}%", like_escape(query)),
|
||||
"ORDER BY mtime DESC LIMIT ?2",
|
||||
)];
|
||||
lanes.push((
|
||||
format!("{}%", like_escape(&first.to_string())),
|
||||
"ORDER BY name COLLATE NOCASE LIMIT ?2",
|
||||
));
|
||||
let mut extra = Vec::new();
|
||||
for (pattern, order) in lanes {
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT path, name, is_dir, size, mtime FROM local_files
|
||||
WHERE name COLLATE NOCASE LIKE ?1 ESCAPE '\\' {order}"
|
||||
))?;
|
||||
extra.extend(
|
||||
stmt.query_map(params![pattern, lane_limit as i64], local_hit)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?,
|
||||
);
|
||||
}
|
||||
// Prefix hits go in front: `rows` is truncated to `limit` below, and
|
||||
// the lane exists precisely because trigram rank was burying them.
|
||||
let trigram = std::mem::take(&mut rows);
|
||||
for hit in extra.into_iter().chain(trigram) {
|
||||
if !rows.iter().any(|existing| existing.path == hit.path) {
|
||||
rows.push(hit);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::Db;
|
||||
use crate::Result;
|
||||
|
||||
/// Current schema version. Bump on every forward migration added below.
|
||||
pub(super) const SCHEMA_VERSION: i64 = 20;
|
||||
pub(super) const SCHEMA_VERSION: i64 = 21;
|
||||
|
||||
impl Db {
|
||||
pub(super) fn migrate(&self) -> Result<()> {
|
||||
@@ -101,6 +101,18 @@ impl Db {
|
||||
if current < 20 {
|
||||
tx.execute_batch(MIGRATION_V20)?;
|
||||
}
|
||||
if current < 21 {
|
||||
// A V17-and-older fixture may carry only the tables its own test
|
||||
// cares about; there is nothing to reindex without `nodes`.
|
||||
let has_nodes: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'nodes'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0),
|
||||
)? > 0;
|
||||
if has_nodes {
|
||||
tx.execute_batch(MIGRATION_V21)?;
|
||||
}
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
@@ -527,3 +539,47 @@ const MIGRATION_V20: &str = "
|
||||
ALTER TABLE photos ADD COLUMN favorite INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_favorite ON photos(favorite, seq);
|
||||
";
|
||||
|
||||
/// V21: rebuild the node search index after fixing what counts as indexable.
|
||||
///
|
||||
/// The v16 backfill rooted its path walk at any node whose parent is null *or*
|
||||
/// not cached, but the write path's `node_is_indexable_tx` demanded a
|
||||
/// null-parent ancestor. Only the My Files root has one — a device folder's
|
||||
/// root is stored in `device`/`sync_folder`, never in `nodes` — so every node
|
||||
/// under a device folder was dropped from `nodes_fts` the first time it was
|
||||
/// upserted after the backfill, and was unfindable from the prompt (2,705 of
|
||||
/// 9,252 nodes on the account this was diagnosed against).
|
||||
///
|
||||
/// The rule now matches the backfill, so this replays it: same recursive walk
|
||||
/// as v16, over the current `nodes`.
|
||||
/// Two details the v16 backfill did not carry, both cheap here: a node under a
|
||||
/// trashed folder stays out (the write path has always excluded it, and
|
||||
/// `tombstone_subtree_tx` only marks a subtree it was told about), and the walk
|
||||
/// is depth-capped so a parent cycle in a corrupted database cannot spin the
|
||||
/// migration forever.
|
||||
const MIGRATION_V21: &str = "
|
||||
DROP TABLE IF EXISTS nodes_fts;
|
||||
CREATE VIRTUAL TABLE nodes_fts USING fts5(
|
||||
name, path, tokenize='trigram'
|
||||
);
|
||||
INSERT INTO nodes_fts (rowid, name, path)
|
||||
WITH RECURSIVE paths(rowid, uid, path, trashed, depth) AS (
|
||||
-- Only a true root (no parent at all) contributes nothing to the path: its
|
||||
-- name is the mount. A row whose parent is merely uncached is an ordinary
|
||||
-- folder and keeps its name, which is what `path_of` does at runtime.
|
||||
SELECT n.rowid, n.uid,
|
||||
CASE WHEN n.parent_uid IS NULL THEN '' ELSE n.name END, n.trashed, 0
|
||||
FROM nodes n
|
||||
WHERE n.parent_uid IS NULL
|
||||
OR NOT EXISTS (SELECT 1 FROM nodes p WHERE p.uid = n.parent_uid)
|
||||
UNION ALL
|
||||
SELECT n.rowid, n.uid,
|
||||
CASE WHEN paths.path = '' THEN n.name ELSE paths.path || '/' || n.name END,
|
||||
MAX(paths.trashed, n.trashed), paths.depth + 1
|
||||
FROM nodes n JOIN paths ON n.parent_uid = paths.uid
|
||||
WHERE paths.depth < 256
|
||||
)
|
||||
SELECT n.rowid, n.name, paths.path
|
||||
FROM nodes n JOIN paths ON paths.rowid = n.rowid
|
||||
WHERE paths.trashed = 0;
|
||||
";
|
||||
@@ -50,6 +50,7 @@ pub use ops::{
|
||||
PendingCounts, PendingOp, RenameMeta, op_supersedes,
|
||||
};
|
||||
pub use photos::{StoredPhoto, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
|
||||
pub use pins::PinRow;
|
||||
pub use sync::{StoredSyncEntry, StoredSyncFolder};
|
||||
pub use trash::StoredTrash;
|
||||
|
||||
|
||||
@@ -403,22 +403,30 @@ impl Db {
|
||||
)?;
|
||||
collect_pairs(stmt.query_map(params![expression, lane_limit as i64], pair)?)?
|
||||
};
|
||||
// A short substitution can destroy every trigram (`vedio` vs `video`).
|
||||
// Feed the scorer an additional indexed same-initial lane so it can
|
||||
// recover those candidates without scanning the full node table.
|
||||
// Trigram rank does not know that a name *starts* with the query, and a
|
||||
// short substitution can destroy every trigram outright (`vedio` vs
|
||||
// `video`). Two indexed lanes cover both without scanning the node
|
||||
// table: whole-query prefix first, then same-initial.
|
||||
if !terms.is_empty()
|
||||
&& let Some(first) = query.chars().next()
|
||||
{
|
||||
let prefix = format!("{}%", like_escape(&first.to_string()));
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT node_json, uid FROM nodes
|
||||
WHERE name COLLATE NOCASE LIKE ?1 ESCAPE '\\'
|
||||
AND trashed = 0 AND node_json IS NOT NULL
|
||||
ORDER BY name COLLATE NOCASE LIMIT ?2",
|
||||
)?;
|
||||
let fallback =
|
||||
collect_pairs(stmt.query_map(params![prefix, lane_limit as i64], pair)?)?;
|
||||
for row in fallback {
|
||||
let mut extra = Vec::new();
|
||||
for pattern in [
|
||||
format!("{}%", like_escape(query)),
|
||||
format!("{}%", like_escape(&first.to_string())),
|
||||
] {
|
||||
extra.extend(collect_pairs(
|
||||
stmt.query_map(params![pattern, lane_limit as i64], pair)?,
|
||||
)?);
|
||||
}
|
||||
let trigram = std::mem::take(&mut rows);
|
||||
for row in extra.into_iter().chain(trigram) {
|
||||
if !rows.iter().any(|(_, uid)| uid == &row.1) {
|
||||
rows.push(row);
|
||||
}
|
||||
@@ -556,12 +564,18 @@ fn upsert_node_tx(tx: &Transaction<'_>, node: &Node) -> Result<()> {
|
||||
)?;
|
||||
let mut affected = vec![rowid];
|
||||
if node.is_folder() {
|
||||
// The depth cap is a liveness guard, not a policy: `UNION ALL` over a
|
||||
// parent cycle (a's parent is b, b's parent is a — corrupt data, but the
|
||||
// API can hand it to us) never terminates, and this runs inside the
|
||||
// write transaction that holds the daemon's only SQLite connection.
|
||||
// Real Drive trees are nowhere near this deep.
|
||||
let mut stmt = tx.prepare(
|
||||
"WITH RECURSIVE descendants(rowid, uid) AS (
|
||||
SELECT rowid, uid FROM nodes WHERE parent_uid = ?1
|
||||
"WITH RECURSIVE descendants(rowid, uid, depth) AS (
|
||||
SELECT rowid, uid, 0 FROM nodes WHERE parent_uid = ?1
|
||||
UNION ALL
|
||||
SELECT n.rowid, n.uid FROM nodes n
|
||||
SELECT n.rowid, n.uid, d.depth + 1 FROM nodes n
|
||||
JOIN descendants d ON n.parent_uid = d.uid
|
||||
WHERE d.depth < 256
|
||||
) SELECT rowid FROM descendants",
|
||||
)?;
|
||||
for descendant in stmt.query_map(params![uid], |row| row.get(0))? {
|
||||
@@ -603,13 +617,27 @@ fn direct_child_uids_tx(tx: &Transaction<'_>, parent: &str) -> Result<Vec<String
|
||||
Ok(uids)
|
||||
}
|
||||
|
||||
/// Whether a node belongs in the search index: it exists, and nothing on the
|
||||
/// way up to the top of its cached chain is trashed.
|
||||
///
|
||||
/// The chain does *not* have to reach a `parent_uid IS NULL` row. Only the My
|
||||
/// Files root is stored that way; a device folder's root lives in `device` /
|
||||
/// `sync_folder` and never gets a `nodes` row, so requiring a null-parent
|
||||
/// ancestor silently excluded every device-folder subtree from search — 29% of
|
||||
/// the nodes on the account this was found on. A subtree whose topmost cached
|
||||
/// row has an uncached parent is ordinary, reachable data.
|
||||
///
|
||||
/// What is still excluded is a *cycle*: the walk's own guard stops it, but
|
||||
/// [`path_of`] has no such guard, so an indexed cycle would hang a search. A
|
||||
/// clean chain ends at a row whose parent is null or simply not cached; a cycle
|
||||
/// ends at one whose parent is a row we have already visited.
|
||||
fn node_is_indexable_tx(tx: &Transaction<'_>, uid: &str) -> Result<bool> {
|
||||
let indexable: i64 = tx.query_row(
|
||||
"WITH RECURSIVE ancestors(uid, parent_uid, trashed, path) AS (
|
||||
SELECT uid, parent_uid, trashed, char(31) || uid || char(31)
|
||||
"WITH RECURSIVE ancestors(uid, parent_uid, trashed, depth, path) AS (
|
||||
SELECT uid, parent_uid, trashed, 0, char(31) || uid || char(31)
|
||||
FROM nodes WHERE uid = ?1
|
||||
UNION ALL
|
||||
SELECT n.uid, n.parent_uid, n.trashed,
|
||||
SELECT n.uid, n.parent_uid, n.trashed, a.depth + 1,
|
||||
a.path || n.uid || char(31)
|
||||
FROM ancestors a JOIN nodes n ON n.uid = a.parent_uid
|
||||
WHERE instr(a.path, char(31) || n.uid || char(31)) = 0
|
||||
@@ -617,7 +645,12 @@ fn node_is_indexable_tx(tx: &Transaction<'_>, uid: &str) -> Result<bool> {
|
||||
SELECT CASE
|
||||
WHEN COUNT(*) = 0 THEN 0
|
||||
WHEN MAX(trashed) != 0 THEN 0
|
||||
WHEN MAX(CASE WHEN parent_uid IS NULL THEN 1 ELSE 0 END) = 0 THEN 0
|
||||
WHEN EXISTS (
|
||||
SELECT 1 FROM ancestors a
|
||||
WHERE a.depth = (SELECT MAX(depth) FROM ancestors)
|
||||
AND a.parent_uid IS NOT NULL
|
||||
AND EXISTS (SELECT 1 FROM nodes p WHERE p.uid = a.parent_uid)
|
||||
) THEN 0
|
||||
ELSE 1
|
||||
END
|
||||
FROM ancestors",
|
||||
|
||||
@@ -6,6 +6,18 @@ use rusqlite::{OptionalExtension, params};
|
||||
use super::Db;
|
||||
use crate::Result;
|
||||
|
||||
/// One row of [`Db::pin_list`]. `recursive` is pin *policy* — whether the whole
|
||||
/// subtree is kept — while `is_dir` is the node's kind as the node cache knows
|
||||
/// it, or `None` for a pin whose node is not cached. Reading the former as the
|
||||
/// latter is what made a non-recursively pinned folder render as a file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PinRow {
|
||||
pub uid: String,
|
||||
pub path: String,
|
||||
pub recursive: bool,
|
||||
pub is_dir: Option<bool>,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn pin_add(&self, uid: &str, path: &str, recursive: bool) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
@@ -25,16 +37,23 @@ impl Db {
|
||||
Ok(n > 0)
|
||||
}
|
||||
|
||||
/// Every directly-pinned entry `(uid, path, recursive)`, ordered by uid.
|
||||
pub fn pin_list(&self) -> Result<Vec<(String, String, bool)>> {
|
||||
/// Every directly-pinned entry, ordered by uid.
|
||||
pub fn pin_list(&self) -> Result<Vec<PinRow>> {
|
||||
let conn = self.conn.lock();
|
||||
let mut stmt = conn.prepare("SELECT uid, path, recursive FROM pins ORDER BY uid")?;
|
||||
// `recursive` is pin policy; the node's kind comes from `nodes`, and is
|
||||
// NULL for a pin whose node was never cached.
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT p.uid, p.path, p.recursive, n.is_dir
|
||||
FROM pins p LEFT JOIN nodes n ON n.uid = p.uid
|
||||
ORDER BY p.uid",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, i64>(2)? != 0,
|
||||
))
|
||||
Ok(PinRow {
|
||||
uid: r.get(0)?,
|
||||
path: r.get(1)?,
|
||||
recursive: r.get::<_, i64>(2)? != 0,
|
||||
is_dir: r.get::<_, Option<i64>>(3)?.map(|is_dir| is_dir != 0),
|
||||
})
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
for r in rows {
|
||||
|
||||
@@ -989,6 +989,62 @@ fn search_excludes_trashed_and_respects_limit() {
|
||||
assert_eq!(db.search("alph", 1).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
/// A device folder's root is stored in `device`/`sync_folder`, never in
|
||||
/// `nodes`, so its children's `parent_uid` points at a row that does not exist.
|
||||
/// Requiring the ancestor walk to reach a `parent_uid IS NULL` row therefore
|
||||
/// excluded every device-folder subtree from search: 2,705 of 9,252 nodes on
|
||||
/// the account this was found on, including everything under `~/Downloads`.
|
||||
#[test]
|
||||
fn search_finds_nodes_below_an_uncached_parent() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
// "device-root" is deliberately never upserted.
|
||||
db.upsert_node(&folder("downloads", Some("device-root"), "Downloads"))
|
||||
.unwrap();
|
||||
db.upsert_node(&file("t", "downloads", "tickets.pdf", 1))
|
||||
.unwrap();
|
||||
|
||||
let hits = db.search("tickets", 10).unwrap();
|
||||
assert_eq!(hits.len(), 1, "a device folder's files must be searchable");
|
||||
assert_eq!(hits[0].path, "Downloads/tickets.pdf");
|
||||
}
|
||||
|
||||
/// The relaxed rule must not also start indexing trash: a node whose *parent*
|
||||
/// is trashed stays out even though the walk now terminates happily.
|
||||
#[test]
|
||||
fn search_excludes_a_node_under_a_trashed_ancestor() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
db.upsert_node(&folder("root", None, "My Files")).unwrap();
|
||||
let mut folder_gone = folder("boxed", Some("root"), "Boxed");
|
||||
folder_gone.trashed = true;
|
||||
db.upsert_node(&folder_gone).unwrap();
|
||||
db.upsert_node(&file("f1", "boxed", "buried.txt", 1))
|
||||
.unwrap();
|
||||
|
||||
assert!(db.search("buried", 10).unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// A parent cycle is corrupt data the API can still hand us. It must stay out
|
||||
/// of the index, and — because the short-query `LIKE` lane reads `nodes`
|
||||
/// directly and never consults the index — resolving one's path must terminate
|
||||
/// rather than spin inside the daemon's only SQLite connection.
|
||||
#[test]
|
||||
fn a_parent_cycle_is_unindexed_and_never_hangs_a_search() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
db.upsert_node(&folder("a", Some("b"), "Alphaville"))
|
||||
.unwrap();
|
||||
db.upsert_node(&folder("b", Some("a"), "Betamax")).unwrap();
|
||||
|
||||
// Index lane: the cycle is not indexed, so it cannot be found.
|
||||
assert!(db.search("alphaville", 10).unwrap().is_empty());
|
||||
assert!(db.search("betamax", 10).unwrap().is_empty());
|
||||
|
||||
// LIKE lane (below the trigram minimum): the rows are reachable, and what
|
||||
// matters is that resolving their paths returns at all.
|
||||
let hits = db.search("al", 10).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert!(hits[0].path.ends_with("Alphaville"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_short_query_like_fallback() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
@@ -2472,14 +2528,41 @@ fn pin_add_list_remove_roundtrip() {
|
||||
db.pin_add("vol~d", "docs", true).unwrap();
|
||||
let list = db.pin_list().unwrap();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!(list[0], ("vol~a".into(), "docs/a.txt".into(), false));
|
||||
assert_eq!(list[1], ("vol~d".into(), "docs".into(), true));
|
||||
// No `nodes` row for either pin, so the kind is unknown rather than guessed
|
||||
// from the recursive flag.
|
||||
assert_eq!(
|
||||
list[0],
|
||||
PinRow {
|
||||
uid: "vol~a".into(),
|
||||
path: "docs/a.txt".into(),
|
||||
recursive: false,
|
||||
is_dir: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
list[1],
|
||||
PinRow {
|
||||
uid: "vol~d".into(),
|
||||
path: "docs".into(),
|
||||
recursive: true,
|
||||
is_dir: None,
|
||||
}
|
||||
);
|
||||
|
||||
// Once the node is cached, the pin reports the real kind — a folder pinned
|
||||
// non-recursively must not look like a file.
|
||||
db.upsert_node(&folder("root", None, "My Files")).unwrap();
|
||||
db.upsert_node(&folder("d", Some("root"), "docs")).unwrap();
|
||||
db.pin_add("vol~d", "docs", false).unwrap();
|
||||
let list = db.pin_list().unwrap();
|
||||
assert!(!list[1].recursive, "pin policy stays non-recursive");
|
||||
assert_eq!(list[1].is_dir, Some(true), "but the node is still a folder");
|
||||
|
||||
// Re-pin refreshes path/flag, not a duplicate row.
|
||||
db.pin_add("vol~a", "moved/a.txt", false).unwrap();
|
||||
let list = db.pin_list().unwrap();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!(list[0].1, "moved/a.txt");
|
||||
assert_eq!(list[0].path, "moved/a.txt");
|
||||
|
||||
assert!(db.pin_remove("vol~a").unwrap());
|
||||
assert!(!db.pin_remove("vol~a").unwrap());
|
||||
|
||||
@@ -31,19 +31,32 @@ pub(super) fn like_escape(s: &str) -> String {
|
||||
.replace('_', "\\_")
|
||||
}
|
||||
|
||||
/// How deep the parent walk may go before it gives up. Real Drive trees are
|
||||
/// nowhere near this; a parent *cycle* is unbounded, and this query is on the
|
||||
/// path of every search result, including the `LIKE` lane that reads `nodes`
|
||||
/// directly and so never passed through the index's cycle check.
|
||||
const MAX_PATH_DEPTH: usize = 256;
|
||||
|
||||
/// Resolve a node's mountpoint-relative path by walking `parent_uid` to the
|
||||
/// root via a recursive CTE. The root (the node with no parent) is excluded, so
|
||||
/// a top-level file `report.pdf` yields `"report.pdf"`, not `"My Files/report.pdf"`.
|
||||
///
|
||||
/// A cycle in `parent_uid` is corrupt data the API can still hand us, and
|
||||
/// `UNION ALL` over one never terminates — the walk is therefore depth-capped
|
||||
/// and returns the truncated path rather than hanging the caller. That caller is
|
||||
/// usually a search serving a keystroke, holding the daemon's only SQLite
|
||||
/// connection.
|
||||
pub(super) fn path_of(conn: &Connection, uid: &str) -> Result<String> {
|
||||
let mut stmt = conn.prepare(
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"WITH RECURSIVE anc(uid, parent_uid, name, depth) AS (
|
||||
SELECT uid, parent_uid, name, 0 FROM nodes WHERE uid = ?1
|
||||
UNION ALL
|
||||
SELECT n.uid, n.parent_uid, n.name, anc.depth + 1
|
||||
FROM nodes n JOIN anc ON n.uid = anc.parent_uid
|
||||
WHERE anc.depth < {MAX_PATH_DEPTH}
|
||||
)
|
||||
SELECT name, parent_uid FROM anc ORDER BY depth DESC",
|
||||
)?;
|
||||
SELECT name, parent_uid FROM anc ORDER BY depth DESC"
|
||||
))?;
|
||||
let rows = stmt.query_map(params![uid], |r| {
|
||||
Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?))
|
||||
})?;
|
||||
|
||||
@@ -11,7 +11,9 @@ pub mod control;
|
||||
pub mod db;
|
||||
pub mod error;
|
||||
pub mod localindex;
|
||||
pub mod menu;
|
||||
pub mod mounts;
|
||||
pub mod opener;
|
||||
pub mod profile;
|
||||
pub mod sdkcache;
|
||||
pub mod search;
|
||||
|
||||
@@ -26,10 +26,20 @@ const SKIP_DIRS: &[&str] = &[
|
||||
"venv",
|
||||
".venv",
|
||||
"vendor",
|
||||
"dist",
|
||||
"dist-newstyle",
|
||||
"build",
|
||||
"Trash",
|
||||
];
|
||||
|
||||
/// Directory *paths* skipped when they end with one of these, for caches whose
|
||||
/// own name is too generic to blacklist (`mod`). The Go module cache was 63,399
|
||||
/// of the 110,187 entries indexed on the machine this was measured on — 58% of
|
||||
/// the index, crowding real files out of the bounded candidate pool the fuzzy
|
||||
/// scorer draws from. The other big dependency caches (`.cargo`, `.rustup`,
|
||||
/// `.gradle`, `.m2`) are already skipped by the hidden-file filter.
|
||||
const SKIP_PATH_SUFFIXES: &[&str] = &["go/pkg/mod"];
|
||||
|
||||
/// Hard cap on indexed entries, so a pathological home directory cannot grow the
|
||||
/// database without bound. Reaching it stops the walk early.
|
||||
const MAX_ENTRIES: usize = 400_000;
|
||||
@@ -90,7 +100,10 @@ pub fn scan(
|
||||
if excludes.iter().any(|e| path.starts_with(e)) {
|
||||
return false;
|
||||
}
|
||||
!matches!(entry.file_name().to_str(), Some(name) if SKIP_DIRS.contains(&name))
|
||||
if matches!(entry.file_name().to_str(), Some(name) if SKIP_DIRS.contains(&name)) {
|
||||
return false;
|
||||
}
|
||||
!is_skipped_path(path)
|
||||
});
|
||||
|
||||
let state = parking_lot::Mutex::new(SinkState {
|
||||
@@ -150,6 +163,17 @@ impl<F: FnMut(Vec<LocalEntry>)> SinkState<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is (or is inside) one of the [`SKIP_PATH_SUFFIXES`] caches.
|
||||
/// Matched on the path's own components so a directory merely *named* `mod`
|
||||
/// keeps being indexed.
|
||||
fn is_skipped_path(path: &Path) -> bool {
|
||||
let path = path.to_string_lossy();
|
||||
SKIP_PATH_SUFFIXES.iter().any(|suffix| {
|
||||
path.strip_suffix(suffix)
|
||||
.is_some_and(|head| head.is_empty() || head.ends_with('/'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert a walker entry into a [`LocalEntry`], reusing the metadata the walker
|
||||
/// already fetched. Entries with non-UTF-8 paths are dropped: the index (and the
|
||||
/// JSON wire format) is UTF-8 only.
|
||||
@@ -221,4 +245,27 @@ mod tests {
|
||||
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
/// The Go module cache is the single largest source of index noise on a
|
||||
/// developer's machine (58% of the entries on the one this was measured
|
||||
/// on), and it cannot be pruned by directory name: `mod` is far too
|
||||
/// common a name to blacklist outright.
|
||||
#[test]
|
||||
fn the_go_module_cache_is_pruned_but_a_plain_mod_dir_is_not() {
|
||||
let tmp = std::env::temp_dir().join(format!("pdfs-scan-gomod-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
std::fs::create_dir_all(tmp.join("go/pkg/mod/example.com/lib")).unwrap();
|
||||
std::fs::create_dir_all(tmp.join("kernel/mod")).unwrap();
|
||||
std::fs::write(tmp.join("go/pkg/mod/example.com/lib/vendored.go"), b"x").unwrap();
|
||||
std::fs::write(tmp.join("kernel/mod/mine.conf"), b"x").unwrap();
|
||||
|
||||
let mut got = Vec::new();
|
||||
scan(std::slice::from_ref(&tmp), &[], |batch| got.extend(batch));
|
||||
|
||||
let names: Vec<&str> = got.iter().map(|e| e.name.as_str()).collect();
|
||||
assert!(!names.contains(&"vendored.go"), "{names:?}");
|
||||
assert!(names.contains(&"mine.conf"), "{names:?}");
|
||||
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
//! Driving an external dmenu-style launcher (fuzzel, rofi, wofi, …).
|
||||
//!
|
||||
//! `pdfs-prompt` ships its own GTK HUD, but on a tiling-WM desktop the user
|
||||
//! already has a launcher bound to a key, themed to match everything else. This
|
||||
//! module lets the prompt borrow it: entries go out on the child's stdin, the
|
||||
//! chosen line comes back on stdout.
|
||||
//!
|
||||
//! Two things vary between launchers and are the only reasons this is not four
|
||||
//! lines of `Command`:
|
||||
//!
|
||||
//! * the flag that turns on filter mode and the one that sets the prompt text;
|
||||
//! * icon support, which fuzzel and rofi both spell `text\0icon\x1fNAME` and
|
||||
//! everything else would render as literal garbage.
|
||||
//!
|
||||
//! Selection is matched back by label rather than by index, because the one
|
||||
//! feature no launcher agrees on is index output. A line that matches nothing is
|
||||
//! the user's own typing — [`MenuChoice::Custom`] — which is what makes
|
||||
//! type-then-search work at all.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
/// Separates the label from its icon name in the fuzzel/rofi protocol.
|
||||
const ICON_SEPARATOR: &str = "\0icon\x1f";
|
||||
|
||||
/// Launchers we know how to invoke, most-preferred first:
|
||||
/// `(program, filter-mode args, prompt flag, icon protocol)`.
|
||||
///
|
||||
/// The prompt flag is written as it is passed: fuzzel wants `--prompt=TEXT` as
|
||||
/// one argument, the rest take the text as a separate one.
|
||||
const KNOWN_MENUS: [MenuFlavor; 6] = [
|
||||
MenuFlavor {
|
||||
program: "fuzzel",
|
||||
mode: &["--dmenu"],
|
||||
prompt: PromptFlag::Joined("--prompt="),
|
||||
icons: true,
|
||||
},
|
||||
MenuFlavor {
|
||||
program: "rofi",
|
||||
mode: &["-dmenu"],
|
||||
prompt: PromptFlag::Separate("-p"),
|
||||
icons: true,
|
||||
},
|
||||
MenuFlavor {
|
||||
program: "wofi",
|
||||
mode: &["--dmenu"],
|
||||
prompt: PromptFlag::Separate("--prompt"),
|
||||
icons: false,
|
||||
},
|
||||
MenuFlavor {
|
||||
program: "tofi",
|
||||
mode: &[],
|
||||
prompt: PromptFlag::Joined("--prompt-text="),
|
||||
icons: false,
|
||||
},
|
||||
MenuFlavor {
|
||||
program: "bemenu",
|
||||
mode: &[],
|
||||
prompt: PromptFlag::Separate("-p"),
|
||||
icons: false,
|
||||
},
|
||||
MenuFlavor {
|
||||
program: "dmenu",
|
||||
mode: &[],
|
||||
prompt: PromptFlag::Separate("-p"),
|
||||
icons: false,
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum PromptFlag {
|
||||
/// `--prompt=TEXT`
|
||||
Joined(&'static str),
|
||||
/// `-p TEXT`
|
||||
Separate(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct MenuFlavor {
|
||||
program: &'static str,
|
||||
mode: &'static [&'static str],
|
||||
prompt: PromptFlag,
|
||||
icons: bool,
|
||||
}
|
||||
|
||||
/// Prompt behaviour from `config.json`, under `prompt`.
|
||||
///
|
||||
/// ```json
|
||||
/// "prompt": { "menu": ["fuzzel", "--dmenu", "--width=60"], "menu_limit": 40 }
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PromptConfig {
|
||||
/// Which front end `pdfs-prompt` uses when invoked with no mode flag, so a
|
||||
/// desktop shortcut does not have to be re-bound to switch. `None` is
|
||||
/// [`PromptMode::Gtk`], the built-in HUD.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mode: Option<PromptMode>,
|
||||
/// Launcher argv for `pdfs-prompt --dmenu`. Unset means "find one" — see
|
||||
/// [`resolve_menu`]. A `{prompt}` token anywhere in the argv is replaced by
|
||||
/// the prompt text; without one the launcher's own prompt flag is appended.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub menu: Option<Vec<String>>,
|
||||
/// How many results to feed the launcher. Unset means
|
||||
/// [`DEFAULT_MENU_LIMIT`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub menu_limit: Option<usize>,
|
||||
/// Show icons when the launcher understands them. Defaults to true; set
|
||||
/// false for a launcher that advertises support but is themed without them.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub menu_icons: Option<bool>,
|
||||
}
|
||||
|
||||
/// Which front end the prompt presents.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PromptMode {
|
||||
/// The built-in GTK HUD.
|
||||
#[default]
|
||||
Gtk,
|
||||
/// The user's own launcher, driven over stdin/stdout.
|
||||
Dmenu,
|
||||
}
|
||||
|
||||
/// Rows an external launcher can show without becoming a scroll exercise. Larger
|
||||
/// than the GTK prompt's cap because filtering happens launcher-side.
|
||||
pub const DEFAULT_MENU_LIMIT: usize = 50;
|
||||
|
||||
impl PromptConfig {
|
||||
pub fn resolved_mode(&self) -> PromptMode {
|
||||
self.mode.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn resolved_menu_limit(&self) -> usize {
|
||||
self.menu_limit.unwrap_or(DEFAULT_MENU_LIMIT)
|
||||
}
|
||||
|
||||
pub fn resolved_menu_icons(&self) -> bool {
|
||||
self.menu_icons.unwrap_or(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// One line offered to the launcher.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MenuItem {
|
||||
/// What the user sees, and what identifies the choice on the way back.
|
||||
pub label: String,
|
||||
/// Icon theme name, used only by launchers that support the protocol.
|
||||
pub icon: Option<String>,
|
||||
}
|
||||
|
||||
impl MenuItem {
|
||||
pub fn new(label: impl Into<String>, icon: Option<String>) -> Self {
|
||||
Self {
|
||||
label: label.into(),
|
||||
icon,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What came back from the launcher.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MenuChoice {
|
||||
/// Index into the items that were passed in.
|
||||
Item(usize),
|
||||
/// Text the user typed that matched no item — treat it as a query.
|
||||
Custom(String),
|
||||
/// Escape, or an empty selection.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// The launcher to run: the configured one, or the first [`KNOWN_MENUS`] entry
|
||||
/// on `PATH`. Returns the argv as it should be spawned, filter-mode flags
|
||||
/// included.
|
||||
pub fn resolve_menu(configured: Option<&Vec<String>>) -> Option<Vec<String>> {
|
||||
if let Some(argv) = configured.filter(|argv| !argv.is_empty()) {
|
||||
return Some(argv.clone());
|
||||
}
|
||||
let flavor = KNOWN_MENUS.iter().find(|f| on_path(f.program))?;
|
||||
let mut argv = vec![flavor.program.to_string()];
|
||||
argv.extend(flavor.mode.iter().map(|f| (*f).to_string()));
|
||||
Some(argv)
|
||||
}
|
||||
|
||||
/// Show `items` in the launcher named by `argv` and wait for a choice.
|
||||
///
|
||||
/// Blocking by design: the caller is a one-shot CLI invocation whose entire job
|
||||
/// is this round-trip.
|
||||
pub fn run(argv: &[String], prompt: &str, items: &[MenuItem]) -> Result<MenuChoice> {
|
||||
let argv = with_prompt(argv, prompt);
|
||||
let Some((program, args)) = argv.split_first() else {
|
||||
return Err(Error::Other("no launcher command configured".into()));
|
||||
};
|
||||
let icons = supports_icons(program);
|
||||
|
||||
let mut child = Command::new(program)
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| Error::Other(format!("cannot run launcher {program}: {e}")))?;
|
||||
|
||||
// Write on a worker: a launcher that starts reading only after it maps its
|
||||
// window would otherwise deadlock against a full pipe buffer.
|
||||
let payload = render(items, icons);
|
||||
let mut stdin = child
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| Error::Other("launcher stdin unavailable".into()))?;
|
||||
let writer = std::thread::spawn(move || {
|
||||
let _ = stdin.write_all(payload.as_bytes());
|
||||
let _ = stdin.flush();
|
||||
});
|
||||
|
||||
let mut selected = String::new();
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
// Only the first line matters; multi-select is not a thing here, and a
|
||||
// launcher that emits more must not leave us blocked on a full pipe.
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if selected.is_empty() {
|
||||
selected = line.trim_end_matches('\n').to_string();
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
}
|
||||
let _ = child.wait();
|
||||
let _ = writer.join();
|
||||
|
||||
Ok(interpret(&selected, items))
|
||||
}
|
||||
|
||||
/// Map the launcher's output back to a choice. Exposed for tests; the ambiguity
|
||||
/// it resolves (label vs. free text) is the whole contract with the launcher.
|
||||
fn interpret(selected: &str, items: &[MenuItem]) -> MenuChoice {
|
||||
// Some launchers echo the icon protocol back verbatim.
|
||||
let selected = selected
|
||||
.split(ICON_SEPARATOR)
|
||||
.next()
|
||||
.unwrap_or(selected)
|
||||
.trim_end();
|
||||
if selected.is_empty() {
|
||||
return MenuChoice::Cancelled;
|
||||
}
|
||||
match items.iter().position(|item| item.label == selected) {
|
||||
Some(index) => MenuChoice::Item(index),
|
||||
None => MenuChoice::Custom(selected.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stdin payload. Labels are stripped of newlines rather than escaped —
|
||||
/// there is no escape in this protocol, and a file name with a newline in it
|
||||
/// would otherwise become two entries.
|
||||
fn render(items: &[MenuItem], icons: bool) -> String {
|
||||
let mut out = String::new();
|
||||
for item in items {
|
||||
let label = item.label.replace(['\n', '\r'], " ");
|
||||
out.push_str(&label);
|
||||
if icons && let Some(icon) = &item.icon {
|
||||
out.push_str(ICON_SEPARATOR);
|
||||
out.push_str(icon);
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Add the prompt text: substituted for `{prompt}` if the user placed one,
|
||||
/// otherwise appended using the launcher's own flag. An unrecognised launcher
|
||||
/// gets no prompt rather than a guessed flag that might not parse.
|
||||
fn with_prompt(argv: &[String], prompt: &str) -> Vec<String> {
|
||||
if argv.iter().any(|arg| arg.contains("{prompt}")) {
|
||||
return argv
|
||||
.iter()
|
||||
.map(|arg| arg.replace("{prompt}", prompt))
|
||||
.collect();
|
||||
}
|
||||
let mut argv = argv.to_vec();
|
||||
if prompt.is_empty() {
|
||||
return argv;
|
||||
}
|
||||
if let Some(flavor) = argv.first().and_then(|program| flavor_of(program)) {
|
||||
match flavor.prompt {
|
||||
PromptFlag::Joined(flag) => argv.push(format!("{flag}{prompt}")),
|
||||
PromptFlag::Separate(flag) => {
|
||||
argv.push(flag.to_string());
|
||||
argv.push(prompt.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
argv
|
||||
}
|
||||
|
||||
fn supports_icons(program: &str) -> bool {
|
||||
flavor_of(program).is_some_and(|flavor| flavor.icons)
|
||||
}
|
||||
|
||||
fn flavor_of(program: &str) -> Option<&'static MenuFlavor> {
|
||||
let base = Path::new(program).file_name()?.to_str()?;
|
||||
KNOWN_MENUS.iter().find(|flavor| flavor.program == base)
|
||||
}
|
||||
|
||||
fn on_path(program: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
};
|
||||
std::env::split_paths(&path).any(|dir| dir.join(program).is_file())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn items() -> Vec<MenuItem> {
|
||||
vec![
|
||||
MenuItem::new(
|
||||
"notes.md · My files / Docs",
|
||||
Some("text-x-generic".into()),
|
||||
),
|
||||
MenuItem::new("photo.png · Home / Pictures", None),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_line_is_an_item_and_anything_else_is_a_query() {
|
||||
let items = items();
|
||||
assert_eq!(
|
||||
interpret("notes.md · My files / Docs", &items),
|
||||
MenuChoice::Item(0)
|
||||
);
|
||||
assert_eq!(
|
||||
interpret("invoice", &items),
|
||||
MenuChoice::Custom("invoice".into())
|
||||
);
|
||||
assert_eq!(interpret("", &items), MenuChoice::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_echoed_icon_field_does_not_break_the_match() {
|
||||
let items = items();
|
||||
assert_eq!(
|
||||
interpret(
|
||||
"notes.md · My files / Docs\0icon\x1ftext-x-generic",
|
||||
&items
|
||||
),
|
||||
MenuChoice::Item(0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icons_are_only_rendered_for_launchers_that_understand_them() {
|
||||
let items = items();
|
||||
assert_eq!(
|
||||
render(&items, true),
|
||||
"notes.md · My files / Docs\0icon\x1ftext-x-generic\nphoto.png · Home / Pictures\n"
|
||||
);
|
||||
assert_eq!(
|
||||
render(&items, false),
|
||||
"notes.md · My files / Docs\nphoto.png · Home / Pictures\n"
|
||||
);
|
||||
assert!(supports_icons("fuzzel"));
|
||||
assert!(supports_icons("/usr/bin/rofi"));
|
||||
assert!(!supports_icons("wofi"));
|
||||
assert!(!supports_icons("mystery-menu"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_with_a_newline_stays_one_entry() {
|
||||
let sneaky = vec![MenuItem::new("two\nlines.txt", None)];
|
||||
assert_eq!(render(&sneaky, false), "two lines.txt\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_uses_each_launchers_own_flag() {
|
||||
assert_eq!(
|
||||
with_prompt(&["fuzzel".into(), "--dmenu".into()], "Drive"),
|
||||
vec!["fuzzel", "--dmenu", "--prompt=Drive"]
|
||||
);
|
||||
assert_eq!(
|
||||
with_prompt(&["rofi".into(), "-dmenu".into()], "Drive"),
|
||||
vec!["rofi", "-dmenu", "-p", "Drive"]
|
||||
);
|
||||
// Unknown launcher: no guessed flag.
|
||||
assert_eq!(
|
||||
with_prompt(&["mystery-menu".into()], "Drive"),
|
||||
vec!["mystery-menu"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_placeholder_wins_over_the_flag() {
|
||||
assert_eq!(
|
||||
with_prompt(
|
||||
&[
|
||||
"rofi".into(),
|
||||
"-dmenu".into(),
|
||||
"-p".into(),
|
||||
"{prompt} >".into()
|
||||
],
|
||||
"Drive"
|
||||
),
|
||||
vec!["rofi", "-dmenu", "-p", "Drive >"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_launcher_is_used_verbatim() {
|
||||
let configured = vec!["my-menu".to_string(), "--pick".to_string()];
|
||||
assert_eq!(resolve_menu(Some(&configured)), Some(configured.clone()));
|
||||
// An empty list is "not configured", not "run nothing".
|
||||
assert_eq!(
|
||||
resolve_menu(Some(&Vec::new())),
|
||||
resolve_menu(None),
|
||||
"an empty menu list must fall back to detection"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,599 @@
|
||||
//! How a file chosen in the prompt (or the browser) is actually opened.
|
||||
//!
|
||||
//! The default is `xdg-open`, which routes through the desktop's MIME
|
||||
//! associations. That is the right answer for a GNOME session and the wrong one
|
||||
//! for a tiling-WM setup where "open a text file" means "run `nvim` inside my
|
||||
//! terminal" — there is no desktop file for that, and pointing `xdg-open` at a
|
||||
//! terminal editor globally breaks every graphical caller.
|
||||
//!
|
||||
//! So the rules live in `config.json` under `open_with`: an ordered list of
|
||||
//! name/class patterns mapped to argv, each optionally wrapped in a terminal.
|
||||
//! First match wins; anything unmatched falls through to `default` (itself
|
||||
//! `xdg-open` unless overridden). Nothing here is required — an absent
|
||||
//! `open_with` reproduces the previous behaviour exactly.
|
||||
//!
|
||||
//! ```json
|
||||
//! "open_with": {
|
||||
//! "terminal": ["alacritty", "-e"],
|
||||
//! "rules": [
|
||||
//! { "match": ["@text", "*.rs", "*.toml"], "command": ["nvim"], "terminal": true },
|
||||
//! { "match": ["*.png"], "command": ["imv"] }
|
||||
//! ]
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Environment override for the terminal used by `"terminal": true` rules.
|
||||
/// Checked before `$TERMINAL` so a support case can redirect it without editing
|
||||
/// config.
|
||||
pub const TERMINAL_ENV: &str = "PDFS_TERMINAL";
|
||||
|
||||
/// Terminals we know how to hand a command line to, most-preferred first, with
|
||||
/// the argument that means "run this, don't parse it as options". `kitty` and
|
||||
/// `wezterm start --` take the command positionally.
|
||||
const KNOWN_TERMINALS: [(&str, &[&str]); 11] = [
|
||||
("alacritty", &["-e"]),
|
||||
("foot", &["-e"]),
|
||||
("kitty", &[]),
|
||||
("ghostty", &["-e"]),
|
||||
("wezterm", &["start", "--"]),
|
||||
("gnome-terminal", &["--"]),
|
||||
("konsole", &["-e"]),
|
||||
("xfce4-terminal", &["-x"]),
|
||||
("urxvt", &["-e"]),
|
||||
("st", &["-e"]),
|
||||
("xterm", &["-e"]),
|
||||
];
|
||||
|
||||
/// The opener policy as it appears in `config.json`.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OpenWith {
|
||||
/// Terminal argv used by rules with `"terminal": true`, e.g.
|
||||
/// `["alacritty", "-e"]`. Unset means "resolve one" — see
|
||||
/// [`resolve_terminal`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub terminal: Option<Vec<String>>,
|
||||
/// What to run when no rule matches. Unset means `xdg-open`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub default: Option<Vec<String>>,
|
||||
/// Ordered; first match wins.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub rules: Vec<OpenRule>,
|
||||
}
|
||||
|
||||
/// One `pattern set -> command` mapping.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OpenRule {
|
||||
/// Patterns this rule answers to. Either a shell-style glob against the file
|
||||
/// name (`*.md`, `notes-*.txt`) or one of the classes `@dir`, `@text`,
|
||||
/// `@document`, `@image`, `@media`, `@any`. Matching is case-insensitive.
|
||||
#[serde(rename = "match", default)]
|
||||
pub patterns: Vec<String>,
|
||||
/// argv to run. A `{}` token is replaced by the path; without one the path
|
||||
/// is appended. `$VAR`/`${VAR}` tokens expand from the environment, so
|
||||
/// `["$EDITOR"]` follows the user's editor.
|
||||
#[serde(default)]
|
||||
pub command: Vec<String>,
|
||||
/// Wrap [`command`](Self::command) in the terminal emulator.
|
||||
#[serde(default)]
|
||||
pub terminal: bool,
|
||||
}
|
||||
|
||||
impl OpenWith {
|
||||
/// The argv that opens `path`, terminal wrapping included. Never fails: an
|
||||
/// unmatched path — or a rule whose terminal cannot be resolved — degrades
|
||||
/// to the default opener rather than doing nothing.
|
||||
pub fn command_for(&self, path: &Path, is_dir: bool) -> Vec<String> {
|
||||
let name = path
|
||||
.file_name()
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
self.command_for_named(path, &name, is_dir)
|
||||
}
|
||||
|
||||
/// [`command_for`](Self::command_for) with the rules matched against `name`
|
||||
/// instead of the last component of `path`.
|
||||
///
|
||||
/// A materialised Drive file lives in the content cache under its content
|
||||
/// hash — no extension, no original name — so matching the on-disk path
|
||||
/// classifies every download as "unknown" and hands it to `xdg-open`, which
|
||||
/// sniffs the bytes and picks whatever claims `text/plain` (LibreOffice, for
|
||||
/// a Markdown file). The rules are about *what the user opened*, so the
|
||||
/// caller passes that name and the argv still gets the real path.
|
||||
pub fn command_for_named(&self, path: &Path, name: &str, is_dir: bool) -> Vec<String> {
|
||||
for rule in &self.rules {
|
||||
if rule.command.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !rule.patterns.iter().any(|p| matches(p, name, is_dir)) {
|
||||
continue;
|
||||
}
|
||||
let argv = expand(&rule.command, path);
|
||||
if !rule.terminal {
|
||||
return argv;
|
||||
}
|
||||
match self.terminal_argv() {
|
||||
Some(mut terminal) => {
|
||||
terminal.extend(argv);
|
||||
return terminal;
|
||||
}
|
||||
// A terminal rule with no terminal to run it in would silently
|
||||
// launch a TUI with no tty. Fall through to the desktop instead.
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"no terminal found for a terminal open rule; using the default opener"
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fallback = self
|
||||
.default
|
||||
.clone()
|
||||
.unwrap_or_else(|| vec!["xdg-open".to_string()]);
|
||||
expand(&fallback, path)
|
||||
}
|
||||
|
||||
/// The configured terminal, or a resolved one.
|
||||
fn terminal_argv(&self) -> Option<Vec<String>> {
|
||||
match &self.terminal {
|
||||
Some(argv) if !argv.is_empty() => Some(argv.clone()),
|
||||
_ => resolve_terminal(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Launch `path` under `policy`. Fire-and-forget: the child outlives us, and a
|
||||
/// spawn failure is logged rather than propagated — every caller is a UI action
|
||||
/// with nowhere useful to report to.
|
||||
pub fn open(policy: &OpenWith, path: &Path, is_dir: bool) {
|
||||
let argv = policy.command_for(path, is_dir);
|
||||
spawn(&argv, path);
|
||||
}
|
||||
|
||||
/// [`open`] for a path whose own file name says nothing about its type — see
|
||||
/// [`OpenWith::command_for_named`].
|
||||
pub fn open_named(policy: &OpenWith, path: &Path, name: &str, is_dir: bool) {
|
||||
let argv = policy.command_for_named(path, name, is_dir);
|
||||
spawn(&argv, path);
|
||||
}
|
||||
|
||||
fn spawn(argv: &[String], path: &Path) {
|
||||
let Some((program, args)) = argv.split_first() else {
|
||||
return;
|
||||
};
|
||||
tracing::info!(path = %path.display(), command = ?argv, "opening");
|
||||
if let Err(e) = Command::new(program).args(args).spawn() {
|
||||
tracing::error!(command = ?argv, "open failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`open`] with the policy from the user's `config.json`, read once per
|
||||
/// process. For callers that open the occasional path and have no reason to
|
||||
/// carry a policy around; long-lived windows should hold their own copy.
|
||||
pub fn open_default(path: &Path, is_dir: bool) {
|
||||
open(default_policy(), path, is_dir);
|
||||
}
|
||||
|
||||
/// [`open_default`] matching the rules against `name` — see
|
||||
/// [`OpenWith::command_for_named`].
|
||||
pub fn open_default_named(path: &Path, name: &str, is_dir: bool) {
|
||||
open_named(default_policy(), path, name, is_dir);
|
||||
}
|
||||
|
||||
fn default_policy() -> &'static OpenWith {
|
||||
static POLICY: std::sync::OnceLock<OpenWith> = std::sync::OnceLock::new();
|
||||
POLICY.get_or_init(|| {
|
||||
crate::config::AppDirs::new()
|
||||
.map(|dirs| dirs.load_config().resolved_open_with())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
/// `$PDFS_TERMINAL`, then `$TERMINAL`, then the first [`KNOWN_TERMINALS`] entry
|
||||
/// on `PATH`. An env value may be a full command line (`"foot -e"`), in which
|
||||
/// case it is used verbatim; a bare program name gains that terminal's "run
|
||||
/// this" argument so `TERMINAL=alacritty` does the obvious thing.
|
||||
pub fn resolve_terminal() -> Option<Vec<String>> {
|
||||
for key in [TERMINAL_ENV, "TERMINAL"] {
|
||||
let Ok(value) = std::env::var(key) else {
|
||||
continue;
|
||||
};
|
||||
let argv: Vec<String> = value.split_whitespace().map(str::to_string).collect();
|
||||
match argv.len() {
|
||||
0 => continue,
|
||||
1 => return Some(with_exec_flag(&argv[0])),
|
||||
_ => return Some(argv),
|
||||
}
|
||||
}
|
||||
|
||||
KNOWN_TERMINALS
|
||||
.iter()
|
||||
.find(|(program, _)| on_path(program))
|
||||
.map(|(program, _)| with_exec_flag(program))
|
||||
}
|
||||
|
||||
/// A bare terminal name plus whatever it needs before a command.
|
||||
fn with_exec_flag(program: &str) -> Vec<String> {
|
||||
let base = Path::new(program)
|
||||
.file_name()
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or(program);
|
||||
let mut argv = vec![program.to_string()];
|
||||
let flags = KNOWN_TERMINALS
|
||||
.iter()
|
||||
.find(|(known, _)| *known == base)
|
||||
.map_or(&["-e"][..], |(_, flags)| *flags);
|
||||
argv.extend(flags.iter().map(|f| (*f).to_string()));
|
||||
argv
|
||||
}
|
||||
|
||||
fn on_path(program: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
};
|
||||
std::env::split_paths(&path).any(|dir| dir.join(program).is_file())
|
||||
}
|
||||
|
||||
/// Substitute `{}` (or append) the path, and expand `$VAR` tokens. Tokens that
|
||||
/// expand to nothing are dropped, so `["$EDITOR"]` with no `EDITOR` set leaves
|
||||
/// an empty argv and falls back at the call site.
|
||||
fn expand(argv: &[String], path: &Path) -> Vec<String> {
|
||||
let target = path.display().to_string();
|
||||
let mut out = Vec::with_capacity(argv.len() + 1);
|
||||
let mut substituted = false;
|
||||
for token in argv {
|
||||
if token.contains("{}") {
|
||||
out.push(token.replace("{}", &target));
|
||||
substituted = true;
|
||||
continue;
|
||||
}
|
||||
match expand_env(token) {
|
||||
Some(value) => out.push(value),
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return vec!["xdg-open".to_string(), target];
|
||||
}
|
||||
if !substituted {
|
||||
out.push(target);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `$VAR` / `${VAR}` for a whole token, `None` when the variable is unset or
|
||||
/// empty so the token drops out. A token that is not a variable reference is
|
||||
/// returned unchanged; this is deliberately not a shell — no word splitting, no
|
||||
/// quoting rules.
|
||||
fn expand_env(token: &str) -> Option<String> {
|
||||
let Some(name) = token
|
||||
.strip_prefix("${")
|
||||
.and_then(|rest| rest.strip_suffix('}'))
|
||||
.or_else(|| token.strip_prefix('$'))
|
||||
else {
|
||||
return Some(token.to_string());
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Some(token.to_string());
|
||||
}
|
||||
// Follow `$EDITOR`'s convention of preferring the graphical-capable one.
|
||||
let value = if name == "EDITOR" {
|
||||
std::env::var("VISUAL")
|
||||
.ok()
|
||||
.filter(|v| !v.is_empty())
|
||||
.or_else(|| std::env::var("EDITOR").ok())
|
||||
} else {
|
||||
std::env::var(name).ok()
|
||||
};
|
||||
value.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Whether `pattern` — a glob or an `@class` — matches this name.
|
||||
fn matches(pattern: &str, name: &str, is_dir: bool) -> bool {
|
||||
let name_lower = name.to_lowercase();
|
||||
match pattern.to_lowercase().as_str() {
|
||||
"@any" => true,
|
||||
"@dir" => is_dir,
|
||||
"@text" => !is_dir && class_text(&name_lower),
|
||||
"@document" => !is_dir && class_document(&name_lower),
|
||||
"@image" => !is_dir && class_image(&name_lower),
|
||||
"@media" => !is_dir && class_media(&name_lower),
|
||||
other if other.starts_with('@') => false,
|
||||
other => glob_match(other, &name_lower),
|
||||
}
|
||||
}
|
||||
|
||||
fn extension(name: &str) -> &str {
|
||||
Path::new(name)
|
||||
.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Plain-text-ish files a terminal editor is a sensible default for. Extensions
|
||||
/// only: the daemon's hits may name files that are not on this machine yet, so
|
||||
/// there is nothing to sniff.
|
||||
fn class_text(name: &str) -> bool {
|
||||
matches!(
|
||||
extension(name),
|
||||
"txt"
|
||||
| "md"
|
||||
| "markdown"
|
||||
| "rst"
|
||||
| "org"
|
||||
| "log"
|
||||
| "conf"
|
||||
| "cfg"
|
||||
| "ini"
|
||||
| "toml"
|
||||
| "yaml"
|
||||
| "yml"
|
||||
| "json"
|
||||
| "xml"
|
||||
| "csv"
|
||||
| "tsv"
|
||||
| "env"
|
||||
| "sh"
|
||||
| "bash"
|
||||
| "zsh"
|
||||
| "fish"
|
||||
| "rs"
|
||||
| "py"
|
||||
| "go"
|
||||
| "c"
|
||||
| "h"
|
||||
| "cpp"
|
||||
| "hpp"
|
||||
| "js"
|
||||
| "ts"
|
||||
| "tsx"
|
||||
| "jsx"
|
||||
| "css"
|
||||
| "html"
|
||||
| "sql"
|
||||
| "lua"
|
||||
| "vim"
|
||||
| "nix"
|
||||
| "patch"
|
||||
| "diff"
|
||||
) || name == "makefile"
|
||||
|| name == "dockerfile"
|
||||
}
|
||||
|
||||
fn class_document(name: &str) -> bool {
|
||||
matches!(
|
||||
extension(name),
|
||||
"pdf"
|
||||
| "doc"
|
||||
| "docx"
|
||||
| "odt"
|
||||
| "rtf"
|
||||
| "xls"
|
||||
| "xlsx"
|
||||
| "ods"
|
||||
| "ppt"
|
||||
| "pptx"
|
||||
| "odp"
|
||||
| "epub"
|
||||
) || class_text(name)
|
||||
}
|
||||
|
||||
fn class_image(name: &str) -> bool {
|
||||
matches!(
|
||||
extension(name),
|
||||
"png" | "jpg" | "jpeg" | "webp" | "gif" | "bmp" | "svg" | "avif" | "heic" | "tiff"
|
||||
)
|
||||
}
|
||||
|
||||
fn class_media(name: &str) -> bool {
|
||||
matches!(
|
||||
extension(name),
|
||||
"mp4"
|
||||
| "mkv"
|
||||
| "webm"
|
||||
| "mov"
|
||||
| "avi"
|
||||
| "mp3"
|
||||
| "flac"
|
||||
| "wav"
|
||||
| "ogg"
|
||||
| "opus"
|
||||
| "m4a"
|
||||
| "aac"
|
||||
)
|
||||
}
|
||||
|
||||
/// `*` and `?` globbing, no character classes and no path semantics — patterns
|
||||
/// are matched against a bare file name. Iterative with backtracking so a
|
||||
/// pathological pattern cannot blow the stack.
|
||||
fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
let pattern: Vec<char> = pattern.chars().collect();
|
||||
let name: Vec<char> = name.chars().collect();
|
||||
let (mut p, mut n) = (0usize, 0usize);
|
||||
// Where to resume if the current `*` turns out to have matched too little.
|
||||
let (mut star, mut resume) = (None, 0usize);
|
||||
|
||||
while n < name.len() {
|
||||
match pattern.get(p) {
|
||||
Some('*') => {
|
||||
star = Some(p);
|
||||
resume = n;
|
||||
p += 1;
|
||||
}
|
||||
Some('?') => {
|
||||
p += 1;
|
||||
n += 1;
|
||||
}
|
||||
Some(c) if *c == name[n] => {
|
||||
p += 1;
|
||||
n += 1;
|
||||
}
|
||||
_ => match star {
|
||||
Some(s) => {
|
||||
p = s + 1;
|
||||
resume += 1;
|
||||
n = resume;
|
||||
}
|
||||
None => return false,
|
||||
},
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|c| *c == '*')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rule(patterns: &[&str], command: &[&str], terminal: bool) -> OpenRule {
|
||||
OpenRule {
|
||||
patterns: patterns.iter().map(|p| (*p).to_string()).collect(),
|
||||
command: command.iter().map(|c| (*c).to_string()).collect(),
|
||||
terminal,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_blob_is_classified_by_the_name_it_was_opened_as() {
|
||||
let policy = OpenWith {
|
||||
terminal: Some(vec!["alacritty".into(), "-e".into()]),
|
||||
default: None,
|
||||
rules: vec![rule(&["@text"], &["nvim"], true)],
|
||||
};
|
||||
// What the daemon hands back: content-hash name, no extension. Matched
|
||||
// on its own it is "unknown" and would land in xdg-open's lap.
|
||||
let blob = Path::new("/home/me/.cache/proton-drive-linux/content/364d1d8cc8e6");
|
||||
assert_eq!(
|
||||
policy.command_for(blob, false),
|
||||
vec![
|
||||
"xdg-open",
|
||||
"/home/me/.cache/proton-drive-linux/content/364d1d8cc8e6"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
policy.command_for_named(blob, "ONBOARDING.md", false),
|
||||
vec![
|
||||
"alacritty",
|
||||
"-e",
|
||||
"nvim",
|
||||
"/home/me/.cache/proton-drive-linux/content/364d1d8cc8e6"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_policy_is_xdg_open() {
|
||||
let policy = OpenWith::default();
|
||||
assert_eq!(
|
||||
policy.command_for(Path::new("/tmp/a.md"), false),
|
||||
vec!["xdg-open".to_string(), "/tmp/a.md".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_terminal_rule_wraps_the_command() {
|
||||
let policy = OpenWith {
|
||||
terminal: Some(vec!["alacritty".into(), "-e".into()]),
|
||||
default: None,
|
||||
rules: vec![rule(&["@text"], &["nvim"], true)],
|
||||
};
|
||||
assert_eq!(
|
||||
policy.command_for(Path::new("/tmp/notes.md"), false),
|
||||
vec!["alacritty", "-e", "nvim", "/tmp/notes.md"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_matching_rule_wins_and_globs_are_case_insensitive() {
|
||||
let policy = OpenWith {
|
||||
terminal: None,
|
||||
default: None,
|
||||
rules: vec![
|
||||
rule(&["*.PNG"], &["imv"], false),
|
||||
rule(&["@image"], &["eog"], false),
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
policy.command_for(Path::new("/tmp/shot.png"), false),
|
||||
vec!["imv", "/tmp/shot.png"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placeholder_positions_the_path_instead_of_appending_it() {
|
||||
let policy = OpenWith {
|
||||
terminal: None,
|
||||
default: None,
|
||||
rules: vec![rule(&["@any"], &["sh", "-c", "cat {} | less"], false)],
|
||||
};
|
||||
assert_eq!(
|
||||
policy.command_for(Path::new("/tmp/a.log"), false),
|
||||
vec!["sh", "-c", "cat /tmp/a.log | less"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directories_only_match_the_dir_class() {
|
||||
let policy = OpenWith {
|
||||
terminal: None,
|
||||
default: None,
|
||||
rules: vec![
|
||||
rule(&["@text"], &["nvim"], false),
|
||||
rule(&["@dir"], &["nautilus"], false),
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
policy.command_for(Path::new("/tmp/notes.md"), true),
|
||||
vec!["nautilus", "/tmp/notes.md"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rule_that_cannot_find_a_terminal_falls_back_to_the_default() {
|
||||
// A terminal that is spelled out in config is always honoured; this is
|
||||
// the other path — resolution must not invent one from the test host.
|
||||
let policy = OpenWith {
|
||||
terminal: Some(Vec::new()),
|
||||
default: Some(vec!["gio".into(), "open".into()]),
|
||||
rules: vec![rule(&["@text"], &["nvim"], true)],
|
||||
};
|
||||
let argv = policy.command_for(Path::new("/tmp/a.md"), false);
|
||||
// Either a terminal exists on this machine (wrapped nvim) or it does
|
||||
// not (the default). Both are correct; what must not happen is a bare
|
||||
// `nvim` with no tty.
|
||||
assert!(
|
||||
argv == vec!["gio", "open", "/tmp/a.md"]
|
||||
|| argv.ends_with(&["nvim".to_string(), "/tmp/a.md".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn globs_backtrack() {
|
||||
assert!(glob_match("*.md", "notes.md"));
|
||||
assert!(glob_match("*notes*.md", "my-notes-2024.md"));
|
||||
assert!(glob_match("a?c.txt", "abc.txt"));
|
||||
assert!(!glob_match("*.md", "notes.mdx"));
|
||||
assert!(!glob_match("a?c.txt", "ac.txt"));
|
||||
assert!(glob_match("*", "anything"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_terminal_name_gains_its_exec_flag() {
|
||||
assert_eq!(with_exec_flag("alacritty"), vec!["alacritty", "-e"]);
|
||||
assert_eq!(with_exec_flag("kitty"), vec!["kitty"]);
|
||||
assert_eq!(
|
||||
with_exec_flag("/usr/bin/wezterm"),
|
||||
vec!["/usr/bin/wezterm", "start", "--"]
|
||||
);
|
||||
// Unknown terminals get the near-universal `-e`.
|
||||
assert_eq!(with_exec_flag("mystery-term"), vec!["mystery-term", "-e"]);
|
||||
}
|
||||
}
|
||||
@@ -332,15 +332,20 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CtlRequest::OpenFile { path }) => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.open_file(&rel) {
|
||||
// A uid addresses the node wherever it lives; the path only works for
|
||||
// the primary mount's tree. Prefer the uid when the client sent one.
|
||||
Ok(CtlRequest::OpenFile { path, uid }) => {
|
||||
let opened = match uid.as_deref() {
|
||||
Some(uid) => core.open_file_uid(uid),
|
||||
None => rel_to_mount(mountpoint, &path).and_then(|rel| core.open_file(&rel)),
|
||||
};
|
||||
match opened {
|
||||
Ok(p) => CtlResponse::FilePath {
|
||||
path: p.display().to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(CtlRequest::Search { query, limit }) => match core.search(&query, limit) {
|
||||
Ok(hits) => CtlResponse::SearchResults { hits },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
|
||||
+94
-22
@@ -2974,15 +2974,24 @@ impl Core {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Return an absolute path through the most specific live on-demand mount
|
||||
/// Return an absolute path through the most specific local location
|
||||
/// covering `uid`. A node may be below several configured roots, so prefer
|
||||
/// the root leaving the shortest descendant path.
|
||||
///
|
||||
/// An on-demand folder only answers while its mount is live — without the
|
||||
/// mount its `local_path` is an ordinary empty directory. A mirror folder
|
||||
/// needs no mount: its files are real local copies the sync loop pushes
|
||||
/// back, so it is a valid open target whenever it is configured.
|
||||
fn mounted_search_path(&self, uid: &str) -> Option<String> {
|
||||
let live_mounts = self.mounts.lock();
|
||||
let folders = self.db.sync_folder_list().ok()?;
|
||||
folders
|
||||
.into_iter()
|
||||
.filter(|folder| folder.mode == "ondemand" && live_mounts.contains_key(&folder.id))
|
||||
.filter(|folder| match folder.mode.as_str() {
|
||||
"ondemand" => live_mounts.contains_key(&folder.id),
|
||||
"mirror" => true,
|
||||
_ => false,
|
||||
})
|
||||
.filter_map(|folder| {
|
||||
let relative = self.db.path_relative_to(&folder.remote_uid, uid).ok()??;
|
||||
let depth = relative.split('/').count();
|
||||
@@ -3164,7 +3173,68 @@ impl Core {
|
||||
node_size(&e.node),
|
||||
)
|
||||
};
|
||||
if let Some(p) = self.cache.cached_content_path(&uid, mtime, size) {
|
||||
self.fetch_content(&uid, &name, mtime, size)
|
||||
}
|
||||
|
||||
/// [`open_file`](Self::open_file) addressed by uid instead of by path.
|
||||
///
|
||||
/// A search hit is a metadata-index row, and the index covers every
|
||||
/// location this daemon knows — including on-demand sync folders and
|
||||
/// mirrors, whose nodes have no path inside the primary mount's tree.
|
||||
/// Walking such a hit's path from the mount root answers ENOENT even though
|
||||
/// the node is perfectly reachable, so front-ends address hits by uid.
|
||||
///
|
||||
/// Metadata comes from the live tree, then the index, then the API — the
|
||||
/// last covers a node the index knows but no location holds. Unlike the
|
||||
/// mutating by-uid handlers this does not demand a
|
||||
/// [`resolve_anywhere`](Self::resolve_anywhere) residency proof: reading
|
||||
/// one's own file is what the API authorizes anyway, and requiring
|
||||
/// residency is exactly what turned an openable search hit into "no such
|
||||
/// file or folder". [`open_shared_file`](Self::open_shared_file) already
|
||||
/// works this way. Reserved (local/virtual) uids name no remote node and
|
||||
/// are still rejected.
|
||||
fn open_file_uid(&self, raw_uid: &str) -> CoreResult<PathBuf> {
|
||||
let uid = parse_uid(raw_uid)
|
||||
.filter(|uid| !is_local_uid(uid) && !is_virtual_uid(uid))
|
||||
.ok_or_else(|| CoreError::invalid(format!("invalid uid: {raw_uid}")))?;
|
||||
let live = self
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.values()
|
||||
.find(|e| e.uid == uid)
|
||||
.map(|e| e.node.clone());
|
||||
let node = match live {
|
||||
Some(node) => node,
|
||||
None => match self
|
||||
.db
|
||||
.node_by_uid(&uid.to_string())
|
||||
.map_err(|e| CoreError::from_api(&e, "load node"))?
|
||||
{
|
||||
Some(node) => node,
|
||||
None => self
|
||||
.rt
|
||||
.block_on(self.client.get_node(&uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "get node"))?
|
||||
.ok_or_else(|| CoreError::not_found("node vanished"))?,
|
||||
},
|
||||
};
|
||||
if !node.is_file() {
|
||||
return Err(CoreError::invalid("not a regular file"));
|
||||
}
|
||||
self.fetch_content(&uid, &node.name, node.modification_time, node_size(&node))
|
||||
}
|
||||
|
||||
/// Materialise a file's full content into the content cache, returning its
|
||||
/// on-disk path. Serves a fresh cached blob without touching the network.
|
||||
fn fetch_content(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
name: &str,
|
||||
mtime: i64,
|
||||
size: u64,
|
||||
) -> CoreResult<PathBuf> {
|
||||
if let Some(p) = self.cache.cached_content_path(uid, mtime, size) {
|
||||
return Ok(p);
|
||||
}
|
||||
|
||||
@@ -3175,7 +3245,7 @@ impl Core {
|
||||
// from sharing a partially written staging file.
|
||||
static OPEN_TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
let seq = OPEN_TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let tmp = self.cache.content_path(&uid).with_extension(format!(
|
||||
let tmp = self.cache.content_path(uid).with_extension(format!(
|
||||
"open-{}-{}-{seq}.tmp",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
@@ -3188,7 +3258,7 @@ impl Core {
|
||||
.create_new(true)
|
||||
.open(&tmp)
|
||||
.map_err(|e| CoreError::internal(format!("create download temp: {e}")))?;
|
||||
let file = match self.download_file_tracked_to(&uid, &name, size, file) {
|
||||
let file = match self.download_file_tracked_to(uid, name, size, file) {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
@@ -3199,12 +3269,12 @@ impl Core {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(CoreError::internal(format!("sync download temp: {e}")));
|
||||
}
|
||||
if let Err(e) = self.cache.store_file(&uid, mtime, size, &tmp) {
|
||||
if let Err(e) = self.cache.store_file(uid, mtime, size, &tmp) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(CoreError::internal(format!("cache store: {e}")));
|
||||
}
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
Ok(self.cache.content_path(&uid))
|
||||
Ok(self.cache.content_path(uid))
|
||||
}
|
||||
|
||||
/// Drop the cached child listing of `rel`'s parent directory so the next
|
||||
@@ -5182,14 +5252,17 @@ mod tests {
|
||||
);
|
||||
descendant.parent_uid = Some(shared_with_me_uid());
|
||||
state.db.upsert_node(&descendant).unwrap();
|
||||
assert!(
|
||||
state
|
||||
.db
|
||||
.search("AtomicRollbackFindable", 10)
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"a descendant with no synthetic ancestor starts outside FTS"
|
||||
);
|
||||
// A node whose parent row is not cached — the synthetic root is not one
|
||||
// until this publication commits — is indexed under the path it can
|
||||
// actually be resolved to, which is its bare name. Publication reindexes
|
||||
// the subtree beneath the synthetic ancestor, so that path is what the
|
||||
// rollback has to restore.
|
||||
let path_before = {
|
||||
let hits = state.db.search("AtomicRollbackFindable", 10).unwrap();
|
||||
assert_eq!(hits.len(), 1, "the descendant starts out searchable");
|
||||
hits[0].path.clone()
|
||||
};
|
||||
assert_eq!(path_before, "AtomicRollbackFindable");
|
||||
|
||||
// The pin is the transaction's final statement. Failing it proves the
|
||||
// earlier access, node, and descendant FTS work rolls back with it.
|
||||
@@ -5251,13 +5324,12 @@ mod tests {
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(state.db.share_access(&shared_with_me_uid()).unwrap(), None);
|
||||
assert!(
|
||||
state
|
||||
.db
|
||||
.search("AtomicRollbackFindable", 10)
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"descendant FTS visibility must roll back with the failed pin"
|
||||
let hits = state.db.search("AtomicRollbackFindable", 10).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(
|
||||
hits[0].path, path_before,
|
||||
"the descendant's indexed path must roll back with the failed pin, \
|
||||
not keep the synthetic ancestor the publication tried to add"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -149,10 +149,10 @@ impl Core {
|
||||
.pin_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
.into_iter()
|
||||
.map(|(uid, path, recursive)| ProfilePin {
|
||||
uid,
|
||||
path,
|
||||
recursive,
|
||||
.map(|row| ProfilePin {
|
||||
uid: row.uid,
|
||||
path: row.path,
|
||||
recursive: row.recursive,
|
||||
})
|
||||
.collect();
|
||||
let cfg = pdfs_core::config::AppDirs::new()
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
//! Shared Drive-result activation policy for the GTK browser and quick prompt.
|
||||
//!
|
||||
//! Media should be handed to its mounted path so players can issue range reads
|
||||
//! through FUSE. Other files retain the materialize-then-open behaviour because
|
||||
//! many desktop applications expect a stable ordinary file.
|
||||
//! through FUSE. Everything else opens through the mount too whenever the mount
|
||||
//! exposes it, and only falls back to materialize-then-open when it does not —
|
||||
//! see [`mounted_target`].
|
||||
//!
|
||||
//! Both binaries `#[path]`-include this file, so each compiles its own copy and
|
||||
//! anything only one of them calls looks dead in the other. That is what the
|
||||
//! `dead_code` allowances below are for — not code nobody uses.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use pdfs_core::control::PhotoKind;
|
||||
use pdfs_core::control::{PhotoKind, SearchHit};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum DriveActivation {
|
||||
@@ -29,6 +34,49 @@ pub(crate) fn mounted_path(mountpoint: &Path, relative_path: &str) -> PathBuf {
|
||||
mountpoint.join(relative_path)
|
||||
}
|
||||
|
||||
/// Where a Drive hit should be opened from, when a mount exposes it.
|
||||
///
|
||||
/// Materialised content is a *copy*: it lives in the cache under its content
|
||||
/// hash, so an editor saving into it writes somewhere Drive will never look,
|
||||
/// and the cache is free to evict it afterwards. The mounted path is the real
|
||||
/// file — reads pull 4 MiB blocks on demand and a write becomes a new revision
|
||||
/// — so it wins for every kind of file, not just streamable media.
|
||||
///
|
||||
/// [`Request::OpenFile`](pdfs_core::control::Request::OpenFile) stays the
|
||||
/// fallback for hits no mount exposes: the search index also covers nodes
|
||||
/// outside the mounted tree (a mirror folder's contents, a stale row), and
|
||||
/// those can still be read, just not edited in place.
|
||||
///
|
||||
/// The `stat` is why this returns an `Option` rather than a path: it is the
|
||||
/// only way to tell those two cases apart, and it costs one syscall on a path
|
||||
/// the caller is about to hand to an application anyway.
|
||||
#[allow(dead_code)] // prompt only
|
||||
pub(crate) fn mounted_target(mountpoint: &Path, hit: &SearchHit) -> Option<PathBuf> {
|
||||
present(mounted_or_relative(mountpoint, hit))
|
||||
}
|
||||
|
||||
/// [`mounted_target`] for callers holding a mountpoint-relative path rather
|
||||
/// than a search hit — the browser's listing entries, which are by definition
|
||||
/// paths in the primary mount's tree.
|
||||
#[allow(dead_code)] // browser only
|
||||
pub(crate) fn mounted_target_rel(mountpoint: &Path, relative_path: &str) -> Option<PathBuf> {
|
||||
present(mounted_path(mountpoint, relative_path))
|
||||
}
|
||||
|
||||
fn present(path: PathBuf) -> Option<PathBuf> {
|
||||
path.symlink_metadata().is_ok().then_some(path)
|
||||
}
|
||||
|
||||
/// The mount path for a hit, whether or not anything is there — for callers
|
||||
/// that have no fallback (a folder cannot be materialised) or already know the
|
||||
/// entry came from a mount listing.
|
||||
#[allow(dead_code)] // prompt only
|
||||
pub(crate) fn mounted_or_relative(mountpoint: &Path, hit: &SearchHit) -> PathBuf {
|
||||
hit.mounted_path
|
||||
.as_deref()
|
||||
.map_or_else(|| mounted_path(mountpoint, &hit.path), PathBuf::from)
|
||||
}
|
||||
|
||||
fn is_streamable_media(name: &str) -> bool {
|
||||
if PhotoKind::classify(Some(name), None) == PhotoKind::Video {
|
||||
return true;
|
||||
|
||||
@@ -996,11 +996,18 @@ fn capitalize(s: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a local path with the user's default handler.
|
||||
/// Open a local path with the handler the user configured — `xdg-open` unless
|
||||
/// `open_with` in `config.json` overrides it for this kind of file.
|
||||
fn open_path(path: &str) {
|
||||
if let Err(e) = Command::new("xdg-open").arg(path).spawn() {
|
||||
tracing::error!("xdg-open {path} failed: {e}");
|
||||
}
|
||||
let path = Path::new(path);
|
||||
pdfs_core::opener::open_default(path, path.is_dir());
|
||||
}
|
||||
|
||||
/// [`open_path`] for a file the daemon materialised into the content cache,
|
||||
/// where the on-disk name is a content hash and carries no extension for the
|
||||
/// rules (or `xdg-open`) to key off. `name` is the Drive name it was opened as.
|
||||
pub(crate) fn open_named_path(path: &str, name: &str) {
|
||||
pdfs_core::opener::open_default_named(Path::new(path), name, false);
|
||||
}
|
||||
|
||||
/// Format a byte count as a short binary-unit string (e.g. `1.2 GiB`).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::activation::{DriveActivation, drive_activation, mounted_path};
|
||||
use crate::activation::{DriveActivation, drive_activation, mounted_path, mounted_target_rel};
|
||||
use crate::*;
|
||||
|
||||
pub(crate) struct BrowserState {
|
||||
@@ -659,21 +659,35 @@ pub(crate) fn activate_entry(ui: &Rc<Ui>, entry: &DirEntry) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Download a file's full content into the cache and hand it to the user's
|
||||
/// default application. The download-and-open path behind both a plain
|
||||
/// double-click and the context menu's "Open" (including for a video, when the
|
||||
/// user explicitly wants a local copy rather than to stream it).
|
||||
/// Hand a file to the user's default application: through the mount when it is
|
||||
/// there, otherwise downloaded into the cache first. The open path behind both
|
||||
/// a plain double-click and the context menu's "Open" (including for a video,
|
||||
/// when the user wants their default application rather than the player).
|
||||
///
|
||||
/// The mount comes first because the cache blob is a *copy* keyed by content
|
||||
/// hash — an application saving into it writes where Drive will never look, and
|
||||
/// the cache may evict it afterwards. See
|
||||
/// [`mounted_target`](crate::activation::mounted_target).
|
||||
pub(crate) fn download_and_open(ui: &Rc<Ui>, entry: &DirEntry) {
|
||||
let rel = entry_rel(ui, entry);
|
||||
let mountpoint = ui.dirs.resolved_mountpoint(&ui.dirs.load_config());
|
||||
if let Some(path) = mounted_target_rel(&mountpoint, &rel) {
|
||||
open_path(&path.to_string_lossy());
|
||||
return;
|
||||
}
|
||||
// Ignore a repeat activation of a file already downloading, so an impatient
|
||||
// double-click doesn't kick off a second round-trip.
|
||||
if !ui.opening.borrow_mut().insert(rel.clone()) {
|
||||
return;
|
||||
}
|
||||
ui.busy_begin();
|
||||
let name = entry.name.clone();
|
||||
let rx = spawn_request(
|
||||
ui.dirs.control_socket(),
|
||||
Request::OpenFile { path: rel.clone() },
|
||||
Request::OpenFile {
|
||||
path: rel.clone(),
|
||||
uid: Some(entry.uid.clone()),
|
||||
},
|
||||
);
|
||||
let ui = ui.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
@@ -681,7 +695,9 @@ pub(crate) fn download_and_open(ui: &Rc<Ui>, entry: &DirEntry) {
|
||||
ui.busy_end();
|
||||
ui.opening.borrow_mut().remove(&rel);
|
||||
match result {
|
||||
Ok(Ok(Response::FilePath { path })) => open_path(&path),
|
||||
// A cache blob is named by content hash: match the open rules
|
||||
// against the Drive name the user clicked, not that path.
|
||||
Ok(Ok(Response::FilePath { path })) => open_named_path(&path, &name),
|
||||
Ok(Ok(Response::Error { message, kind })) => {
|
||||
toast_failure(&ui, "Couldn't open file", &message, kind)
|
||||
}
|
||||
|
||||
@@ -388,12 +388,15 @@ fn open_shared_file(ui: &Rc<Ui>, uid: &str, name: &str) {
|
||||
);
|
||||
let ui = ui.clone();
|
||||
let uid = uid.to_string();
|
||||
let name = name.to_string();
|
||||
glib::spawn_future_local(async move {
|
||||
let result = rx.recv().await;
|
||||
ui.busy_end();
|
||||
ui.opening.borrow_mut().remove(&uid);
|
||||
match result {
|
||||
Ok(Ok(Response::FilePath { path })) => open_path(&path),
|
||||
// A cache blob is named by content hash, so the open rules key off
|
||||
// the shared node's name instead.
|
||||
Ok(Ok(Response::FilePath { path })) => open_named_path(&path, &name),
|
||||
Ok(Ok(Response::Error { message, kind })) => {
|
||||
toast_failure(&ui, "Couldn't open file", &message, kind)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
//! `pdfs-prompt --dmenu`: the same search, presented in the user's own launcher.
|
||||
//!
|
||||
//! Everything here is blocking and GTK-free — the process exists for one
|
||||
//! round-trip and then exits, so there is no main loop to keep off. It reuses
|
||||
//! the GTK prompt's [`Hit`](crate::Hit) model and ranking, and its Drive
|
||||
//! activation policy, so the two front ends cannot drift on what "open" means.
|
||||
//!
|
||||
//! Launchers filter a static list; they cannot call back for a new one per
|
||||
//! keystroke. So the interaction is a loop: the first menu shows pinned files
|
||||
//! and accepts free text, and any text that matches no entry becomes the next
|
||||
//! search. Escape (an empty selection) ends it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use pdfs_core::config::AppDirs;
|
||||
use pdfs_core::control::{
|
||||
Request, Response, SearchFilters, SearchHit, SearchKind, SearchSource, send,
|
||||
};
|
||||
use pdfs_core::menu::{self, MenuChoice, MenuItem, PromptConfig};
|
||||
use pdfs_core::opener::{self, OpenWith};
|
||||
|
||||
use crate::activation::{DriveActivation, drive_activation, mounted_or_relative, mounted_target};
|
||||
use crate::{Hit, file_name, is_document, is_image, is_media, rank_hits};
|
||||
|
||||
/// Guard against a launcher that keeps handing back text we cannot satisfy —
|
||||
/// without it a scripted (non-interactive) menu could spin forever.
|
||||
const MAX_ROUNDS: usize = 64;
|
||||
|
||||
pub(crate) struct Options {
|
||||
/// Launcher argv from `--menu`, overriding the configured/detected one.
|
||||
pub menu: Option<Vec<String>>,
|
||||
/// Skip the pinned-files round and search for this immediately.
|
||||
pub query: Option<String>,
|
||||
}
|
||||
|
||||
/// Run the launcher flow. Returns an error only for conditions the user must
|
||||
/// act on (no daemon, no launcher); a plain cancel is `Ok`.
|
||||
pub(crate) fn run(options: Options) -> Result<(), String> {
|
||||
let dirs = AppDirs::new().map_err(|e| format!("cannot resolve app dirs: {e}"))?;
|
||||
let config = dirs.load_config();
|
||||
let prompt: PromptConfig = config.resolved_prompt();
|
||||
let policy: OpenWith = config.resolved_open_with();
|
||||
let socket = dirs.control_socket();
|
||||
|
||||
let menu_argv =
|
||||
menu::resolve_menu(options.menu.as_ref().or(prompt.menu.as_ref())).ok_or_else(|| {
|
||||
"no launcher found — install fuzzel/rofi/wofi, or set prompt.menu in config.json"
|
||||
.to_string()
|
||||
})?;
|
||||
|
||||
let mountpoint = match request(&socket, Request::Status)? {
|
||||
Response::Status { mountpoint, .. } => PathBuf::from(mountpoint),
|
||||
_ => dirs.default_mountpoint(),
|
||||
};
|
||||
|
||||
let mut query = options
|
||||
.query
|
||||
.map(|q| q.trim().to_string())
|
||||
.filter(|q| !q.is_empty());
|
||||
for _ in 0..MAX_ROUNDS {
|
||||
let hits = match &query {
|
||||
Some(text) => search(&socket, text, prompt.resolved_menu_limit())?,
|
||||
None => pins(&socket)?,
|
||||
};
|
||||
let items: Vec<MenuItem> = if hits.is_empty() {
|
||||
vec![MenuItem::new(placeholder(query.as_deref()), None)]
|
||||
} else {
|
||||
label_all(&hits)
|
||||
};
|
||||
|
||||
match menu::run(&menu_argv, &title(query.as_deref()), &items).map_err(|e| e.to_string())? {
|
||||
MenuChoice::Item(index) => {
|
||||
let Some(hit) = hits.get(index) else {
|
||||
// The placeholder row. Selecting it is not a cancel — the
|
||||
// user pressed Enter on "type to search", so start over
|
||||
// with the pinned list rather than quitting on them.
|
||||
query = None;
|
||||
continue;
|
||||
};
|
||||
return open(&socket, &mountpoint, &policy, hit, query.is_none());
|
||||
}
|
||||
// No entry matched what was typed: treat it as the next query.
|
||||
MenuChoice::Custom(text) => query = Some(text),
|
||||
MenuChoice::Cancelled => return Ok(()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The launcher's prompt string.
|
||||
///
|
||||
/// A launcher renders this immediately left of the input, so it is the only
|
||||
/// place to say what typing here does. "Drive" alone read as a label and left
|
||||
/// the two-step nature of the flow — type, Enter, *then* results — invisible;
|
||||
/// the verb and the chevron make it a search box, and echoing the current query
|
||||
/// shows which round you are in.
|
||||
fn title(query: Option<&str>) -> String {
|
||||
match query {
|
||||
Some(text) => format!("Drive: {text} › "),
|
||||
None => "Search Drive › ".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text for the one row shown when there is nothing to list.
|
||||
///
|
||||
/// A launcher handed an empty list shows a bare prompt, and some refuse to
|
||||
/// return anything at all from an empty menu — which would strand the user on
|
||||
/// the very first round, since a fresh account has no pins. A single row keeps
|
||||
/// the menu non-empty and says why it is empty.
|
||||
///
|
||||
/// A fuzzy launcher can match this row against what the user types, and the
|
||||
/// selection comes back as a label with no way to tell the two apart — so the
|
||||
/// wording is parenthesised and avoids words that read like a filename query.
|
||||
fn placeholder(query: Option<&str>) -> String {
|
||||
match query {
|
||||
Some(text) => format!("(no matches for “{text}”)"),
|
||||
None => "(no pinned files — type to search)".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned files — the same "you asked to keep these" set the GTK prompt opens
|
||||
/// with, and the only listing the daemon offers without a query.
|
||||
fn pins(socket: &Path) -> Result<Vec<Hit>, String> {
|
||||
let Response::Pins { pins } = request(socket, Request::ListPins)? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(pins
|
||||
.into_iter()
|
||||
.map(|pin| {
|
||||
Hit::Drive(SearchHit {
|
||||
name: file_name(&pin.path),
|
||||
path: pin.path,
|
||||
is_dir: pin.is_dir.unwrap_or(pin.recursive),
|
||||
size: 0,
|
||||
modified: 0,
|
||||
pinned: true,
|
||||
uid: pin.uid,
|
||||
mounted_path: None,
|
||||
score: 0,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn search(socket: &Path, query: &str, limit: usize) -> Result<Vec<Hit>, String> {
|
||||
let reply = request(
|
||||
socket,
|
||||
Request::SearchV2 {
|
||||
query: query.to_string(),
|
||||
limit,
|
||||
filters: SearchFilters {
|
||||
sources: vec![SearchSource::Drive, SearchSource::Local],
|
||||
kind: SearchKind::All,
|
||||
},
|
||||
},
|
||||
)?;
|
||||
let Response::SearchResultsV2 {
|
||||
drive_hits,
|
||||
local_hits,
|
||||
..
|
||||
} = reply
|
||||
else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut hits: Vec<Hit> = drive_hits.into_iter().map(Hit::Drive).collect();
|
||||
hits.extend(local_hits.into_iter().map(Hit::Local));
|
||||
rank_hits(&mut hits);
|
||||
hits.truncate(limit);
|
||||
Ok(hits)
|
||||
}
|
||||
|
||||
/// One launcher line per hit. Labels must be unique: they are how the selection
|
||||
/// is matched back, and two files of the same name in the same folder listing
|
||||
/// would otherwise be indistinguishable.
|
||||
fn label_all(hits: &[Hit]) -> Vec<MenuItem> {
|
||||
let mut items: Vec<MenuItem> = Vec::with_capacity(hits.len());
|
||||
for hit in hits {
|
||||
let mut label = format!("{} · {}", hit.name(), hit.location());
|
||||
let mut suffix = 2;
|
||||
while items.iter().any(|item| item.label == label) {
|
||||
label = format!("{} · {} ({suffix})", hit.name(), hit.location());
|
||||
suffix += 1;
|
||||
}
|
||||
items.push(MenuItem::new(label, Some(icon_name(hit))));
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// Icon theme name for a hit.
|
||||
///
|
||||
/// Coarse on purpose: `content_type_guess` would give an exact MIME name, but
|
||||
/// only with file *contents* to sniff — a Drive hit is metadata, and passing it
|
||||
/// an empty buffer answers `application-x-zerosize` for everything. The generic
|
||||
/// names below exist in every icon theme.
|
||||
fn icon_name(hit: &Hit) -> String {
|
||||
if hit.is_dir() {
|
||||
return "folder".to_string();
|
||||
}
|
||||
let name = hit.name();
|
||||
if is_image(name) {
|
||||
"image-x-generic"
|
||||
} else if is_media(name) {
|
||||
"video-x-generic"
|
||||
} else if is_document(name) {
|
||||
"text-x-generic"
|
||||
} else {
|
||||
"application-x-generic"
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Open a chosen hit, mirroring the GTK prompt: local files are already on
|
||||
/// disk, a Drive folder or streamable file goes through the mount, and anything
|
||||
/// else is materialised by the daemon first.
|
||||
fn open(
|
||||
socket: &Path,
|
||||
mountpoint: &Path,
|
||||
policy: &OpenWith,
|
||||
hit: &Hit,
|
||||
from_pins: bool,
|
||||
) -> Result<(), String> {
|
||||
match hit {
|
||||
Hit::Local(local) => {
|
||||
opener::open(policy, Path::new(&local.path), local.is_dir);
|
||||
Ok(())
|
||||
}
|
||||
Hit::Drive(drive) => {
|
||||
// A folder has no materialised form, and a pin row's `is_dir` is pin
|
||||
// policy rather than node kind, so both go to the mount unchecked.
|
||||
let unconditional = from_pins
|
||||
|| matches!(
|
||||
drive_activation(&drive.name, drive.is_dir),
|
||||
DriveActivation::Folder | DriveActivation::MountedMedia
|
||||
);
|
||||
if unconditional {
|
||||
opener::open(
|
||||
policy,
|
||||
&mounted_or_relative(mountpoint, drive),
|
||||
drive.is_dir,
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
// Anything else the mount exposes opens there too, so an editor
|
||||
// saves back into Drive instead of into a cache blob.
|
||||
if let Some(path) = mounted_target(mountpoint, drive) {
|
||||
opener::open(policy, &path, false);
|
||||
return Ok(());
|
||||
}
|
||||
match request(
|
||||
socket,
|
||||
Request::OpenFile {
|
||||
path: drive.path.clone(),
|
||||
uid: Some(drive.uid.clone()),
|
||||
},
|
||||
)? {
|
||||
Response::FilePath { path } => {
|
||||
// The reply is a content-hash blob; the rules key off the
|
||||
// Drive name, which is what the user actually opened.
|
||||
opener::open_named(policy, Path::new(&path), &drive.name, false);
|
||||
Ok(())
|
||||
}
|
||||
Response::Error { message, .. } => Err(format!("could not open: {message}")),
|
||||
_ => Err("unexpected reply from the daemon".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One control-socket round-trip, with the daemon-is-down case phrased for a
|
||||
/// terminal rather than a status page.
|
||||
fn request(socket: &Path, request: Request) -> Result<Response, String> {
|
||||
send(socket, &request).map_err(|e| format!("cannot reach the Proton Drive daemon: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pdfs_core::control::LocalHit;
|
||||
|
||||
fn drive(name: &str, path: &str, is_dir: bool) -> Hit {
|
||||
Hit::Drive(SearchHit {
|
||||
name: name.into(),
|
||||
path: path.into(),
|
||||
is_dir,
|
||||
size: 0,
|
||||
modified: 0,
|
||||
pinned: false,
|
||||
uid: "uid".into(),
|
||||
mounted_path: None,
|
||||
score: 0,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_are_unique_so_a_selection_maps_back_to_one_hit() {
|
||||
let hits = vec![
|
||||
drive("notes.md", "Docs/notes.md", false),
|
||||
Hit::Local(LocalHit {
|
||||
name: "notes.md".into(),
|
||||
path: "/home/me/Docs/notes.md".into(),
|
||||
is_dir: false,
|
||||
size: 0,
|
||||
modified: 0,
|
||||
score: 0,
|
||||
}),
|
||||
drive("notes.md", "Docs/notes.md", false),
|
||||
];
|
||||
let items = label_all(&hits);
|
||||
assert_eq!(items.len(), 3);
|
||||
assert_ne!(items[0].label, items[2].label);
|
||||
let unique: std::collections::HashSet<_> =
|
||||
items.iter().map(|item| item.label.clone()).collect();
|
||||
assert_eq!(unique.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_says_a_search_is_what_enter_does() {
|
||||
let first = title(None);
|
||||
assert!(first.to_lowercase().contains("search"), "{first}");
|
||||
// The launcher renders the input immediately after the prompt, so the
|
||||
// prompt has to carry its own separator or it runs into what is typed.
|
||||
assert!(first.ends_with(' '), "{first:?}");
|
||||
|
||||
let refined = title(Some("md"));
|
||||
assert!(refined.contains("md"), "{refined}");
|
||||
assert!(refined.ends_with(' '), "{refined:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_round_still_has_a_row_explaining_itself() {
|
||||
assert!(placeholder(None).contains("type to search"));
|
||||
assert!(placeholder(Some("md")).contains("md"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icons_are_theme_names_the_launcher_can_look_up() {
|
||||
assert_eq!(icon_name(&drive("Photos", "Photos", true)), "folder");
|
||||
assert_eq!(
|
||||
icon_name(&drive("a.png", "a.png", false)),
|
||||
"image-x-generic"
|
||||
);
|
||||
assert_eq!(icon_name(&drive("a.md", "a.md", false)), "text-x-generic");
|
||||
assert_eq!(
|
||||
icon_name(&drive("a.bin", "a.bin", false)),
|
||||
"application-x-generic"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -134,9 +134,7 @@ fn poll_state(socket: &Path, default_mountpoint: &Path) -> DriveState {
|
||||
}
|
||||
|
||||
fn open_folder(mountpoint: &Path) {
|
||||
if let Err(e) = Command::new("xdg-open").arg(mountpoint).spawn() {
|
||||
tracing::error!("failed to xdg-open {}: {e}", mountpoint.display());
|
||||
}
|
||||
pdfs_core::opener::open_default(mountpoint, true);
|
||||
}
|
||||
|
||||
/// Launch (or, since it's `SingleMainWindow`, raise) the settings/management
|
||||
|
||||
+209
-44
@@ -9,7 +9,6 @@
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -20,9 +19,12 @@ use pdfs_core::config::AppDirs;
|
||||
use pdfs_core::control::{
|
||||
LocalHit, Request, Response, SearchFilters, SearchHit, SearchKind, SearchSource, send,
|
||||
};
|
||||
use pdfs_core::menu::PromptMode;
|
||||
use pdfs_core::opener::{self, OpenWith};
|
||||
|
||||
mod activation;
|
||||
use activation::{DriveActivation, drive_activation, mounted_path};
|
||||
mod dmenu;
|
||||
use activation::{DriveActivation, drive_activation, mounted_or_relative, mounted_target};
|
||||
|
||||
const APP_ID: &str = "io.narl.proton-drive-linux-prompt";
|
||||
|
||||
@@ -145,29 +147,26 @@ impl Hit {
|
||||
}
|
||||
|
||||
/// The dimmed second line: the containing folder, as the user thinks of it.
|
||||
///
|
||||
/// A Drive hit is only "My files" when it really sits in the primary mount.
|
||||
/// A node inside a device folder resolves to a path on this machine
|
||||
/// (`~/Downloads/…`) — the daemon has already worked that out in
|
||||
/// `mounted_path`, and saying "My files / Downloads" for it names a folder
|
||||
/// the user cannot find and does not match where activating the row opens.
|
||||
fn location(&self) -> String {
|
||||
match self {
|
||||
Hit::Drive(h) => {
|
||||
let parent = parent_of(&h.path);
|
||||
if parent.is_empty() {
|
||||
"My files".to_string()
|
||||
} else {
|
||||
format!("My files / {}", parent.replace('/', " / "))
|
||||
Hit::Drive(h) => match h.mounted_path.as_deref() {
|
||||
Some(mounted) => home_relative(&parent_of(mounted)),
|
||||
None => {
|
||||
let parent = parent_of(&h.path);
|
||||
if parent.is_empty() {
|
||||
"My files".to_string()
|
||||
} else {
|
||||
format!("My files / {}", parent.replace('/', " / "))
|
||||
}
|
||||
}
|
||||
}
|
||||
Hit::Local(h) => {
|
||||
let parent = parent_of(&h.path);
|
||||
match dirs_home().and_then(|home| {
|
||||
Path::new(&parent)
|
||||
.strip_prefix(&home)
|
||||
.ok()
|
||||
.map(|rel| rel.display().to_string())
|
||||
}) {
|
||||
Some(rel) if rel.is_empty() => "Home".to_string(),
|
||||
Some(rel) => format!("Home / {}", rel.replace('/', " / ")),
|
||||
None => parent,
|
||||
}
|
||||
}
|
||||
},
|
||||
Hit::Local(h) => home_relative(&parent_of(&h.path)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,6 +219,10 @@ fn rank_hits(hits: &mut [Hit]) {
|
||||
struct Ui {
|
||||
socket: PathBuf,
|
||||
mountpoint: RefCell<PathBuf>,
|
||||
/// How a chosen file is launched. Read once at window build: the prompt is
|
||||
/// resident, but a config edit is rare enough that a restart is a fair
|
||||
/// price for not re-reading the file on every Enter.
|
||||
opener: OpenWith,
|
||||
|
||||
entry: gtk4::Entry,
|
||||
spinner: gtk4::Spinner,
|
||||
@@ -328,6 +331,71 @@ impl Section {
|
||||
}
|
||||
}
|
||||
|
||||
const USAGE: &str = "\
|
||||
pdfs-prompt — search Proton Drive and this computer
|
||||
|
||||
Usage: pdfs-prompt [OPTIONS]
|
||||
|
||||
Options:
|
||||
--dmenu Present the results in an external launcher (fuzzel,
|
||||
rofi, …) instead of the built-in GTK window. Also
|
||||
settable permanently as \"prompt\": { \"mode\": \"dmenu\" }
|
||||
in config.json.
|
||||
--gtk Force the built-in window, overriding that setting.
|
||||
--menu <COMMAND> Launcher command line for --dmenu, e.g.
|
||||
--menu 'fuzzel --dmenu --width 60'. Overrides
|
||||
\"prompt\": { \"menu\": [...] }.
|
||||
--query <TEXT> Search for TEXT immediately instead of opening on the
|
||||
pinned-files list (--dmenu only).
|
||||
-h, --help Show this help.
|
||||
";
|
||||
|
||||
/// What the command line asked for, before any GTK setup happens: the launcher
|
||||
/// path must not pay for — or fail on — a display connection it never uses.
|
||||
struct Args {
|
||||
mode: Option<PromptMode>,
|
||||
menu: Option<Vec<String>>,
|
||||
query: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_args(argv: impl Iterator<Item = String>) -> Result<Args, String> {
|
||||
let mut args = Args {
|
||||
mode: None,
|
||||
menu: None,
|
||||
query: None,
|
||||
};
|
||||
let mut argv = argv.peekable();
|
||||
while let Some(arg) = argv.next() {
|
||||
match arg.as_str() {
|
||||
"--dmenu" => args.mode = Some(PromptMode::Dmenu),
|
||||
"--gtk" => args.mode = Some(PromptMode::Gtk),
|
||||
// A launcher command is one shell-ish string so it can live in a
|
||||
// keybinding; splitting on whitespace is enough for flags, and a
|
||||
// launcher argument needing spaces belongs in config.json.
|
||||
"--menu" => {
|
||||
let value = argv
|
||||
.next()
|
||||
.ok_or_else(|| "--menu needs a command".to_string())?;
|
||||
let parts: Vec<String> = value.split_whitespace().map(str::to_string).collect();
|
||||
if parts.is_empty() {
|
||||
return Err("--menu needs a command".to_string());
|
||||
}
|
||||
args.menu = Some(parts);
|
||||
// A launcher was named explicitly; that only makes sense here.
|
||||
args.mode.get_or_insert(PromptMode::Dmenu);
|
||||
}
|
||||
"--query" => {
|
||||
args.query = Some(
|
||||
argv.next()
|
||||
.ok_or_else(|| "--query needs a search term".to_string())?,
|
||||
);
|
||||
}
|
||||
other => return Err(format!("unrecognised argument: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
fn main() -> glib::ExitCode {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
@@ -335,6 +403,37 @@ fn main() -> glib::ExitCode {
|
||||
)
|
||||
.init();
|
||||
|
||||
let raw: Vec<String> = std::env::args().skip(1).collect();
|
||||
if raw.iter().any(|arg| arg == "-h" || arg == "--help") {
|
||||
print!("{USAGE}");
|
||||
return glib::ExitCode::SUCCESS;
|
||||
}
|
||||
let args = match parse_args(raw.into_iter()) {
|
||||
Ok(args) => args,
|
||||
Err(message) => {
|
||||
eprintln!("pdfs-prompt: {message}\n\n{USAGE}");
|
||||
return glib::ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
// The stored mode makes an existing keybinding switch front ends without
|
||||
// being re-bound; an explicit flag still wins.
|
||||
let stored = AppDirs::new()
|
||||
.map(|dirs| dirs.load_config().resolved_prompt().resolved_mode())
|
||||
.unwrap_or_default();
|
||||
if args.mode.unwrap_or(stored) == PromptMode::Dmenu {
|
||||
return match dmenu::run(dmenu::Options {
|
||||
menu: args.menu,
|
||||
query: args.query,
|
||||
}) {
|
||||
Ok(()) => glib::ExitCode::SUCCESS,
|
||||
Err(message) => {
|
||||
eprintln!("pdfs-prompt: {message}");
|
||||
glib::ExitCode::FAILURE
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let app = adw::Application::builder().application_id(APP_ID).build();
|
||||
// GtkApplication normally remains active while it owns a window, including
|
||||
// when that window is hidden. Hold it explicitly as well: residency is a
|
||||
@@ -354,7 +453,8 @@ fn main() -> glib::ExitCode {
|
||||
};
|
||||
ui.activate();
|
||||
});
|
||||
app.run()
|
||||
// GTK must not try to parse our own flags; they were consumed above.
|
||||
app.run_with_args::<&str>(&[])
|
||||
}
|
||||
|
||||
fn build_window(app: &adw::Application) -> Option<Rc<Ui>> {
|
||||
@@ -478,6 +578,7 @@ fn build_window(app: &adw::Application) -> Option<Rc<Ui>> {
|
||||
let ui = Rc::new(Ui {
|
||||
socket: dirs.control_socket(),
|
||||
mountpoint: RefCell::new(dirs.default_mountpoint()),
|
||||
opener: dirs.load_config().resolved_open_with(),
|
||||
entry: entry.clone(),
|
||||
spinner,
|
||||
stack,
|
||||
@@ -686,6 +787,20 @@ impl Ui {
|
||||
self.entry.grab_focus();
|
||||
}
|
||||
|
||||
/// Hand a resolved path to the configured opener — `xdg-open` unless
|
||||
/// `open_with` in `config.json` says otherwise (a terminal editor for text
|
||||
/// files, say).
|
||||
fn open_path(&self, path: &Path, is_dir: bool) {
|
||||
opener::open(&self.opener, path, is_dir);
|
||||
}
|
||||
|
||||
/// Open a file the daemon just materialised into the content cache. The
|
||||
/// blob is named after its content hash, so the open rules have to be
|
||||
/// matched against the Drive name instead.
|
||||
fn open_materialized(&self, path: &Path, name: &str) {
|
||||
opener::open_named(&self.opener, path, name, false);
|
||||
}
|
||||
|
||||
/// Dismiss without destroying the application window. GTK continues to
|
||||
/// associate the hidden window with the single application instance, so a
|
||||
/// later desktop shortcut invocation is a cheap `activate` round-trip.
|
||||
@@ -751,7 +866,7 @@ impl Ui {
|
||||
.map(|pin| SearchHit {
|
||||
name: file_name(&pin.path),
|
||||
path: pin.path,
|
||||
is_dir: pin.recursive,
|
||||
is_dir: pin.is_dir.unwrap_or(pin.recursive),
|
||||
size: 0,
|
||||
modified: 0,
|
||||
pinned: true,
|
||||
@@ -1081,7 +1196,7 @@ impl Ui {
|
||||
|
||||
match hit {
|
||||
Hit::Local(local) => {
|
||||
xdg_open(Path::new(&local.path));
|
||||
self.open_path(Path::new(&local.path), local.is_dir);
|
||||
self.dismiss();
|
||||
}
|
||||
Hit::Drive(drive) => {
|
||||
@@ -1091,25 +1206,28 @@ impl Ui {
|
||||
// this handles non-recursively pinned folders without mistaking
|
||||
// them for files and sending an invalid OpenFile request.
|
||||
if self.rendered_query.borrow().is_empty() {
|
||||
let path = drive.mounted_path.as_deref().map_or_else(
|
||||
|| mounted_path(&self.mountpoint.borrow(), &drive.path),
|
||||
PathBuf::from,
|
||||
);
|
||||
xdg_open(&path);
|
||||
let path = mounted_or_relative(&self.mountpoint.borrow(), &drive);
|
||||
self.open_path(&path, drive.is_dir);
|
||||
self.dismiss();
|
||||
return;
|
||||
}
|
||||
match drive_activation(&drive.name, drive.is_dir) {
|
||||
DriveActivation::Folder | DriveActivation::MountedMedia => {
|
||||
let path = drive.mounted_path.as_deref().map_or_else(
|
||||
|| mounted_path(&self.mountpoint.borrow(), &drive.path),
|
||||
PathBuf::from,
|
||||
);
|
||||
xdg_open(&path);
|
||||
let path = mounted_or_relative(&self.mountpoint.borrow(), &drive);
|
||||
self.open_path(&path, drive.is_dir);
|
||||
self.dismiss();
|
||||
return;
|
||||
}
|
||||
DriveActivation::Materialize => {}
|
||||
// The mount holds the real file; the cache holds a copy an
|
||||
// editor would save into for nothing. Prefer the mount, and
|
||||
// materialise only what it does not expose.
|
||||
DriveActivation::Materialize => {
|
||||
if let Some(path) = mounted_target(&self.mountpoint.borrow(), &drive) {
|
||||
self.open_path(&path, false);
|
||||
self.dismiss();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.opening.set(true);
|
||||
@@ -1121,6 +1239,7 @@ impl Ui {
|
||||
self.socket.clone(),
|
||||
Request::OpenFile {
|
||||
path: drive.path.clone(),
|
||||
uid: Some(drive.uid.clone()),
|
||||
},
|
||||
);
|
||||
let ui = self.clone();
|
||||
@@ -1131,7 +1250,7 @@ impl Ui {
|
||||
ui.opening.set(false);
|
||||
match reply {
|
||||
Ok(Ok(Response::FilePath { path })) => {
|
||||
xdg_open(Path::new(&path));
|
||||
ui.open_materialized(Path::new(&path), &drive.name);
|
||||
ui.dismiss();
|
||||
}
|
||||
Ok(Ok(Response::Error { message, .. })) => {
|
||||
@@ -1224,13 +1343,6 @@ fn spawn_request(
|
||||
rx
|
||||
}
|
||||
|
||||
fn xdg_open(path: &Path) {
|
||||
tracing::info!(path = %path.display(), "opening");
|
||||
if let Err(e) = Command::new("xdg-open").arg(path).spawn() {
|
||||
tracing::error!("xdg-open failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn dirs_home() -> Option<PathBuf> {
|
||||
AppDirs::new().ok().and_then(|dirs| dirs.home_dir())
|
||||
}
|
||||
@@ -1243,6 +1355,21 @@ fn file_name(path: &str) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// An absolute directory path as "Home / …", falling back to the path itself
|
||||
/// for anything outside the home directory.
|
||||
fn home_relative(parent: &str) -> String {
|
||||
match dirs_home().and_then(|home| {
|
||||
Path::new(parent)
|
||||
.strip_prefix(&home)
|
||||
.ok()
|
||||
.map(|rel| rel.display().to_string())
|
||||
}) {
|
||||
Some(rel) if rel.is_empty() => "Home".to_string(),
|
||||
Some(rel) => format!("Home / {}", rel.replace('/', " / ")),
|
||||
None => parent.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_of(path: &str) -> String {
|
||||
Path::new(path)
|
||||
.parent()
|
||||
@@ -1466,4 +1593,42 @@ mod tests {
|
||||
assert!(matches!(&hits[0], Hit::Local(hit) if hit.name == "better.pdf"));
|
||||
assert!(matches!(&hits[1], Hit::Drive(hit) if hit.name == "alpha.pdf"));
|
||||
}
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Args, String> {
|
||||
parse_args(args.iter().map(|a| (*a).to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_arguments_defer_the_mode_to_config() {
|
||||
let args = parse(&[]).unwrap();
|
||||
assert_eq!(args.mode, None);
|
||||
assert_eq!(args.menu, None);
|
||||
assert_eq!(args.query, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_a_launcher_implies_dmenu_but_an_explicit_mode_still_wins() {
|
||||
let args = parse(&["--menu", "fuzzel --dmenu"]).unwrap();
|
||||
assert_eq!(args.mode, Some(PromptMode::Dmenu));
|
||||
assert_eq!(
|
||||
args.menu,
|
||||
Some(vec!["fuzzel".to_string(), "--dmenu".to_string()])
|
||||
);
|
||||
|
||||
let args = parse(&["--gtk", "--menu", "rofi -dmenu"]).unwrap();
|
||||
assert_eq!(args.mode, Some(PromptMode::Gtk));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flag_without_its_value_is_an_error_not_a_default() {
|
||||
assert!(parse(&["--menu"]).is_err());
|
||||
assert!(parse(&["--query"]).is_err());
|
||||
assert!(parse(&["--nonsense"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_is_taken_verbatim_including_spaces() {
|
||||
let args = parse(&["--dmenu", "--query", "tax return 2024"]).unwrap();
|
||||
assert_eq!(args.query.as_deref(), Some("tax return 2024"));
|
||||
}
|
||||
}
|
||||
+113
@@ -12,6 +12,119 @@ Conventions:
|
||||
|
||||
---
|
||||
|
||||
## B82 — A `parent_uid` cycle hangs the daemon on any short search
|
||||
|
||||
**Status:** Fixed (unverified) 2026-08-12 — unit-tested, not driven against a
|
||||
real corrupted database (nobody has one).
|
||||
**Found:** 2026-08-12, writing a test for B80. The test built a two-node cycle
|
||||
and called `search`; `cargo test -p pdfs-core` then sat at
|
||||
`search_excludes_a_parent_cycle` for 29 minutes with **zero CPU** before it was
|
||||
killed. Two earlier runs had already been abandoned to the same stall without
|
||||
the cause being understood — it looks exactly like a cargo lock contention
|
||||
problem, which is what it was first blamed on.
|
||||
**Where:** `path_of` (`crates/pdfs-core/src/db/utils.rs`), `upsert_node_tx`'s
|
||||
`descendants` CTE (`db/nodes.rs`).
|
||||
|
||||
**Root cause.** Both walks are recursive CTEs using `UNION ALL`, which does not
|
||||
deduplicate, so `a.parent = b, b.parent = a` never terminates. The index side
|
||||
was never exposed — `node_is_indexable_tx` rejects a cycle — but a query shorter
|
||||
than `TRIGRAM_MIN` (3 chars) takes the `LIKE` lane, and **that lane reads
|
||||
`nodes` directly and never consults the index**. Every row it returns is then
|
||||
handed to `path_of`. So typing two characters into the prompt was enough, and
|
||||
the spin happens while holding the daemon's only SQLite connection: the mount,
|
||||
the drain, and every control request stop with it.
|
||||
|
||||
The API is what would produce such a cycle (a rename/move race, a malformed
|
||||
event), so this is not a "corrupt your own DB" scenario only.
|
||||
|
||||
**Fix.** `path_of` is depth-capped at 256 and returns the truncated path rather
|
||||
than hanging; `path_relative_to` already carried a 1024 cap, which is the
|
||||
precedent. The `descendants` CTE in `upsert_node_tx` got the same guard for the
|
||||
write side. Cycles also stay out of the index (see B80).
|
||||
|
||||
**Still open:** `pin_is_pinned`'s ancestor walk (`db/pins.rs`) has the same
|
||||
shape and no guard. Not reached from search, so it was left alone.
|
||||
|
||||
## B81 — Prompt labels every Drive hit "My files", including device folders
|
||||
|
||||
**Status:** Fixed (unverified) 2026-08-12 — needs a GUI/dmenu run.
|
||||
**Found:** 2026-08-12, reading the prompt while fixing B80: with B80 fixed, a
|
||||
device-folder hit would render as `My files / Downloads`, a folder that does not
|
||||
exist under the primary mount, while activating the same row opens
|
||||
`~/Downloads/…`. Label and action disagreed.
|
||||
**Where:** `Hit::location()` (`crates/pdfs-gui/src/prompt.rs`), shared by the
|
||||
GTK prompt and the dmenu front-end.
|
||||
|
||||
The label was built from `SearchHit::path` with a hardcoded `My files /` prefix.
|
||||
The daemon already resolves a device/sync-folder hit to a real local path in
|
||||
`mounted_path` (`Core::mounted_search_path`), which is also what activation
|
||||
uses; the label now derives from that when it is set, and falls back to
|
||||
`My files` only for the primary mount.
|
||||
|
||||
**Second defect, same area.** Pin rows set `is_dir` from `Pin::recursive`
|
||||
(`prompt.rs`, `dmenu.rs`). That flag is pin *policy* — whether the subtree is
|
||||
kept on disk — not node kind, so a folder pinned non-recursively drew a file
|
||||
icon and sent an invalid `OpenFile`. `Pin` now carries an `is_dir: Option<bool>`
|
||||
resolved from the `nodes` row by `pin_list`, serde-defaulted so an older daemon
|
||||
(which omits it) still parses; front-ends fall back to `recursive` only when the
|
||||
node is not cached.
|
||||
|
||||
## B80 — 29% of the account is absent from the search index
|
||||
|
||||
**Status:** Fixed (unverified) 2026-08-12 — migration replayed against a
|
||||
read-only copy of the live DB; not yet run by the daemon itself.
|
||||
**Found:** 2026-08-12, auditing `cache.db` after a user report that search felt
|
||||
unreliable. `pdfs search tickets` returned only the My Files folder
|
||||
`Documents/Tickets`, never the `tickets.pdf` sitting in the device folder
|
||||
`Downloads`. Counting the tables explained it:
|
||||
|
||||
```
|
||||
nodes 9252
|
||||
nodes_fts 6547 ← 2705 rows never indexed
|
||||
nodes in orphan subtrees 2705 ← exactly the missing set
|
||||
```
|
||||
|
||||
**Where:** `node_is_indexable_tx` (`crates/pdfs-core/src/db/nodes.rs`).
|
||||
|
||||
**Root cause — the same one as B79.** A node was indexed only if walking
|
||||
`parent_uid` reached a row with `parent_uid IS NULL`. Exactly one row is stored
|
||||
that way (the My Files root). A device folder's root lives in `device` /
|
||||
`sync_folder` and is **never persisted as a `nodes` row**, so `Downloads`,
|
||||
`Pictures`, `Documents`, `Music` and `Videos` walk up to a parent that does not
|
||||
exist and were judged unindexable, along with everything beneath them. Stale
|
||||
`pdfs-acceptance-*` roots hit the same path.
|
||||
|
||||
The v16 backfill did *not* share the bug — it rooted its walk at any node whose
|
||||
parent is null **or absent**. So the index was correct immediately after
|
||||
migrating and then lost each subtree the first time one of its nodes was
|
||||
rewritten. That divergence between backfill and write path is why this survived:
|
||||
a fresh install looks fine.
|
||||
|
||||
**Fix.** Indexability now requires only that the walk terminates with nothing
|
||||
trashed on the way; a cycle is still rejected explicitly (B82). `MIGRATION_V21`
|
||||
(`SCHEMA_VERSION` → 21) rebuilds `nodes_fts` so existing installs recover
|
||||
without waiting for each node to be rewritten, and fixes two gaps in the v16
|
||||
walk it replays: descendants of a trashed folder stay out, and the walk is
|
||||
depth-capped.
|
||||
|
||||
Replayed against a `.backup` of the live DB: **9276 non-trashed nodes → 9276
|
||||
indexed** (from 6547), 300 rows under `Downloads`, `tickets.pdf` at
|
||||
`Downloads/tickets.pdf`.
|
||||
|
||||
**Watch for.** That path is the second thing this uncovered: the backfill first
|
||||
seeded an uncached-parent root with an empty path, so the migration indexed
|
||||
`tickets.pdf` while a later upsert indexed `Downloads/tickets.pdf` — the same
|
||||
node with two paths depending on which code wrote it. Any future rebuild of this
|
||||
index has to match `path_of`, not invent its own root rule.
|
||||
|
||||
**Related, not a defect.** The local half of the prompt indexes 110,187 files,
|
||||
63,399 of them (58%) the Go module cache. Candidates are capped at 1000 and
|
||||
scored *after* SQLite, so for a common term the pool filled with vendored files
|
||||
before a real one was considered — for "test", 367 of the 500 best-ranked
|
||||
candidates came from `go/pkg/mod`. `SKIP_DIRS` gained `dist`/`build`, a new
|
||||
`SKIP_PATH_SUFFIXES` covers `go/pkg/mod`, and both candidate functions gained a
|
||||
whole-query prefix lane ahead of the existing single-character one.
|
||||
|
||||
## B79 — Every write in an on-demand device-folder mount fails EACCES
|
||||
|
||||
**Status:** Fixed (verified live 2026-07-31, running in a locally rebuilt 1.2.1
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# Search index + prompt display fixes
|
||||
|
||||
Working plan. Findings come from an audit of a real `cache.db`
|
||||
(9,252 Drive nodes, 110,187 local files) on 2026-08-12.
|
||||
|
||||
## Evidence
|
||||
|
||||
```
|
||||
nodes 9252
|
||||
nodes_fts 6547 ← 2705 rows never indexed
|
||||
nodes in orphan subtrees 2705 ← exactly the missing set
|
||||
local_files 110187
|
||||
/home/narl/go/pkg/mod 63399 (58% of the local index)
|
||||
query "test" 46405 local matches, candidate pool capped at 1000
|
||||
top 500 by fts rank 367 (73%) from go/pkg/mod
|
||||
```
|
||||
|
||||
`pdfs search tickets` returns only `Documents/Tickets` (My Files); the
|
||||
`tickets.pdf` sitting in the device folder `Downloads` is invisible.
|
||||
|
||||
## P1 — 29% of Drive is unsearchable
|
||||
|
||||
`node_is_indexable_tx` (`crates/pdfs-core/src/db/nodes.rs:606`) indexes a node
|
||||
only when the ancestor walk terminates at a row with `parent_uid IS NULL`. The
|
||||
DB holds exactly one such row (the My Files root). Device roots live in
|
||||
`device`/`sync_folder`, never in `nodes`, so every device-folder subtree
|
||||
(`Downloads`, `Pictures`, `Documents`, `Music`, `Videos` under device
|
||||
*nthinkpad*) walks up to a `parent_uid` with no row and is judged unindexable.
|
||||
Stale `pdfs-acceptance-*` roots hit the same path.
|
||||
|
||||
- [x] Relax the rule to "the walk terminates and no ancestor is trashed",
|
||||
keeping the existing cycle guard. A subtree whose top row's parent is
|
||||
simply not cached is still real, reachable data.
|
||||
- [x] `MIGRATION_V21`: rebuild `nodes_fts` under the new rule, so existing
|
||||
installs recover the missing rows instead of waiting for each node to be
|
||||
upserted again.
|
||||
- [x] Tests: a node under an uncached parent is indexed; a trashed ancestor
|
||||
still excludes; the migration backfills.
|
||||
|
||||
### Found while testing: a parent cycle hangs the daemon
|
||||
|
||||
Writing the cycle test surfaced a live defect, not a test artefact. A query
|
||||
below the trigram minimum takes the `LIKE` lane, which reads `nodes` directly
|
||||
and never consults the index, and every row it returns goes through `path_of` —
|
||||
whose parent walk is an unguarded `UNION ALL`. On a `parent_uid` cycle it never
|
||||
terminates, while holding the daemon's only SQLite connection.
|
||||
|
||||
- [x] Depth-cap `path_of` (`db/utils.rs`), matching the 1024 cap
|
||||
`path_relative_to` already carried.
|
||||
- [x] Depth-cap the `descendants` CTE in `upsert_node_tx`, which has the same
|
||||
exposure on the write side.
|
||||
- [x] Keep cycles out of the index (part of the P1 rule above).
|
||||
|
||||
Still unguarded, not touched here: `pin_is_pinned`'s ancestor walk.
|
||||
|
||||
## P2 — local index noise crowds real files out of the candidate pool
|
||||
|
||||
`SKIP_DIRS` (`crates/pdfs-core/src/localindex.rs:23`) misses the Go module
|
||||
cache and build output dirs. `search_v2` clamps candidates to ≤1000 and scores
|
||||
*after* SQLite, so for any common term the pool is exhausted by vendored files
|
||||
before a real one is considered.
|
||||
|
||||
- [x] Skip `go/pkg/mod` (path-relative, not a bare name), `dist`, `build`,
|
||||
`.cache`-style artefact dirs.
|
||||
- [x] Give `search_local_candidates` a name-prefix lane, mirroring what
|
||||
`search_candidates` already does for Drive, so an exact-prefix match
|
||||
cannot be starved by trigram rank.
|
||||
- [x] Tests for both.
|
||||
|
||||
## P3 — display lies about where a hit lives
|
||||
|
||||
- [x] `Hit::location()` (`crates/pdfs-gui/src/prompt.rs:150`) hardcodes
|
||||
`My files / …` for every Drive hit. Derive the label from
|
||||
`mounted_path` when the daemon resolved one (device folder, sync folder)
|
||||
and fall back to `My files` only for the primary mount.
|
||||
- [x] Pin rows set `is_dir: pin.recursive` (`dmenu.rs:133`, `prompt.rs:872`) —
|
||||
a non-recursively pinned folder renders and activates as a file.
|
||||
- [ ] `pdfs locations` prints `Device folder 1..5` rather than the device and
|
||||
folder name. (Cosmetic; deferred.)
|
||||
|
||||
## Verification
|
||||
|
||||
Done, 2026-08-12:
|
||||
|
||||
```
|
||||
cargo fmt --all -- --check clean
|
||||
cargo clippy --workspace --all-targets -- -D warnings clean
|
||||
cargo test --workspace --locked 439 passed, 0 failed
|
||||
```
|
||||
|
||||
The V21 backfill was also replayed against a read-only `.backup` of the live
|
||||
`cache.db`:
|
||||
|
||||
```
|
||||
live_nodes 9276
|
||||
indexed 9276 (was 6547)
|
||||
downloads_subtree 300
|
||||
tickets.pdf -> Downloads/tickets.pdf
|
||||
```
|
||||
|
||||
That run is what caught the last defect: the backfill originally seeded an
|
||||
uncached-parent root with an empty path, so a node indexed by the migration
|
||||
(`tickets.pdf`) and the same node after a later upsert (`Downloads/tickets.pdf`)
|
||||
disagreed. The seed now keeps the name for any row that has a parent, matching
|
||||
`path_of`.
|
||||
|
||||
Still to do, on the live system: rebuild, restart `proton-drive.service`, and
|
||||
confirm `pdfs search tickets` returns the device folder's `tickets.pdf`. The
|
||||
schema move to 21 is one-way — an older `pdfs` refuses a v21 database. The
|
||||
`local_files` shrink (~110k → ~47k) lands with the next background scan.
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
# Build + install: cd packaging && makepkg -fi
|
||||
|
||||
pkgname=proton-drive-linux
|
||||
pkgver=1.4.0
|
||||
pkgver=1.6.0
|
||||
pkgrel=1
|
||||
pkgdesc="Proton Drive client for Linux: FUSE files-on-demand mount, CLI, GTK4 app + tray"
|
||||
arch=('x86_64')
|
||||
|
||||
Reference in new issue
Block a user