Skip to main content

jump_core/
files.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! File search.
5//!
6//! ## Why we build our own index
7//!
8//! The system `plocate` database is not usable for this. On a btrfs machine
9//! running snapper it contained 37,153,401 paths of which **36,496,775 were
10//! under `/.snapshots/`** — 98.2% of the index is snapshot duplicates of the
11//! same files. Every one of the first 2000 results for `config` came from a
12//! snapshot, so filtering them out after the fact returns nothing: the limit is
13//! exhausted long before a real file appears.
14//!
15//! Editing `/etc/updatedb.conf` would fix that, but it needs root, it is a
16//! system-wide change made on the user's behalf, and it still would not index
17//! removable drives. Building a private database instead solves all three at
18//! once and costs 8.75 s for 1.5 M entries in a 44 MB file — cheap enough to
19//! refresh on a timer.
20//!
21//! ## Why ranking has to be separate from matching
22//!
23//! `plocate` answers "which paths contain this substring" in order of database
24//! position, which is essentially filesystem order. It has no notion of
25//! relevance, so the raw answer for a common word is thousands of equally-ranked
26//! paths. Useful results come from over-fetching a bounded candidate set and
27//! ranking it here, in two phases:
28//!
29//! 1. **String-only scoring** over every candidate. No syscalls, so it can run
30//!    over thousands of paths within a frame.
31//! 2. **Filesystem scoring** over only the survivors — `stat` is a syscall per
32//!    file, so it runs on ~100 paths, not 2000.
33
34use std::collections::HashSet;
35use std::path::{Path, PathBuf};
36use std::process::Stdio;
37use std::time::{Duration, SystemTime};
38
39use tokio::process::Command;
40
41use crate::model::{Icon, Item, ItemKey, Source};
42
43/// Paths fetched from the index before ranking.
44///
45/// Large enough that the good answer is almost certainly somewhere in the set,
46/// small enough that scoring stays well inside a frame. Measured at ~20 ms for
47/// 2000 candidates, dominated by `plocate` itself rather than by scoring.
48const CANDIDATES: usize = 2000;
49
50/// Paths fetched per extension when enumerating content-index candidates.
51///
52/// Generous because this runs in the background, not per keystroke, but still
53/// bounded so one pathological extension cannot dominate the pass.
54const CONTENT_CANDIDATES: usize = 20_000;
55
56/// Candidates promoted to the `stat` phase.
57const STAT_BUDGET: usize = 120;
58
59/// Results returned to the UI.
60const RESULTS: usize = 12;
61
62/// A plugin-style deadline: file search must never delay the frame.
63const QUERY_TIMEOUT: Duration = Duration::from_millis(250);
64
65/// Directory names that are never worth indexing.
66///
67/// These are build and cache trees: high file counts, near-zero chance the user
68/// is searching for something inside them by name.
69const PRUNE_NAMES: &str = ".git node_modules .cache __pycache__ .venv venv target .next .nuxt \
70     .gradle .tox .mypy_cache .pytest_cache .terraform vendor .snapshots .Trash-1000 Trash \
71     .cargo .rustup .npm .pnpm-store .yarn .bun .deno .m2 .ivy2 .nuget .conda .rbenv \
72     .pyenv .nvm .stack .cabal .ccache .zig-cache .swiftpm";
73
74/// Query tokens shorter than this are not worth sending to the index on their
75/// own — they match nearly everything.
76const MIN_TOKEN: usize = 2;
77
78/// What to index and what to return. Comes from the user's configuration.
79#[derive(Debug, Clone)]
80pub struct Config {
81    /// Whether file search runs at all.
82    pub enabled: bool,
83    /// Trees to index. Defaults to the user's home directory.
84    pub roots: Vec<PathBuf>,
85    /// Directory names never to index, in addition to the built-in list.
86    ///
87    /// Applied at index time, so excluding a large tree makes the index both
88    /// smaller and faster to build — unlike a query-time filter, which pays for
89    /// the paths anyway.
90    pub ignore_names: Vec<String>,
91    /// Absolute paths never to index.
92    pub ignore_paths: Vec<PathBuf>,
93    /// If non-empty, only files with these extensions are returned.
94    ///
95    /// Applied at query time rather than index time: it is the setting most
96    /// likely to be changed on a whim, and re-indexing after every change would
97    /// be a poor trade for a filter this cheap.
98    pub include_extensions: Vec<String>,
99    /// Extensions never returned, beyond the built-in noise list.
100    pub exclude_extensions: Vec<String>,
101    /// Also index mounted external volumes (NTFS drives and the like).
102    ///
103    /// Off by default: these are frequently multi-terabyte, and indexing one
104    /// takes minutes rather than seconds.
105    pub external_drives: bool,
106    /// How stale the index may get before it is rebuilt.
107    pub refresh: Duration,
108}
109
110impl Default for Config {
111    fn default() -> Self {
112        Self {
113            enabled: true,
114            roots: dirs::home_dir().into_iter().collect(),
115            ignore_names: Vec::new(),
116            ignore_paths: Vec::new(),
117            include_extensions: Vec::new(),
118            exclude_extensions: Vec::new(),
119            external_drives: false,
120            refresh: Duration::from_secs(6 * 3600),
121        }
122    }
123}
124
125/// File search backed by a private `plocate` database.
126#[derive(Debug, Clone)]
127pub struct Files {
128    config: Config,
129    /// Databases to search, most important first.
130    databases: Vec<PathBuf>,
131    data_dir: PathBuf,
132}
133
134impl Files {
135    /// Build a searcher for `config`.
136    ///
137    /// Returns `None` when file search is disabled, or when no XDG data
138    /// directory is available to hold the index.
139    #[must_use]
140    pub fn new(config: Config) -> Option<Self> {
141        if !config.enabled {
142            return None;
143        }
144        let data_dir = dirs::data_dir()?.join("jump").join("index");
145
146        let mut files = Self {
147            config,
148            databases: Vec::new(),
149            data_dir,
150        };
151        files.databases = files.existing_databases();
152        Some(files)
153    }
154
155    fn home_db(&self) -> PathBuf {
156        self.data_dir.join("home.db")
157    }
158
159    fn external_db(&self) -> PathBuf {
160        self.data_dir.join("external.db")
161    }
162
163    /// Databases that exist on disk right now.
164    ///
165    /// `plocate` aborts the whole query if any database in the list is missing,
166    /// so a stale path must never be passed to it.
167    fn existing_databases(&self) -> Vec<PathBuf> {
168        let mut databases = Vec::new();
169        if self.home_db().is_file() {
170            databases.push(self.home_db());
171        }
172        if self.config.external_drives && self.external_db().is_file() {
173            databases.push(self.external_db());
174        }
175        databases
176    }
177
178    /// Whether any index exists yet.
179    #[must_use]
180    pub fn is_ready(&self) -> bool {
181        !self.databases.is_empty()
182    }
183
184    /// Whether the index is missing or older than the refresh interval.
185    #[must_use]
186    pub fn needs_refresh(&self) -> bool {
187        let Ok(metadata) = std::fs::metadata(self.home_db()) else {
188            return true;
189        };
190        let Ok(modified) = metadata.modified() else {
191            return true;
192        };
193        SystemTime::now()
194            .duration_since(modified)
195            .is_ok_and(|age| age > self.config.refresh)
196    }
197
198    /// Rebuild the index.
199    ///
200    /// Runs `updatedb` per root. This takes seconds for a home directory and
201    /// minutes for a multi-terabyte drive, so it is never called on the
202    /// interactive path — the caller schedules it.
203    pub async fn rebuild(&mut self) {
204        if let Err(error) = tokio::fs::create_dir_all(&self.data_dir).await {
205            tracing::warn!(%error, dir = ?self.data_dir, "cannot create index directory");
206            return;
207        }
208
209        let roots: Vec<PathBuf> = self
210            .config
211            .roots
212            .iter()
213            .filter(|root| root.is_dir())
214            .cloned()
215            .collect();
216
217        if !roots.is_empty() {
218            build_database(&roots, &self.home_db(), &self.config).await;
219        }
220
221        if self.config.external_drives {
222            let external = external_mounts();
223            if external.is_empty() {
224                tracing::info!("no external volumes mounted; skipping external index");
225            } else {
226                tracing::info!(count = external.len(), "indexing external volumes");
227                build_database(&external, &self.external_db(), &self.config).await;
228            }
229        }
230
231        self.databases = self.existing_databases();
232    }
233
234    /// Search the index and return ranked results.
235    pub async fn search(&self, query: &str) -> Vec<Item> {
236        if self.databases.is_empty() {
237            return Vec::new();
238        }
239
240        let tokens = tokenize(query);
241        let Some(probe) = tokens.iter().max_by_key(|token| token.len()) else {
242            return Vec::new();
243        };
244        if probe.len() < MIN_TOKEN {
245            return Vec::new();
246        }
247
248        let candidates = self.candidates(probe).await;
249        if candidates.is_empty() {
250            return Vec::new();
251        }
252
253        let candidates: Vec<String> = candidates
254            .into_iter()
255            .filter(|path| self.extension_allowed(path))
256            .collect();
257
258        rank(candidates, &tokens).await
259    }
260
261    /// Paths worth handing to the content indexer.
262    ///
263    /// Enumerated from the path index rather than by walking the tree again:
264    /// `updatedb` already did that walk, and asking `plocate` for one extension
265    /// at a time is both faster and automatically consistent with whatever the
266    /// index excludes.
267    pub async fn content_candidates(&self, extensions: &[String]) -> Vec<PathBuf> {
268        let mut candidates: Vec<(u8, PathBuf)> = Vec::new();
269        let mut seen = HashSet::new();
270
271        for extension in extensions {
272            let needle = normalise_extension(extension);
273            for path in self.candidates_for(&needle, CONTENT_CANDIDATES).await {
274                // plocate matches substrings, so `.ts` also returns `.tsx`.
275                if !path.to_lowercase().ends_with(&needle) {
276                    continue;
277                }
278                if !seen.insert(path.clone()) {
279                    continue;
280                }
281                candidates.push((index_priority(&path), PathBuf::from(path)));
282            }
283        }
284
285        // Highest priority first. The content index has a size ceiling, so the
286        // *order* decides what survives when it is reached: documents the user
287        // wrote should be indexed before scratch files and dotfile trees, not
288        // whichever extension happened to be enumerated first.
289        candidates.sort_by_key(|(priority, _)| std::cmp::Reverse(*priority));
290        candidates.into_iter().map(|(_, path)| path).collect()
291    }
292
293    /// Whether a path survives the configured extension filters.
294    fn extension_allowed(&self, path: &str) -> bool {
295        let lower = path.to_lowercase();
296
297        if self
298            .config
299            .exclude_extensions
300            .iter()
301            .any(|ext| lower.ends_with(&normalise_extension(ext)))
302        {
303            return false;
304        }
305
306        if self.config.include_extensions.is_empty() {
307            return true;
308        }
309
310        // Directories have no extension but are still worth showing when the
311        // user has restricted the result types, since they contain them.
312        self.config
313            .include_extensions
314            .iter()
315            .any(|ext| lower.ends_with(&normalise_extension(ext)))
316    }
317
318    /// Ask `plocate` for paths whose basename contains `probe`.
319    ///
320    /// `--basename` matters: a whole-path match for `config` hits every file
321    /// under every directory called `config`, which buries the file actually
322    /// named `config`.
323    async fn candidates(&self, probe: &str) -> Vec<String> {
324        self.candidates_for(probe, CANDIDATES).await
325    }
326
327    /// Ask `plocate` for up to `limit` basename matches.
328    async fn candidates_for(&self, probe: &str, limit: usize) -> Vec<String> {
329        // plocate accepts several databases as one colon-separated argument.
330        let databases = self
331            .databases
332            .iter()
333            .filter_map(|path| path.to_str())
334            .collect::<Vec<_>>()
335            .join(":");
336
337        let output = Command::new("plocate")
338            .arg("--database")
339            .arg(&databases)
340            .arg("--basename")
341            .arg("--ignore-case")
342            .arg("--limit")
343            .arg(limit.to_string())
344            .arg(probe)
345            .stdin(Stdio::null())
346            .stdout(Stdio::piped())
347            .stderr(Stdio::null())
348            .kill_on_drop(true)
349            .output();
350
351        let output = match tokio::time::timeout(QUERY_TIMEOUT, output).await {
352            Ok(Ok(output)) => output,
353            Ok(Err(error)) => {
354                tracing::warn!(%error, "plocate failed to run");
355                return Vec::new();
356            }
357            Err(_) => {
358                tracing::warn!("file search exceeded its deadline");
359                return Vec::new();
360            }
361        };
362
363        // plocate exits non-zero when nothing matched, which is not an error.
364        String::from_utf8_lossy(&output.stdout)
365            .lines()
366            .map(ToOwned::to_owned)
367            .collect()
368    }
369}
370
371/// Run `updatedb` over `roots` into `output`.
372async fn build_database(roots: &[PathBuf], output: &Path, config: &Config) {
373    // updatedb takes a single root, so multiple roots mean multiple databases.
374    // Rather than juggle a database per root, index the common ancestor when
375    // there is one and otherwise index each root into a temporary and keep the
376    // last — in practice `roots` is the home directory alone.
377    let Some(root) = roots.first() else {
378        return;
379    };
380    if roots.len() > 1 {
381        tracing::warn!(
382            extra = roots.len() - 1,
383            "updatedb indexes one root per database; only the first is indexed"
384        );
385    }
386
387    let started = SystemTime::now();
388    let result = Command::new("updatedb")
389        .arg("--database-root")
390        .arg(root)
391        .arg("--output")
392        .arg(output)
393        // Without this, updatedb records only paths readable by everyone, which
394        // for a private index of the user's own home is exactly backwards.
395        .arg("--require-visibility")
396        .arg("no")
397        .arg("--prune-bind-mounts")
398        .arg("yes")
399        .arg("--add-prunenames")
400        .arg(prune_names(config))
401        .arg("--add-prunepaths")
402        .arg(prune_paths(config))
403        .stdin(Stdio::null())
404        .stdout(Stdio::null())
405        .stderr(Stdio::piped())
406        .kill_on_drop(true)
407        .output()
408        .await;
409
410    match result {
411        Ok(output_result) if output_result.status.success() => {
412            let elapsed = started.elapsed().unwrap_or_default();
413            tracing::info!(?root, ?elapsed, "index rebuilt");
414        }
415        Ok(output_result) => {
416            let stderr = String::from_utf8_lossy(&output_result.stderr);
417            tracing::warn!(?root, %stderr, "updatedb failed");
418        }
419        Err(error) => tracing::warn!(%error, "could not run updatedb"),
420    }
421}
422
423/// Indexing priority for a path, higher first.
424///
425/// Deliberately coarse. The aim is to get the user's own documents and projects
426/// in before anything else, not to produce a finely-graded ordering — a
427/// three-way split does nearly all the work a hundred rules would.
428fn index_priority(path: &str) -> u8 {
429    const PREFERRED: &[&str] = &[
430        "/documents/",
431        "/desktop/",
432        "/projects/",
433        "/github/",
434        "/work/",
435        "/notes/",
436        "/src/",
437    ];
438
439    let lower = path.to_lowercase();
440
441    // Hidden trees are configuration and state: occasionally useful to search,
442    // never the first thing worth spending the index budget on.
443    if lower.contains("/.") {
444        return 0;
445    }
446    if PREFERRED.iter().any(|dir| lower.contains(dir)) {
447        return 2;
448    }
449    1
450}
451
452/// Built-in prune list plus anything the user added.
453fn prune_names(config: &Config) -> String {
454    if config.ignore_names.is_empty() {
455        return PRUNE_NAMES.to_owned();
456    }
457    format!("{PRUNE_NAMES} {}", config.ignore_names.join(" "))
458}
459
460/// User-specified absolute paths to skip. Space-separated, as updatedb expects.
461fn prune_paths(config: &Config) -> String {
462    config
463        .ignore_paths
464        .iter()
465        .filter_map(|path| path.to_str())
466        .collect::<Vec<_>>()
467        .join(" ")
468}
469
470/// Mounted volumes that look like removable or external storage.
471///
472/// Derived from `/proc/mounts` rather than a configured list so that plugging a
473/// drive in does not require editing configuration. NTFS is the common case, but
474/// exFAT and ext4 externals are picked up the same way.
475fn external_mounts() -> Vec<PathBuf> {
476    const EXTERNAL_FS: &[&str] = &["ntfs3", "ntfs", "fuseblk", "exfat", "vfat"];
477    const EXTERNAL_ROOTS: &[&str] = &["/run/media/", "/media/", "/mnt/"];
478
479    let Ok(mounts) = std::fs::read_to_string("/proc/mounts") else {
480        return Vec::new();
481    };
482
483    let mut seen = HashSet::new();
484    mounts
485        .lines()
486        .filter_map(|line| {
487            let mut fields = line.split_whitespace();
488            let _device = fields.next()?;
489            let mount_point = fields.next()?;
490            let filesystem = fields.next()?;
491
492            // `/proc/mounts` escapes spaces as \040.
493            let mount_point = mount_point.replace("\\040", " ");
494
495            let external = EXTERNAL_FS.contains(&filesystem)
496                || EXTERNAL_ROOTS
497                    .iter()
498                    .any(|root| mount_point.starts_with(root));
499
500            (external && seen.insert(mount_point.clone())).then(|| PathBuf::from(mount_point))
501        })
502        .filter(|path| path.is_dir())
503        .collect()
504}
505
506/// Accept extensions written either as `pdf` or `.pdf`.
507fn normalise_extension(extension: &str) -> String {
508    let lower = extension.trim().to_lowercase();
509    if lower.starts_with('.') {
510        lower
511    } else {
512        format!(".{lower}")
513    }
514}
515
516/// Split a query into lowercase tokens.
517fn tokenize(query: &str) -> Vec<String> {
518    query
519        .split_whitespace()
520        .map(str::to_lowercase)
521        .filter(|token| !token.is_empty())
522        .collect()
523}
524
525/// Score and order candidates, then attach filesystem signals to the survivors.
526async fn rank(candidates: Vec<String>, tokens: &[String]) -> Vec<Item> {
527    let mut scored: Vec<(f32, String)> = candidates
528        .into_iter()
529        .filter_map(|path| score_path(&path, tokens).map(|score| (score, path)))
530        .collect();
531
532    scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
533    scored.truncate(STAT_BUDGET);
534
535    // Phase two: only now does anything touch the filesystem.
536    let now = SystemTime::now();
537    let mut refined: Vec<(f32, PathBuf)> = Vec::with_capacity(scored.len());
538    for (score, path) in scored {
539        let path = PathBuf::from(path);
540        let Ok(metadata) = tokio::fs::metadata(&path).await else {
541            // Indexed but gone: the database is a snapshot, not the truth.
542            continue;
543        };
544
545        let mut score = score;
546        if metadata.is_dir() {
547            // Directories are usually a means to a file, not the destination.
548            score -= 0.15;
549        }
550        if let Ok(modified) = metadata.modified()
551            && let Ok(age) = now.duration_since(modified)
552        {
553            score += recency_bonus(age);
554        }
555        refined.push((score, path));
556    }
557
558    refined.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
559    refined.truncate(RESULTS);
560
561    refined
562        .into_iter()
563        .map(|(score, path)| item(&path, score))
564        .collect()
565}
566
567/// Recency contribution, on the same scale as the string signals.
568///
569/// Bucketed rather than continuous for the same reason frecency is: a file must
570/// not drift down the list while the user is looking at it.
571fn recency_bonus(age: Duration) -> f32 {
572    const DAY: u64 = 86_400;
573    match age.as_secs() {
574        0..=DAY => 0.5,
575        secs if secs <= 7 * DAY => 0.3,
576        secs if secs <= 30 * DAY => 0.15,
577        _ => 0.0,
578    }
579}
580
581/// String-only relevance. `None` rejects the candidate outright.
582fn score_path(path: &str, tokens: &[String]) -> Option<f32> {
583    let lower = path.to_lowercase();
584
585    // Every token must appear somewhere in the path. plocate only guaranteed
586    // the probe token, so this is what makes multi-word queries behave: typing
587    // "cargo toml" should not return every Cargo.toml on the system.
588    if !tokens.iter().all(|token| lower.contains(token.as_str())) {
589        return None;
590    }
591
592    let basename = lower.rsplit('/').next().unwrap_or(&lower);
593    let mut score = 0.0;
594
595    // The strongest signal by far: how well the *name* matches, not the path.
596    let longest = tokens.iter().max_by_key(|token| token.len())?;
597    score += name_match(basename, longest) * 3.0;
598
599    // Every token that also hits the basename is worth more than one that only
600    // matched somewhere up the directory tree.
601    let in_name = tokens
602        .iter()
603        .filter(|token| basename.contains(token.as_str()))
604        .count();
605    score += in_name as f32 * 0.4;
606
607    // Shallow paths are more likely to be what someone means. Capped so that a
608    // deeply-nested exact match still beats a shallow partial one.
609    let depth = path.matches('/').count();
610    score -= (depth as f32 * 0.06).min(0.9);
611
612    // Hidden files are usually configuration the user did not ask for, unless
613    // they typed a leading dot.
614    let hidden = lower.contains("/.");
615    if hidden && !tokens.iter().any(|token| token.starts_with('.')) {
616        score -= 0.8;
617    }
618
619    score += location_prior(&lower);
620    score += extension_prior(basename);
621
622    Some(score)
623}
624
625/// How well `name` matches `token`, in 0.0..=1.0.
626///
627/// plocate already guaranteed a substring match somewhere, so this is about
628/// *where* and *how much* of the name the token accounts for.
629fn name_match(name: &str, token: &str) -> f32 {
630    let Some(position) = name.find(token) else {
631        return 0.0;
632    };
633
634    if name == token {
635        1.0
636    } else if position == 0 {
637        // Prefix match, scaled by how much of the name the token covers, so
638        // "cargo" scores higher against "cargo.toml" than against
639        // "cargo-something-very-long".
640        0.75 + 0.2 * (token.len() as f32 / name.len() as f32)
641    } else if name[..position].ends_with(['-', '_', '.', ' ']) {
642        // Start of a word inside the name.
643        0.6
644    } else {
645        0.35
646    }
647}
648
649/// Directory-based priors, expressed as a bonus or penalty.
650fn location_prior(lower: &str) -> f32 {
651    const PREFERRED: &[&str] = &[
652        "/documents/",
653        "/desktop/",
654        "/downloads/",
655        "/pictures/",
656        "/projects/",
657        "/github/",
658        "/src/",
659        "/work/",
660    ];
661    const DEPRIORITISED: &[&str] = &[
662        "/.local/",
663        "/.config/",
664        "/.mozilla/",
665        "/.steam/",
666        "/site-packages/",
667        "/dist-packages/",
668        "/.wine/",
669        "/proton/",
670    ];
671
672    let mut prior = 0.0;
673    if PREFERRED.iter().any(|dir| lower.contains(dir)) {
674        prior += 0.6;
675    }
676    if DEPRIORITISED.iter().any(|dir| lower.contains(dir)) {
677        prior -= 0.7;
678    }
679    prior
680}
681
682/// Extension-based priors: things people open beat build residue.
683fn extension_prior(basename: &str) -> f32 {
684    const DOCUMENTS: &[&str] = &[
685        ".pdf", ".odt", ".docx", ".doc", ".md", ".txt", ".epub", ".xlsx", ".ods", ".pptx", ".rtf",
686    ];
687    const MEDIA: &[&str] = &[
688        ".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg", ".mp4", ".mkv", ".mp3", ".flac", ".wav",
689    ];
690    const NOISE: &[&str] = &[
691        ".lock", ".tmp", ".swp", ".pyc", ".o", ".d", ".rlib", ".rmeta", ".log", ".bak", ".part",
692    ];
693
694    if DOCUMENTS.iter().any(|ext| basename.ends_with(ext)) {
695        0.5
696    } else if MEDIA.iter().any(|ext| basename.ends_with(ext)) {
697        0.3
698    } else if NOISE.iter().any(|ext| basename.ends_with(ext)) {
699        -1.2
700    } else {
701        0.0
702    }
703}
704
705/// Open a file with the user's default handler.
706///
707/// Delegates to `xdg-open` rather than resolving the MIME association here:
708/// the desktop already owns that mapping, and duplicating it would diverge.
709pub fn open(path: &Path) {
710    let result = Command::new("xdg-open")
711        .arg(path)
712        .stdin(Stdio::null())
713        .stdout(Stdio::null())
714        .stderr(Stdio::null())
715        .spawn();
716
717    match result {
718        Ok(mut child) => {
719            tokio::spawn(async move {
720                let _ = child.wait().await;
721            });
722        }
723        Err(error) => tracing::error!(%error, ?path, "could not open file"),
724    }
725}
726
727/// Turn a ranked path into a result row.
728fn item(path: &Path, score: f32) -> Item {
729    let title = path.file_name().map_or_else(
730        || path.display().to_string(),
731        |name| name.to_string_lossy().into_owned(),
732    );
733
734    // Show the containing directory, with the home prefix shortened, because the
735    // full path of a deeply-nested file is unreadable at row width.
736    let subtitle = path
737        .parent()
738        .map(|parent| {
739            let text = parent.display().to_string();
740            match dirs::home_dir().and_then(|home| {
741                text.strip_prefix(home.to_str()?)
742                    .map(|rest| format!("~{rest}"))
743            }) {
744                Some(shortened) => shortened,
745                None => text,
746            }
747        })
748        .unwrap_or_default();
749
750    Item {
751        key: ItemKey(format!("file:{}", path.display())),
752        id: 0,
753        title,
754        subtitle,
755        icon: Some(Icon::Name("text-x-generic".to_owned())),
756        category_icon: Some(Icon::Name("system-file-manager".to_owned())),
757        window: None,
758        source: Source::File {
759            path: path.to_path_buf(),
760        },
761        autocomplete: None,
762        score,
763    }
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769
770    fn score(path: &str, query: &str) -> f32 {
771        score_path(path, &tokenize(query)).unwrap_or(f32::MIN)
772    }
773
774    #[test]
775    fn exact_name_beats_partial() {
776        let exact = score("/home/u/documents/report.pdf", "report");
777        let partial = score("/home/u/documents/report-draft-v2.pdf", "report");
778        assert!(exact > partial);
779    }
780
781    #[test]
782    fn shallow_beats_deep() {
783        let shallow = score("/home/u/notes.md", "notes");
784        let deep = score("/home/u/a/b/c/d/e/f/notes.md", "notes");
785        assert!(shallow > deep);
786    }
787
788    #[test]
789    fn build_residue_is_penalised() {
790        let source = score("/home/u/projects/main.rs", "main");
791        let residue = score("/home/u/projects/main.o", "main");
792        assert!(source > residue);
793    }
794
795    #[test]
796    fn hidden_paths_are_penalised_unless_asked_for() {
797        let visible = score("/home/u/projects/config.toml", "config");
798        let hidden = score("/home/u/.config/config.toml", "config");
799        assert!(visible > hidden);
800    }
801
802    #[test]
803    fn all_tokens_must_match() {
804        // The probe token matched, but the second token appears nowhere.
805        assert!(score_path("/home/u/Cargo.toml", &tokenize("cargo nonexistent")).is_none());
806        assert!(score_path("/home/u/jump/Cargo.toml", &tokenize("cargo jump")).is_some());
807    }
808
809    #[test]
810    fn documents_outrank_unknown_types() {
811        let document = score("/home/u/documents/thesis.pdf", "thesis");
812        let unknown = score("/home/u/documents/thesis.xyz", "thesis");
813        assert!(document > unknown);
814    }
815
816    #[test]
817    fn word_boundary_beats_mid_word() {
818        let boundary = score("/home/u/my-report.pdf", "report");
819        let mid = score("/home/u/xxreportxx.pdf", "report");
820        assert!(boundary > mid);
821    }
822
823    fn files_with(config: Config) -> Files {
824        Files {
825            config,
826            databases: vec![PathBuf::from("/nonexistent")],
827            data_dir: PathBuf::from("/tmp"),
828        }
829    }
830
831    #[test]
832    fn documents_are_indexed_before_dotfiles() {
833        assert!(
834            index_priority("/home/u/Documents/thesis.md") > index_priority("/home/u/scratch.md")
835        );
836        assert!(index_priority("/home/u/scratch.md") > index_priority("/home/u/.config/app.md"));
837    }
838
839    #[test]
840    fn include_extensions_restrict_results() {
841        let files = files_with(Config {
842            include_extensions: vec!["pdf".to_owned(), ".md".to_owned()],
843            ..Config::default()
844        });
845
846        assert!(files.extension_allowed("/home/u/report.pdf"));
847        assert!(files.extension_allowed("/home/u/notes.md"));
848        assert!(!files.extension_allowed("/home/u/main.rs"));
849    }
850
851    #[test]
852    fn exclude_extensions_win_over_include() {
853        let files = files_with(Config {
854            include_extensions: vec!["pdf".to_owned()],
855            exclude_extensions: vec!["pdf".to_owned()],
856            ..Config::default()
857        });
858
859        assert!(!files.extension_allowed("/home/u/report.pdf"));
860    }
861
862    #[test]
863    fn everything_is_allowed_by_default() {
864        let files = files_with(Config::default());
865        assert!(files.extension_allowed("/home/u/anything.xyz"));
866    }
867
868    #[test]
869    fn user_prune_names_extend_the_builtin_list() {
870        let config = Config {
871            ignore_names: vec!["Games".to_owned()],
872            ..Config::default()
873        };
874        let names = prune_names(&config);
875        assert!(names.contains("node_modules"), "built-ins are kept");
876        assert!(names.contains("Games"));
877    }
878
879    #[test]
880    fn recency_is_bucketed_and_decays() {
881        assert!(
882            recency_bonus(Duration::from_secs(3600))
883                > recency_bonus(Duration::from_secs(86_400 * 10))
884        );
885        assert_eq!(recency_bonus(Duration::from_secs(86_400 * 400)), 0.0);
886    }
887}