use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::document_io::natural_cmp;
use crate::documents::DocumentBackend;
use crate::error::WorkspaceError;
use crate::grants::PathGrants;
use crate::watch::WorkspaceWatcher;
pub fn path_to_string(path: &Path) -> String {
let raw = path.to_string_lossy();
#[cfg(windows)]
{
if let Some(stripped) = raw.strip_prefix(r"\\?\UNC\") {
return format!(r"\\{stripped}");
}
if let Some(stripped) = raw.strip_prefix(r"\\?\") {
return stripped.to_string();
}
}
raw.into_owned()
}
const LIST_DIR_CAP: usize = 5000;
const JUNK_NAMES: [&str; 3] = [".ds_store", "desktop.ini", "$recycle.bin"];
#[derive(Debug, Serialize, Clone)]
pub struct ExplorerLocation {
pub id: String,
pub label: String,
pub kind: String,
pub dir: String,
}
#[derive(Debug, Serialize, Clone)]
pub struct ExplorerEntry {
pub name: String,
pub kind: String,
pub modified: Option<i64>,
pub size: Option<i64>,
pub path: String,
}
#[derive(Debug, Serialize)]
pub struct ExplorerListing {
pub entries: Vec<ExplorerEntry>,
pub truncated: bool,
}
pub fn fs_io_error(app_name: &str, path: &str, e: std::io::Error) -> WorkspaceError {
match e.kind() {
std::io::ErrorKind::NotFound => {
WorkspaceError::FileNotFound(format!("folder not found: {path}"))
}
std::io::ErrorKind::PermissionDenied => {
WorkspaceError::PermissionDenied(permission_denied_message(app_name, path))
}
_ => WorkspaceError::Io(e.to_string()),
}
}
fn permission_denied_message(app_name: &str, path: &str) -> String {
let name = Path::new(path)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| path.to_string());
#[cfg(target_os = "macos")]
{
format!("{app_name} needs access to {name} — allow in System Settings ▸ Privacy & Security ▸ Files and Folders")
}
#[cfg(not(target_os = "macos"))]
{
format!("{app_name} needs access to {name} — check the folder's permissions")
}
}
fn push_location(
out: &mut Vec<ExplorerLocation>,
id: String,
label: &str,
kind: &str,
dir: PathBuf,
) {
if dir.is_dir() {
out.push(ExplorerLocation {
id,
label: label.to_string(),
kind: kind.to_string(),
dir: path_to_string(&dir),
});
}
}
#[derive(Debug, Clone, Default)]
pub struct HomeLocation {
pub home: Option<PathBuf>,
pub isolated: bool,
}
pub fn explorer_locations(location: &HomeLocation) -> Vec<ExplorerLocation> {
collect_locations(location)
}
fn collect_locations(location: &HomeLocation) -> Vec<ExplorerLocation> {
let mut out = Vec::new();
let home = location.home.clone();
if let Some(home) = &home {
push_location(&mut out, "home".into(), "Home", "home", home.clone());
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
{
let known = |real: fn() -> Option<PathBuf>| {
if location.isolated {
None
} else {
real()
}
};
for (id, label, resolved, fallback) in [
("desktop", "Desktop", known(dirs::desktop_dir), "Desktop"),
(
"documents",
"Documents",
known(dirs::document_dir),
"Documents",
),
(
"downloads",
"Downloads",
known(dirs::download_dir),
"Downloads",
),
] {
let dir = resolved.or_else(|| home.as_ref().map(|h| h.join(fallback)));
if let Some(dir) = dir {
push_location(&mut out, id.into(), label, id, dir);
}
}
}
#[cfg(target_os = "macos")]
{
if let Some(home) = &home {
let icloud = home.join("Library/Mobile Documents/com~apple~CloudDocs");
push_location(&mut out, "icloud".into(), "iCloud Drive", "icloud", icloud);
}
if let Ok(volumes) = std::fs::read_dir("/Volumes") {
for entry in volumes.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let Ok(canon) = std::fs::canonicalize(entry.path()) else {
continue;
};
if !canon.is_dir() || canon == Path::new("/") || mac_volume_not_browsable(&canon) {
continue;
}
push_location(
&mut out,
format!("volume:{}", path_to_string(&canon)),
&name,
"volume",
canon,
);
}
}
}
#[cfg(target_os = "windows")]
{
if let Some(one) = std::env::var_os("OneDrive").map(PathBuf::from) {
push_location(&mut out, "onedrive".into(), "OneDrive", "onedrive", one);
}
use windows::core::PCWSTR;
use windows::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
const DRIVE_NO_ROOT_DIR: u32 = 1;
const DRIVE_REMOTE: u32 = 4;
let mask = unsafe { GetLogicalDrives() };
for (bit, letter) in (b'A'..=b'Z').enumerate() {
if mask & (1u32 << bit) == 0 {
continue;
}
let spec = format!("{}:\\", letter as char);
let wide: Vec<u16> = spec.encode_utf16().chain(std::iter::once(0)).collect();
let kind = unsafe { GetDriveTypeW(PCWSTR(wide.as_ptr())) };
if kind == DRIVE_NO_ROOT_DIR || kind == DRIVE_REMOTE {
continue;
}
let dir = PathBuf::from(&spec);
if dir.is_dir() {
push_location(&mut out, format!("volume:{spec}"), &spec, "volume", dir);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
push_location(&mut out, "root".into(), "/", "root", PathBuf::from("/"));
}
out
}
#[cfg(target_os = "macos")]
fn mac_volume_not_browsable(path: &Path) -> bool {
use std::os::unix::ffi::OsStrExt;
const MNT_DONTBROWSE: u32 = 0x0010_0000;
let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
return true;
};
let mut info = std::mem::MaybeUninit::<libc::statfs>::uninit();
if unsafe { libc::statfs(c_path.as_ptr(), info.as_mut_ptr()) } != 0 {
return true;
}
let info = unsafe { info.assume_init() };
info.f_flags & MNT_DONTBROWSE != 0
}
struct RawEntry {
name: String,
is_dir: bool,
canon: PathBuf,
modified: Option<i64>,
size: Option<i64>,
}
fn child_name(keep: Option<&str>) -> Option<&str> {
keep.filter(|n| !n.is_empty() && !n.contains("..") && !n.contains(['/', '\\']))
}
#[cfg(all(test, unix))]
fn scan_dir(dir: &str, cap: usize) -> Result<(Vec<RawEntry>, bool), WorkspaceError> {
scan_dir_keeping("Test", dir, cap, None)
}
fn scan_dir_keeping(
app_name: &str,
dir: &str,
cap: usize,
keep: Option<&str>,
) -> Result<(Vec<RawEntry>, bool), WorkspaceError> {
let canon_dir = std::fs::canonicalize(dir).map_err(|e| fs_io_error(app_name, dir, e))?;
if !canon_dir.is_dir() {
return Err(WorkspaceError::FileNotFound(format!("not a folder: {dir}")));
}
let read = std::fs::read_dir(&canon_dir).map_err(|e| fs_io_error(app_name, dir, e))?;
let mut dirs = Vec::new();
let mut files = Vec::new();
for entry in read.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') || JUNK_NAMES.contains(&name.to_ascii_lowercase().as_str()) {
continue;
}
let Ok(canon) = std::fs::canonicalize(entry.path()) else {
continue;
};
if !canon.starts_with(&canon_dir) {
continue;
}
if canon == canon_dir {
continue;
}
let Ok(meta) = std::fs::metadata(&canon) else {
continue;
};
let is_dir = meta.is_dir();
let modified = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64);
let raw = RawEntry {
name,
is_dir,
canon,
modified,
size: (!is_dir).then_some(meta.len() as i64),
};
if is_dir {
dirs.push(raw);
} else {
files.push(raw);
}
}
dirs.sort_by(|a, b| natural_cmp(&a.name, &b.name));
files.sort_by(|a, b| natural_cmp(&a.name, &b.name));
let truncated = dirs.len() + files.len() > cap;
let mut all = dirs;
all.extend(files);
let kept = child_name(keep)
.and_then(|name| all.iter().position(|e| e.name == name))
.filter(|&i| i >= cap)
.map(|i| all.remove(i));
all.truncate(cap);
all.extend(kept);
Ok((all, truncated))
}
fn finish_listing(
raws: Vec<RawEntry>,
truncated: bool,
grants: &dyn PathGrants,
docs: &dyn DocumentBackend,
) -> ExplorerListing {
let mut entries = Vec::with_capacity(raws.len());
for raw in raws {
let kind = if raw.is_dir {
"dir"
} else {
match docs.format_of(&path_to_string(&raw.canon)) {
"unknown" | "other" => "other",
supported => supported,
}
};
let path = if raw.is_dir || kind == "other" {
path_to_string(&raw.canon)
} else {
match grants.grant_existing_file_path(&raw.canon) {
Ok(granted) => granted,
Err(_) => continue,
}
};
entries.push(ExplorerEntry {
name: raw.name,
kind: kind.to_string(),
modified: raw.modified,
size: raw.size,
path,
});
}
ExplorerListing { entries, truncated }
}
pub fn explorer_list_dir(
app_name: &str,
grants: &dyn PathGrants,
docs: &dyn DocumentBackend,
dir: &str,
keep: Option<&str>,
on_timing: &dyn Fn(&str),
) -> Result<ExplorerListing, WorkspaceError> {
let started = std::time::Instant::now();
let (raws, truncated) = scan_dir_keeping(app_name, dir, LIST_DIR_CAP, child_name(keep))?;
let listing = finish_listing(raws, truncated, grants, docs);
on_timing(
&serde_json::json!({
"entries": listing.entries.len(),
"truncated": listing.truncated,
"durationMs": started.elapsed().as_millis() as u64,
})
.to_string(),
);
Ok(listing)
}
pub fn explorer_watch_dir(
app_name: &str,
watcher: &dyn WorkspaceWatcher,
dir: &str,
) -> Result<(), WorkspaceError> {
let canon = std::fs::canonicalize(dir).map_err(|e| fs_io_error(app_name, dir, e))?;
if !canon.is_dir() {
return Err(WorkspaceError::FileNotFound(format!("not a folder: {dir}")));
}
watcher
.watch_dir(&canon, dir)
.map_err(WorkspaceError::Watch)
}
pub fn explorer_unwatch_dir(watcher: &dyn WorkspaceWatcher, dir: &str) {
let mut keys = vec![dir.to_string()];
if let Ok(canon) = std::fs::canonicalize(dir) {
keys.insert(0, path_to_string(&canon));
}
watcher.unwatch_dirs(&keys);
}
pub fn explorer_reveal(app_name: &str, path: &str) -> Result<(), WorkspaceError> {
let canon = std::fs::canonicalize(path).map_err(|e| fs_io_error(app_name, path, e))?;
let scope = rightkit_child_process::reveal::PathScope::new([&canon])
.map_err(|e| WorkspaceError::Other(e.to_string()))?;
rightkit_child_process::reveal::reveal(&canon, &scope)
.map_err(|e| WorkspaceError::Other(e.to_string()))
}
#[cfg(all(test, unix))]
#[path = "explorer_tests.rs"]
mod explorer_tests;