Skip to main content

rightkit_document_workspace/
explorer.rs

1//! Backend for the explorer sidebar: system locations, one-level directory listings,
2//! per-folder change watches, and OS-level reveal.
3//!
4//! SECURITY MODEL (mirrors `list_sibling_images` in `document_io.rs`): the renderer may
5//! enumerate directory *metadata* freely — names, kinds, sizes, mtimes — but file
6//! *content* only ever flows through a `PathBroker` grant. Listing a folder grants every
7//! *supported* file inside it: opening that row is exactly what the sidebar exists for,
8//! and the grant is scoped to files the user can see and click. Unsupported files come
9//! back as `kind: "other"` with a bare canonical path and NO grant, so they can be
10//! revealed or have their path copied but can never be read by `read_document`. Every
11//! entry is canonicalized and dropped if its real path escapes the listed directory, so
12//! a symlink can never smuggle a grant to a file outside the folder the user opened.
13
14use std::path::{Path, PathBuf};
15
16use serde::Serialize;
17
18use crate::document_io::natural_cmp;
19use crate::documents::DocumentBackend;
20use crate::error::WorkspaceError;
21use crate::grants::PathGrants;
22use crate::watch::WorkspaceWatcher;
23
24/// The display spelling of a path: lossy UTF-8, without the Windows verbatim (`\\?\`) prefix.
25pub fn path_to_string(path: &Path) -> String {
26    let raw = path.to_string_lossy();
27    #[cfg(windows)]
28    {
29        if let Some(stripped) = raw.strip_prefix(r"\\?\UNC\") {
30            return format!(r"\\{stripped}");
31        }
32        if let Some(stripped) = raw.strip_prefix(r"\\?\") {
33            return stripped.to_string();
34        }
35    }
36    raw.into_owned()
37}
38
39/// Max entries returned per folder; `truncated` tells the UI the listing was cut rather
40/// than that the folder simply ended.
41const LIST_DIR_CAP: usize = 5000;
42
43/// Names that are never listed (any case): Finder/Explorer droppings and the recycle
44/// bin. Dot-prefixed names are filtered separately — they're already hidden by
45/// convention — but `$RECYCLE.BIN` and `desktop.ini` don't start with a dot on Windows.
46const JUNK_NAMES: [&str; 3] = [".ds_store", "desktop.ini", "$recycle.bin"];
47
48#[derive(Debug, Serialize, Clone)]
49pub struct ExplorerLocation {
50    /// Stable, unique id ("home", "desktop", "volume:/Volumes/X", "root", ...).
51    pub id: String,
52    pub label: String,
53    /// "home" | "desktop" | "documents" | "downloads" | "icloud" | "onedrive" |
54    /// "volume" | "root".
55    pub kind: String,
56    /// Display path of the location's root directory.
57    pub dir: String,
58}
59
60#[derive(Debug, Serialize, Clone)]
61pub struct ExplorerEntry {
62    /// The name as it appears in the directory (a symlink keeps its own name even though
63    /// `path` is the resolved target).
64    pub name: String,
65    /// "dir" | a supported format id from `DocumentBackend::format_of` | "other".
66    pub kind: String,
67    /// Unix epoch millis of the target's mtime; null when the FS won't report one.
68    pub modified: Option<i64>,
69    /// Byte size for files; null for directories.
70    pub size: Option<i64>,
71    /// Dirs: canonical dir path. Supported files: broker-granted canonical path.
72    /// "other" files: bare canonical path with NO grant (see module doc).
73    pub path: String,
74}
75
76#[derive(Debug, Serialize)]
77pub struct ExplorerListing {
78    pub entries: Vec<ExplorerEntry>,
79    pub truncated: bool,
80}
81
82/// Map a filesystem error on `path` to the typed envelope: ENOENT → `FileNotFound`,
83/// EACCES → `PermissionDenied` (with the TCC-style hint the UI surfaces), else `Io`.
84/// `app_name` names the product in the permission hint. Public so `library::toggle_pin_dir`
85/// reports identical error classes.
86pub fn fs_io_error(app_name: &str, path: &str, e: std::io::Error) -> WorkspaceError {
87    match e.kind() {
88        std::io::ErrorKind::NotFound => {
89            WorkspaceError::FileNotFound(format!("folder not found: {path}"))
90        }
91        std::io::ErrorKind::PermissionDenied => {
92            WorkspaceError::PermissionDenied(permission_denied_message(app_name, path))
93        }
94        _ => WorkspaceError::Io(e.to_string()),
95    }
96}
97
98/// User-facing permission hint naming the folder. On macOS an EACCES here is usually a
99/// TCC (Files and Folders) denial, so the message points at the System Settings pane
100/// where the user grants it; other platforms get a permissions phrasing.
101fn permission_denied_message(app_name: &str, path: &str) -> String {
102    let name = Path::new(path)
103        .file_name()
104        .map(|n| n.to_string_lossy().into_owned())
105        .filter(|n| !n.is_empty())
106        .unwrap_or_else(|| path.to_string());
107    #[cfg(target_os = "macos")]
108    {
109        format!("{app_name} needs access to {name} — allow in System Settings ▸ Privacy & Security ▸ Files and Folders")
110    }
111    #[cfg(not(target_os = "macos"))]
112    {
113        format!("{app_name} needs access to {name} — check the folder's permissions")
114    }
115}
116
117/// A sidebar location the OS offers that isn't currently on disk is skipped — the list
118/// only advertises folders that actually exist (an empty %OneDrive% var, an unmounted
119/// share, a missing ~/Desktop on a server account all drop out here).
120fn push_location(
121    out: &mut Vec<ExplorerLocation>,
122    id: String,
123    label: &str,
124    kind: &str,
125    dir: PathBuf,
126) {
127    if dir.is_dir() {
128        out.push(ExplorerLocation {
129            id,
130            label: label.to_string(),
131            kind: kind.to_string(),
132            dir: path_to_string(&dir),
133        });
134    }
135}
136
137/// The home folder a listing starts from, as the host resolves it (so test and QA builds never
138/// list the real home).
139#[derive(Debug, Clone, Default)]
140pub struct HomeLocation {
141    /// The home directory, when known.
142    pub home: Option<PathBuf>,
143    /// True when `home` is an isolated stand-in; the real known folders (Desktop, Documents,
144    /// Downloads) are then never asked for, since they would point at the user's own folders.
145    pub isolated: bool,
146}
147
148/// The sidebar locations the OS offers that exist on disk.
149pub fn explorer_locations(location: &HomeLocation) -> Vec<ExplorerLocation> {
150    collect_locations(location)
151}
152
153fn collect_locations(location: &HomeLocation) -> Vec<ExplorerLocation> {
154    let mut out = Vec::new();
155    let home = location.home.clone();
156    if let Some(home) = &home {
157        push_location(&mut out, "home".into(), "Home", "home", home.clone());
158    }
159
160    #[cfg(any(target_os = "macos", target_os = "windows"))]
161    {
162        // dirs::* resolves the platform-correct (possibly localized/redirected)
163        // folder; the conventional subfolder under home is the fallback when it doesn't
164        // answer (e.g. a Windows account with no known-folder mapping).
165        // An isolated home (tests, real-app QA) never asks for the real known folders: they
166        // would point back at the user's own Desktop, Documents and Downloads.
167        let known = |real: fn() -> Option<PathBuf>| {
168            if location.isolated {
169                None
170            } else {
171                real()
172            }
173        };
174        for (id, label, resolved, fallback) in [
175            ("desktop", "Desktop", known(dirs::desktop_dir), "Desktop"),
176            (
177                "documents",
178                "Documents",
179                known(dirs::document_dir),
180                "Documents",
181            ),
182            (
183                "downloads",
184                "Downloads",
185                known(dirs::download_dir),
186                "Downloads",
187            ),
188        ] {
189            let dir = resolved.or_else(|| home.as_ref().map(|h| h.join(fallback)));
190            if let Some(dir) = dir {
191                push_location(&mut out, id.into(), label, id, dir);
192            }
193        }
194    }
195
196    #[cfg(target_os = "macos")]
197    {
198        // iCloud Drive only exists once the user signs in / enables Desktop & Documents
199        // sync — `push_location` drops it otherwise.
200        if let Some(home) = &home {
201            let icloud = home.join("Library/Mobile Documents/com~apple~CloudDocs");
202            push_location(&mut out, "icloud".into(), "iCloud Drive", "icloud", icloud);
203        }
204        // Every real volume mounted under /Volumes. The boot volume appears here as a
205        // symlink to "/" (e.g. "Macintosh HD" -> /) — skip it: Home already covers the
206        // startup disk, and a second entry pointing at "/" would duplicate the whole
207        // drive in the tree.
208        if let Ok(volumes) = std::fs::read_dir("/Volumes") {
209            for entry in volumes.flatten() {
210                let name = entry.file_name().to_string_lossy().into_owned();
211                if name.starts_with('.') {
212                    continue;
213                }
214                let Ok(canon) = std::fs::canonicalize(entry.path()) else {
215                    continue;
216                };
217                if !canon.is_dir() || canon == Path::new("/") || mac_volume_not_browsable(&canon) {
218                    continue;
219                }
220                push_location(
221                    &mut out,
222                    format!("volume:{}", path_to_string(&canon)),
223                    &name,
224                    "volume",
225                    canon,
226                );
227            }
228        }
229    }
230
231    #[cfg(target_os = "windows")]
232    {
233        if let Some(one) = std::env::var_os("OneDrive").map(PathBuf::from) {
234            push_location(&mut out, "onedrive".into(), "OneDrive", "onedrive", one);
235        }
236        // GetLogicalDrives bitmask + GetDriveTypeW avoid probing every letter with
237        // `is_dir()`, which can stall on disconnected network drives. Network drives
238        // (DRIVE_REMOTE) are intentionally not listed as locations.
239        use windows::core::PCWSTR;
240        use windows::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
241        const DRIVE_NO_ROOT_DIR: u32 = 1;
242        const DRIVE_REMOTE: u32 = 4;
243        // SAFETY: GetLogicalDrives takes no arguments and has no preconditions.
244        let mask = unsafe { GetLogicalDrives() };
245        for (bit, letter) in (b'A'..=b'Z').enumerate() {
246            if mask & (1u32 << bit) == 0 {
247                continue;
248            }
249            let spec = format!("{}:\\", letter as char);
250            let wide: Vec<u16> = spec.encode_utf16().chain(std::iter::once(0)).collect();
251            // SAFETY: `wide` is a NUL-terminated UTF-16 string that outlives the call.
252            let kind = unsafe { GetDriveTypeW(PCWSTR(wide.as_ptr())) };
253            if kind == DRIVE_NO_ROOT_DIR || kind == DRIVE_REMOTE {
254                continue;
255            }
256            let dir = PathBuf::from(&spec);
257            if dir.is_dir() {
258                push_location(&mut out, format!("volume:{spec}"), &spec, "volume", dir);
259            }
260        }
261    }
262
263    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
264    {
265        push_location(&mut out, "root".into(), "/", "root", PathBuf::from("/"));
266    }
267
268    out
269}
270
271/// Volumes macOS mounts with `nobrowse` (Recovery, Time Machine local snapshots, installer
272/// and helper disk images) are hidden from Finder's sidebar; hide them here too.
273#[cfg(target_os = "macos")]
274fn mac_volume_not_browsable(path: &Path) -> bool {
275    use std::os::unix::ffi::OsStrExt;
276    const MNT_DONTBROWSE: u32 = 0x0010_0000;
277    let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
278        return true;
279    };
280    let mut info = std::mem::MaybeUninit::<libc::statfs>::uninit();
281    // SAFETY: `c_path` is NUL-terminated and `info` is a valid out-pointer for statfs.
282    if unsafe { libc::statfs(c_path.as_ptr(), info.as_mut_ptr()) } != 0 {
283        return true;
284    }
285    // SAFETY: statfs returned 0, so it fully initialized `info`.
286    let info = unsafe { info.assume_init() };
287    info.f_flags & MNT_DONTBROWSE != 0
288}
289
290/// Everything [`scan_dir`] knows about one directory entry, pre-grant. `canon` is the
291/// resolved (symlink-free) path — the only form the broker and the renderer ever see.
292struct RawEntry {
293    name: String,
294    is_dir: bool,
295    canon: PathBuf,
296    modified: Option<i64>,
297    size: Option<i64>,
298}
299
300/// A `keep` value is one child NAME. Empty values, and values that could name a path (a
301/// separator, or `..`), are ignored, so a kept name can only select an entry the listing
302/// already has after every filter.
303fn child_name(keep: Option<&str>) -> Option<&str> {
304    keep.filter(|n| !n.is_empty() && !n.contains("..") && !n.contains(['/', '\\']))
305}
306
307/// Read ONE level of `dir` (canonicalized first): hidden names and OS junk skipped,
308/// dirs-then-files each natural-sorted, capped at `cap` entries (`truncated` reports the
309/// cut). `keep` names one child that stays listed even when the cap would cut it (the
310/// sidebar passes the next segment of the file it is revealing). Entries whose canonical
311/// path escapes the listed directory — symlinks pointing outside it — are dropped here so
312/// nothing downstream can grant them (the `list_sibling_images` containment rule).
313fn scan_dir_keeping(
314    app_name: &str,
315    dir: &str,
316    cap: usize,
317    keep: Option<&str>,
318) -> Result<(Vec<RawEntry>, bool), WorkspaceError> {
319    let canon_dir = std::fs::canonicalize(dir).map_err(|e| fs_io_error(app_name, dir, e))?;
320    if !canon_dir.is_dir() {
321        return Err(WorkspaceError::FileNotFound(format!("not a folder: {dir}")));
322    }
323    let read = std::fs::read_dir(&canon_dir).map_err(|e| fs_io_error(app_name, dir, e))?;
324    let mut dirs = Vec::new();
325    let mut files = Vec::new();
326    for entry in read.flatten() {
327        let name = entry.file_name().to_string_lossy().into_owned();
328        if name.starts_with('.') || JUNK_NAMES.contains(&name.to_ascii_lowercase().as_str()) {
329            continue;
330        }
331        // Canonical containment: read_dir + canonicalize follow symlinks, so without
332        // this check a symlink in the folder pointing elsewhere on disk would surface —
333        // and for supported types, get a broker grant — for a file outside the folder
334        // the user actually listed. Dropped entries never reach `finish_listing`, so
335        // they can never receive a grant.
336        let Ok(canon) = std::fs::canonicalize(entry.path()) else {
337            continue;
338        };
339        if !canon.starts_with(&canon_dir) {
340            continue;
341        }
342        // A link that resolves to the listed folder itself (Windows' legacy
343        // `AppData\Local\Application Data` junction, or `ln -s . loop`) would be returned
344        // with the folder's own path: an expanded folder would then contain itself, and
345        // the tree would recurse without end.
346        if canon == canon_dir {
347            continue;
348        }
349        let Ok(meta) = std::fs::metadata(&canon) else {
350            continue;
351        };
352        let is_dir = meta.is_dir();
353        let modified = meta
354            .modified()
355            .ok()
356            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
357            .map(|d| d.as_millis() as i64);
358        let raw = RawEntry {
359            name,
360            is_dir,
361            canon,
362            modified,
363            size: (!is_dir).then_some(meta.len() as i64),
364        };
365        if is_dir {
366            dirs.push(raw);
367        } else {
368            files.push(raw);
369        }
370    }
371    dirs.sort_by(|a, b| natural_cmp(&a.name, &b.name));
372    files.sort_by(|a, b| natural_cmp(&a.name, &b.name));
373    let truncated = dirs.len() + files.len() > cap;
374    let mut all = dirs;
375    all.extend(files);
376    // The kept child is appended after the cut rather than swapped in for an entry. Every
377    // entry that survives the cut sorts before it (its index is past `cap`), so the result
378    // stays in listing order; a dir can only sit past the cap when every kept entry is a dir,
379    // so the dirs-then-files grouping holds too. At most `cap + 1` entries are returned, and
380    // without a kept child the cut is unchanged.
381    let kept = child_name(keep)
382        .and_then(|name| all.iter().position(|e| e.name == name))
383        .filter(|&i| i >= cap)
384        .map(|i| all.remove(i));
385    all.truncate(cap);
386    all.extend(kept);
387    Ok((all, truncated))
388}
389
390/// Turn raw entries into the wire shape. Dirs keep their canonical path; supported
391/// files are broker-granted (a grant race — file deleted between scan and grant — drops
392/// the row); unsupported files report `kind: "other"` with a bare canonical path and
393/// are never granted, per the module's security model.
394fn finish_listing(
395    raws: Vec<RawEntry>,
396    truncated: bool,
397    grants: &dyn PathGrants,
398    docs: &dyn DocumentBackend,
399) -> ExplorerListing {
400    let mut entries = Vec::with_capacity(raws.len());
401    for raw in raws {
402        let kind = if raw.is_dir {
403            "dir"
404        } else {
405            match docs.format_of(&path_to_string(&raw.canon)) {
406                "unknown" | "other" => "other",
407                supported => supported,
408            }
409        };
410        let path = if raw.is_dir || kind == "other" {
411            path_to_string(&raw.canon)
412        } else {
413            match grants.grant_existing_file_path(&raw.canon) {
414                Ok(granted) => granted,
415                Err(_) => continue,
416            }
417        };
418        entries.push(ExplorerEntry {
419            name: raw.name,
420            kind: kind.to_string(),
421            modified: raw.modified,
422            size: raw.size,
423            path,
424        });
425    }
426    ExplorerListing { entries, truncated }
427}
428
429/// List one level of a directory for the explorer tree. The directory itself needs no grant (it
430/// is not file content) while the supported files inside are granted so the renderer can open
431/// them (see the module doc for the full model). `keep` is the NAME of one child to list even
432/// past the cap (see `scan_dir_keeping`).
433///
434/// `on_timing` receives the JSON detail record for the listing (entry count, truncation and
435/// duration) so the host can log it.
436pub fn explorer_list_dir(
437    app_name: &str,
438    grants: &dyn PathGrants,
439    docs: &dyn DocumentBackend,
440    dir: &str,
441    keep: Option<&str>,
442    on_timing: &dyn Fn(&str),
443) -> Result<ExplorerListing, WorkspaceError> {
444    let started = std::time::Instant::now();
445    let (raws, truncated) = scan_dir_keeping(app_name, dir, LIST_DIR_CAP, child_name(keep))?;
446    let listing = finish_listing(raws, truncated, grants, docs);
447    on_timing(
448        &serde_json::json!({
449            "entries": listing.entries.len(),
450            "truncated": listing.truncated,
451            "durationMs": started.elapsed().as_millis() as u64,
452        })
453        .to_string(),
454    );
455    Ok(listing)
456}
457
458/// Watch a folder for changes; the host's watcher emits the change event carrying the string
459/// passed here after its debounce. Idempotent on the canonical dir; the host caps concurrent
460/// watches.
461pub fn explorer_watch_dir(
462    app_name: &str,
463    watcher: &dyn WorkspaceWatcher,
464    dir: &str,
465) -> Result<(), WorkspaceError> {
466    let canon = std::fs::canonicalize(dir).map_err(|e| fs_io_error(app_name, dir, e))?;
467    if !canon.is_dir() {
468        return Err(WorkspaceError::FileNotFound(format!("not a folder: {dir}")));
469    }
470    watcher
471        .watch_dir(&canon, dir)
472        .map_err(WorkspaceError::Watch)
473}
474
475/// Stop watching a folder. Idempotent: unwatching an unwatched (or deleted) folder is a no-op, so
476/// the frontend can fire this on collapse without tracking state.
477pub fn explorer_unwatch_dir(watcher: &dyn WorkspaceWatcher, dir: &str) {
478    // The watch is keyed by the canonical dir string, but the folder may have been deleted since
479    // it was armed: pass the raw string too so the entry is found either way.
480    let mut keys = vec![dir.to_string()];
481    if let Ok(canon) = std::fs::canonicalize(dir) {
482        keys.insert(0, path_to_string(&canon));
483    }
484    watcher.unwatch_dirs(&keys);
485}
486
487/// Reveal a folder or an unsupported file in the OS file manager. No grant is required: this only
488/// *displays* the path in Finder/Explorer, it reads no file content. Canonicalize still runs so
489/// the revealed path is the real, unambiguous one.
490pub fn explorer_reveal(app_name: &str, path: &str) -> Result<(), WorkspaceError> {
491    let canon = std::fs::canonicalize(path).map_err(|e| fs_io_error(app_name, path, e))?;
492    // Selects the item in its parent window (a folder too); the scope is the one path.
493    let scope = rightkit_child_process::reveal::PathScope::new([&canon])
494        .map_err(|e| WorkspaceError::Other(e.to_string()))?;
495    rightkit_child_process::reveal::reveal(&canon, &scope)
496        .map_err(|e| WorkspaceError::Other(e.to_string()))
497}