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/// Test entry point with no named child; the command always goes through [`scan_dir_keeping`].
308#[cfg(all(test, unix))]
309fn scan_dir(dir: &str, cap: usize) -> Result<(Vec<RawEntry>, bool), WorkspaceError> {
310 scan_dir_keeping("Test", dir, cap, None)
311}
312
313/// Read ONE level of `dir` (canonicalized first): hidden names and OS junk skipped,
314/// dirs-then-files each natural-sorted, capped at `cap` entries (`truncated` reports the
315/// cut). `keep` names one child that stays listed even when the cap would cut it (the
316/// sidebar passes the next segment of the file it is revealing). Entries whose canonical
317/// path escapes the listed directory — symlinks pointing outside it — are dropped here so
318/// nothing downstream can grant them (the `list_sibling_images` containment rule).
319fn scan_dir_keeping(
320 app_name: &str,
321 dir: &str,
322 cap: usize,
323 keep: Option<&str>,
324) -> Result<(Vec<RawEntry>, bool), WorkspaceError> {
325 let canon_dir = std::fs::canonicalize(dir).map_err(|e| fs_io_error(app_name, dir, e))?;
326 if !canon_dir.is_dir() {
327 return Err(WorkspaceError::FileNotFound(format!("not a folder: {dir}")));
328 }
329 let read = std::fs::read_dir(&canon_dir).map_err(|e| fs_io_error(app_name, dir, e))?;
330 let mut dirs = Vec::new();
331 let mut files = Vec::new();
332 for entry in read.flatten() {
333 let name = entry.file_name().to_string_lossy().into_owned();
334 if name.starts_with('.') || JUNK_NAMES.contains(&name.to_ascii_lowercase().as_str()) {
335 continue;
336 }
337 // Canonical containment: read_dir + canonicalize follow symlinks, so without
338 // this check a symlink in the folder pointing elsewhere on disk would surface —
339 // and for supported types, get a broker grant — for a file outside the folder
340 // the user actually listed. Dropped entries never reach `finish_listing`, so
341 // they can never receive a grant.
342 let Ok(canon) = std::fs::canonicalize(entry.path()) else {
343 continue;
344 };
345 if !canon.starts_with(&canon_dir) {
346 continue;
347 }
348 // A link that resolves to the listed folder itself (Windows' legacy
349 // `AppData\Local\Application Data` junction, or `ln -s . loop`) would be returned
350 // with the folder's own path: an expanded folder would then contain itself, and
351 // the tree would recurse without end.
352 if canon == canon_dir {
353 continue;
354 }
355 let Ok(meta) = std::fs::metadata(&canon) else {
356 continue;
357 };
358 let is_dir = meta.is_dir();
359 let modified = meta
360 .modified()
361 .ok()
362 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
363 .map(|d| d.as_millis() as i64);
364 let raw = RawEntry {
365 name,
366 is_dir,
367 canon,
368 modified,
369 size: (!is_dir).then_some(meta.len() as i64),
370 };
371 if is_dir {
372 dirs.push(raw);
373 } else {
374 files.push(raw);
375 }
376 }
377 dirs.sort_by(|a, b| natural_cmp(&a.name, &b.name));
378 files.sort_by(|a, b| natural_cmp(&a.name, &b.name));
379 let truncated = dirs.len() + files.len() > cap;
380 let mut all = dirs;
381 all.extend(files);
382 // The kept child is appended after the cut rather than swapped in for an entry. Every
383 // entry that survives the cut sorts before it (its index is past `cap`), so the result
384 // stays in listing order; a dir can only sit past the cap when every kept entry is a dir,
385 // so the dirs-then-files grouping holds too. At most `cap + 1` entries are returned, and
386 // without a kept child the cut is unchanged.
387 let kept = child_name(keep)
388 .and_then(|name| all.iter().position(|e| e.name == name))
389 .filter(|&i| i >= cap)
390 .map(|i| all.remove(i));
391 all.truncate(cap);
392 all.extend(kept);
393 Ok((all, truncated))
394}
395
396/// Turn raw entries into the wire shape. Dirs keep their canonical path; supported
397/// files are broker-granted (a grant race — file deleted between scan and grant — drops
398/// the row); unsupported files report `kind: "other"` with a bare canonical path and
399/// are never granted, per the module's security model.
400fn finish_listing(
401 raws: Vec<RawEntry>,
402 truncated: bool,
403 grants: &dyn PathGrants,
404 docs: &dyn DocumentBackend,
405) -> ExplorerListing {
406 let mut entries = Vec::with_capacity(raws.len());
407 for raw in raws {
408 let kind = if raw.is_dir {
409 "dir"
410 } else {
411 match docs.format_of(&path_to_string(&raw.canon)) {
412 "unknown" | "other" => "other",
413 supported => supported,
414 }
415 };
416 let path = if raw.is_dir || kind == "other" {
417 path_to_string(&raw.canon)
418 } else {
419 match grants.grant_existing_file_path(&raw.canon) {
420 Ok(granted) => granted,
421 Err(_) => continue,
422 }
423 };
424 entries.push(ExplorerEntry {
425 name: raw.name,
426 kind: kind.to_string(),
427 modified: raw.modified,
428 size: raw.size,
429 path,
430 });
431 }
432 ExplorerListing { entries, truncated }
433}
434
435/// List one level of a directory for the explorer tree. The directory itself needs no grant (it
436/// is not file content) while the supported files inside are granted so the renderer can open
437/// them (see the module doc for the full model). `keep` is the NAME of one child to list even
438/// past the cap (see `scan_dir_keeping`).
439///
440/// `on_timing` receives the JSON detail record for the listing (entry count, truncation and
441/// duration) so the host can log it.
442pub fn explorer_list_dir(
443 app_name: &str,
444 grants: &dyn PathGrants,
445 docs: &dyn DocumentBackend,
446 dir: &str,
447 keep: Option<&str>,
448 on_timing: &dyn Fn(&str),
449) -> Result<ExplorerListing, WorkspaceError> {
450 let started = std::time::Instant::now();
451 let (raws, truncated) = scan_dir_keeping(app_name, dir, LIST_DIR_CAP, child_name(keep))?;
452 let listing = finish_listing(raws, truncated, grants, docs);
453 on_timing(
454 &serde_json::json!({
455 "entries": listing.entries.len(),
456 "truncated": listing.truncated,
457 "durationMs": started.elapsed().as_millis() as u64,
458 })
459 .to_string(),
460 );
461 Ok(listing)
462}
463
464/// Watch a folder for changes; the host's watcher emits the change event carrying the string
465/// passed here after its debounce. Idempotent on the canonical dir; the host caps concurrent
466/// watches.
467pub fn explorer_watch_dir(
468 app_name: &str,
469 watcher: &dyn WorkspaceWatcher,
470 dir: &str,
471) -> Result<(), WorkspaceError> {
472 let canon = std::fs::canonicalize(dir).map_err(|e| fs_io_error(app_name, dir, e))?;
473 if !canon.is_dir() {
474 return Err(WorkspaceError::FileNotFound(format!("not a folder: {dir}")));
475 }
476 watcher
477 .watch_dir(&canon, dir)
478 .map_err(WorkspaceError::Watch)
479}
480
481/// Stop watching a folder. Idempotent: unwatching an unwatched (or deleted) folder is a no-op, so
482/// the frontend can fire this on collapse without tracking state.
483pub fn explorer_unwatch_dir(watcher: &dyn WorkspaceWatcher, dir: &str) {
484 // The watch is keyed by the canonical dir string, but the folder may have been deleted since
485 // it was armed: pass the raw string too so the entry is found either way.
486 let mut keys = vec![dir.to_string()];
487 if let Ok(canon) = std::fs::canonicalize(dir) {
488 keys.insert(0, path_to_string(&canon));
489 }
490 watcher.unwatch_dirs(&keys);
491}
492
493/// Reveal a folder or an unsupported file in the OS file manager. No grant is required: this only
494/// *displays* the path in Finder/Explorer, it reads no file content. Canonicalize still runs so
495/// the revealed path is the real, unambiguous one.
496pub fn explorer_reveal(app_name: &str, path: &str) -> Result<(), WorkspaceError> {
497 let canon = std::fs::canonicalize(path).map_err(|e| fs_io_error(app_name, path, e))?;
498 // Selects the item in its parent window (a folder too); the scope is the one path.
499 let scope = rightkit_child_process::reveal::PathScope::new([&canon])
500 .map_err(|e| WorkspaceError::Other(e.to_string()))?;
501 rightkit_child_process::reveal::reveal(&canon, &scope)
502 .map_err(|e| WorkspaceError::Other(e.to_string()))
503}
504
505// Its only fixture is the Unix symlink-escape case.
506#[cfg(all(test, unix))]
507#[path = "explorer_tests.rs"]
508mod explorer_tests;