A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
//! The Rust side of rustyfiles for macOS. The Swift app (`macos/`) calls into it through
//! UniFFI; the bindings are generated by `macos/build.sh`.
//!
//! A folder listing stays in Rust: the table asks for one row at a time ([`Folder::item`]), so
//! a 100,000-item folder never crosses the FFI as one big array, and re-sorting only shuffles
//! an index vector. Formatting (sizes, dates, kinds, icons) is left to the Swift side, where
//! the system formatters make it look the way Finder does.
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use rayon::prelude::*;
use rf_core::entry::{Entry, EntryKind, attrs};
use rf_core::sort::{SortDir, SortKey, SortSpec};
uniffi::setup_scaffolding!();
mod organize;
mod archive;
mod ferry;
mod search;
mod rename;
mod diskusage;
mod updates;
mod namequery;
pub use archive::{Archive, ArchiveError, ArchiveFormat, can_make_rar, compress, is_archive, smart_extract_target};
pub use ferry::{
Ferry, FerryConfig, FerryError, FerryEstimate, FerryLink, FerryListener, FerryOffer, FerryPeer, FerryResult, FerrySpeed, FerryStatus,
FerryVisibility,
};
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum FsError {
/// The folder is gone, or the path names something else.
#[error("not found: {path}")]
NotFound { path: String },
/// No permission (on macOS also: the app was not given access to this place in Privacy & Security).
#[error("permission denied: {path}")]
PermissionDenied { path: String },
#[error("{path}: {message}")]
Other { path: String, message: String },
}
impl FsError {
fn from_io(path: &Path, e: std::io::Error) -> Self {
let path = path.display().to_string();
match e.kind() {
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory => FsError::NotFound { path },
std::io::ErrorKind::PermissionDenied => FsError::PermissionDenied { path },
_ => FsError::Other { path, message: e.to_string() },
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum SortColumn {
Name,
Modified,
Created,
Size,
Kind,
}
impl From<SortColumn> for SortKey {
fn from(c: SortColumn) -> Self {
match c {
SortColumn::Name => SortKey::Name,
SortColumn::Modified => SortKey::Modified,
SortColumn::Created => SortKey::Created,
SortColumn::Size => SortKey::Size,
SortColumn::Kind => SortKey::Type,
}
}
}
/// One row of the table.
#[derive(Debug, Clone, uniffi::Record)]
pub struct FileItem {
pub name: String,
/// Lower-case extension without the dot ("" for none and for folders).
pub ext: String,
pub is_dir: bool,
/// Bytes; 0 for folders.
pub size: u64,
/// Unix time in milliseconds, 0 = unknown.
pub modified_ms: i64,
pub created_ms: i64,
pub hidden: bool,
/// A symbolic link (shown with the alias arrow).
pub link: bool,
}
impl From<&Entry> for FileItem {
fn from(e: &Entry) -> Self {
FileItem {
name: e.name.to_string(),
ext: e.ext.to_string(),
is_dir: e.is_dir(),
size: e.size,
modified_ms: e.modified_ms,
created_ms: e.created_ms,
hidden: e.is_hidden(),
link: e.link,
}
}
}
/// A listed folder. Made on a background thread ([`Folder::open`] reads the disk); the
/// accessors only read memory and are cheap enough for the main thread.
#[derive(uniffi::Object)]
pub struct Folder {
path: PathBuf,
entries: Vec<Entry>,
/// Rows in display order: indices into `entries`, hidden items left out unless asked for.
order: RwLock<Vec<u32>>,
/// For a gathered listing (tag results): the folder each entry is in; empty otherwise.
homes: Vec<PathBuf>,
}
impl Folder {
/// A listing made from entries that are not on the disk (a folder inside an archive).
pub(crate) fn from_entries(path: PathBuf, entries: Vec<Entry>) -> Folder {
Folder { path, entries, order: RwLock::new(Vec::new()), homes: Vec::new() }
}
}
#[uniffi::export]
impl Folder {
/// Lists `path`. Blocks on the disk: call it off the main thread.
#[uniffi::constructor]
pub fn open(
path: String, column: SortColumn, ascending: bool, folders_first: bool, show_hidden: bool,
) -> Result<Arc<Self>, FsError> {
let path = PathBuf::from(path);
let entries = list(&path)?;
let folder = Folder { path, entries, order: RwLock::new(Vec::new()), homes: Vec::new() };
folder.arrange(column, ascending, folders_first, show_hidden, String::new(), None, true);
Ok(Arc::new(folder))
}
/// A listing of items from anywhere (the files with a tag, search results): each keeps
/// its own folder, `label` stands for the whole. Items that are gone are left out.
#[uniffi::constructor]
pub fn gathered(
label: String, paths: Vec<String>, column: SortColumn, ascending: bool, folders_first: bool, show_hidden: bool,
) -> Arc<Self> {
let found: Vec<(PathBuf, Entry)> = paths
.par_iter()
.filter_map(|p| {
let p = PathBuf::from(p);
let dir = p.parent()?.to_path_buf();
let e = entry(&dir, p.file_name()?)?;
Some((dir, e))
})
.collect();
let (homes, entries): (Vec<PathBuf>, Vec<Entry>) = found.into_iter().unzip();
let folder = Folder { path: PathBuf::from(label), entries, order: RwLock::new(Vec::new()), homes };
folder.arrange(column, ascending, folders_first, show_hidden, String::new(), None, true);
Arc::new(folder)
}
pub fn path(&self) -> String {
self.path.display().to_string()
}
/// Rows shown (after the hidden filter).
pub fn count(&self) -> u32 {
self.order.read().unwrap().len() as u32
}
/// Every item in the folder, shown or not.
pub fn total(&self) -> u32 {
self.entries.len() as u32
}
pub fn item(&self, row: u32) -> Option<FileItem> {
let i = *self.order.read().unwrap().get(row as usize)?;
Some(FileItem::from(&self.entries[i as usize]))
}
pub fn child_path(&self, row: u32) -> Option<String> {
let i = *self.order.read().unwrap().get(row as usize)?;
let dir = self.homes.get(i as usize).unwrap_or(&self.path);
Some(dir.join(&*self.entries[i as usize].name).display().to_string())
}
/// Takes these rows out of the ones shown (the items of folded groups, all but each group's
/// first, which carries the group's header). The next `arrange` brings them back.
pub fn fold(&self, rows: Vec<u32>) {
if rows.is_empty() {
return;
}
let drop: std::collections::HashSet<u32> = rows.into_iter().collect();
let mut order = self.order.write().unwrap();
let kept: Vec<u32> = order.iter().enumerate().filter(|(r, _)| !drop.contains(&(*r as u32))).map(|(_, &i)| i).collect();
*order = kept;
}
/// The row an item with this name has now (to keep the selection across a re-sort).
pub fn row_of(&self, name: String) -> Option<u32> {
self.order.read().unwrap().iter().position(|&i| *self.entries[i as usize].name == *name).map(|r| r as u32)
}
/// Re-sorts and re-filters in memory; the disk is not read again. `filter` keeps the items
/// whose name contains it, ignoring case (Turkish-aware: "I" matches "ı"); "" keeps all.
/// `then_column` (a grouped list): the items `column` cannot tell apart (one group's) are
/// sorted by it, `then_ascending` giving its direction.
pub fn arrange(
&self, column: SortColumn, ascending: bool, folders_first: bool, show_hidden: bool, filter: String,
then_column: Option<SortColumn>, then_ascending: bool,
) {
let spec = SortSpec {
key: column.into(),
dir: if ascending { SortDir::Asc } else { SortDir::Desc },
dirs_first: folders_first,
files_first: false,
};
let then = then_column.map(|c| SortSpec {
key: c.into(),
dir: if then_ascending { SortDir::Asc } else { SortDir::Desc },
dirs_first: false,
files_first: false,
});
// a part of the name, a * / ? pattern, ext:pdf or kind:video (see namequery)
let query = crate::namequery::NameQuery::parse(&filter);
let mut idx: Vec<u32> = (0..self.entries.len() as u32)
.into_par_iter()
.filter(|&i| {
let e = &self.entries[i as usize];
(show_hidden || !e.is_hidden())
&& (show_system_files() || !is_system_file(&e.name))
&& (query.is_empty() || query.matches(e.shown()))
})
.collect();
idx.par_sort_unstable_by(|&a, &b| {
let (ea, eb) = (&self.entries[a as usize], &self.entries[b as usize]);
match &then {
Some(t) => spec.compare_key(ea, eb).then_with(|| t.compare(ea, eb)),
None => spec.compare(ea, eb),
}
});
*self.order.write().unwrap() = idx;
}
}
/// Which words the number and date formats use: English ("bytes", "2 h ago", decimal point)
/// or Turkish ("bayt", "2 saat önce", decimal comma). Same switch as on Windows.
#[uniffi::export]
pub fn set_english(on: bool) {
rf_core::format::set_english(on);
organize::set_english(on);
}
/// The interface language's own words for times and sizes, as the Windows app hands them over
/// with its language: the relative times' templates ("Przed chwilą", "{n} min temu", "{n} godz.
/// temu", "{n} dni temu") and the language's code ("pl", "ru") for its size names ("1,50 MB",
/// "1,50 МБ"). Once, at start; a second call changes nothing.
#[uniffi::export]
pub fn set_format_words(language: String, now: String, minute: String, hour: String, day: String) {
use rf_core::format::Relative;
static WORDS: std::sync::OnceLock<[String; 4]> = std::sync::OnceLock::new();
if WORDS.set([now, minute, hour, day]).is_err() {
return;
}
rf_core::format::set_relative_words(|kind| {
let w = WORDS.get().expect("set above");
match kind {
Relative::Now => &w[0],
Relative::Minute => &w[1],
Relative::Hour => &w[2],
Relative::Day => &w[3],
}
});
rf_core::format::set_units(rf_core::format::units_for(&language));
}
/// Sizes in powers of 1000 ("1.02 MB" for 1,020,000 bytes) instead of 1024 (Settings › Files and
/// folders › Size format).
#[uniffi::export]
pub fn set_decimal_sizes(on: bool) {
rf_core::format::set_decimal_sizes(on);
}
/// A size the way rustyfiles writes it on Windows: "512 bytes", "80.1 KB", "2.86 MB".
#[uniffi::export]
pub fn format_size(bytes: u64) -> String {
rf_core::format::size(bytes)
}
/// A file time the way rustyfiles writes it on Windows: "just now", "5 min ago", "2 h ago",
/// "3 d ago", older ones as a local date. "" for an unknown time.
#[uniffi::export]
pub fn format_date(ms: i64) -> String {
rf_core::format::datetime(ms)
}
/// Total size in bytes of the files under `path` ("Calculate size"). Links are not followed
/// and unreadable folders count as empty. Blocks on the disk: call it off the main thread.
/// How big a folder is: its files' sizes, or what they take on the disk (`on_disk`: allocated
/// blocks). The walk stays on the folder's own disk and does not follow links, so a folder
/// that holds other volumes (/Volumes, a Time Machine disk) or a network share is not walked
/// through them (issue 324: the root of Macintosh HD took every core and tens of GB), nor into
/// folders still in the cloud. Two sizes at a time, on a pool of two threads, each walk in
/// a fixed amount of memory. Blocks: off the main thread.
#[uniffi::export]
pub fn folder_size_with(path: String, on_disk: bool) -> u64 {
use std::os::unix::fs::MetadataExt;
use std::sync::{Mutex, OnceLock};
// two sizes at a time, whoever asks: a size never takes every core
static SLOTS: OnceLock<(Mutex<usize>, std::sync::Condvar)> = OnceLock::new();
let (lock, cv) = SLOTS.get_or_init(|| (Mutex::new(0), std::sync::Condvar::new()));
{
let mut busy = cv.wait_while(lock.lock().unwrap_or_else(|e| e.into_inner()), |n| *n >= 2).unwrap_or_else(|e| e.into_inner());
*busy += 1;
}
struct Release<'a>(&'a (Mutex<usize>, std::sync::Condvar));
impl Drop for Release<'_> {
fn drop(&mut self) {
*self.0 .0.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
self.0 .1.notify_one();
}
}
let _slot = Release(SLOTS.get().expect("slots"));
let root = Path::new(&path);
let Ok(m) = fs::metadata(root) else { return 0 };
let dev = m.dev();
static POOL: OnceLock<rayon::ThreadPool> = OnceLock::new();
let pool = POOL.get_or_init(|| rayon::ThreadPoolBuilder::new().num_threads(2).thread_name(|i| format!("rf-size-{i}")).build().expect("size pool"));
// the folder's own files here; its folders on the pool, each walked by size_walk
let mut total = 0u64;
let mut dirs = Vec::new();
for entry in fs::read_dir(root).into_iter().flatten().flatten() {
match size_entry(&entry, dev, on_disk) {
SizeEntry::File(n) => total += n,
SizeEntry::Dir(p) => dirs.push(p),
SizeEntry::Skip => {}
}
}
total + pool.install(|| dirs.par_iter().map(|d| size_walk(d, dev, on_disk)).sum::<u64>())
}
enum SizeEntry {
File(u64),
Dir(std::path::PathBuf),
Skip,
}
/// One entry of a size walk: a file's size, a folder to go into, or nothing (a link, another
/// disk, a folder whose listing is still in the cloud).
fn size_entry(entry: &fs::DirEntry, dev: u64, on_disk: bool) -> SizeEntry {
use std::os::macos::fs::MetadataExt as _;
use std::os::unix::fs::MetadataExt;
// iCloud Drive, a File Provider (Dropbox, Mountain Duck…): reading such a folder makes
// macOS fetch its listing, so it counts as empty, as Finder leaves it
const SF_DATALESS: u32 = 0x4000_0000;
let Ok(ft) = entry.file_type() else { return SizeEntry::Skip };
if ft.is_symlink() {
return SizeEntry::Skip;
}
let Ok(m) = entry.metadata() else { return SizeEntry::Skip };
if ft.is_dir() {
// on the folder's own disk only (issue 324)
if m.dev() == dev && m.st_flags() & SF_DATALESS == 0 { SizeEntry::Dir(entry.path()) } else { SizeEntry::Skip }
} else if ft.is_file() {
SizeEntry::File(if on_disk { m.blocks() * 512 } else { m.len() })
} else {
SizeEntry::Skip
}
}
/// Depth first, one open listing per level and nothing else kept: the memory stays the same
/// whatever the folder holds (issue 429; the walk before read each folder whole, several at
/// a time).
fn size_walk(dir: &Path, dev: u64, on_disk: bool) -> u64 {
let mut total = 0u64;
let mut stack: Vec<fs::ReadDir> = fs::read_dir(dir).into_iter().collect();
while let Some(top) = stack.last_mut() {
let Some(entry) = top.next() else {
stack.pop();
continue;
};
let Ok(entry) = entry else { continue };
match size_entry(&entry, dev, on_disk) {
SizeEntry::File(n) => total += n,
SizeEntry::Dir(p) => stack.extend(fs::read_dir(p)),
SizeEntry::Skip => {}
}
}
total
}
/// A folder's size in bytes (see `folder_size_with`).
#[uniffi::export]
pub fn folder_size(path: String) -> u64 {
folder_size_with(path, false)
}
#[uniffi::export]
pub fn core_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
static SHOW_SYSTEM_FILES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Whether the files macOS keeps for itself (.DS_Store, .localized, Icon\r, ._ copies…) are
/// listed when hidden items are. Off by default, like Windows' "protected operating system
/// files"; the next `arrange` follows it.
#[uniffi::export]
pub fn set_show_system_files(show: bool) {
SHOW_SYSTEM_FILES.store(show, std::sync::atomic::Ordering::Relaxed);
}
fn show_system_files() -> bool {
SHOW_SYSTEM_FILES.load(std::sync::atomic::Ordering::Relaxed)
}
/// A file macOS writes for its own bookkeeping, which nobody opens by hand.
pub(crate) fn is_system_file(name: &str) -> bool {
const NAMES: &[&str] = &[
".DS_Store", ".localized", "Icon\r", ".Spotlight-V100", ".fseventsd", ".Trashes", ".TemporaryItems",
".DocumentRevisions-V100", ".VolumeIcon.icns", ".apdisk", ".com.apple.timemachine.donotpresent",
".PKInstallSandboxManager", ".PKInstallSandboxManager-SystemSoftware", ".file", ".hotfiles.btree", ".vol",
];
NAMES.contains(&name) || name.starts_with("._")
}
#[cfg(test)]
mod folder_size_tests {
#[test]
fn a_size_counts_files_and_stays_out_of_links() {
let d = std::env::temp_dir().join(format!("rf-mac-size-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("a/b")).unwrap();
std::fs::write(d.join("a/one"), vec![0u8; 1000]).unwrap();
std::fs::write(d.join("a/b/two"), vec![0u8; 500]).unwrap();
// a link back to the top is not walked (it would never end)
std::os::unix::fs::symlink(&d, d.join("a/b/loop")).unwrap();
assert_eq!(super::folder_size(d.display().to_string()), 1500);
assert!(super::folder_size_with(d.display().to_string(), true) >= 1500);
let _ = std::fs::remove_dir_all(&d);
}
}
#[cfg(test)]
mod system_files_tests {
use super::is_system_file;
#[test]
fn knows_the_files_macos_keeps_for_itself() {
for n in [".DS_Store", ".localized", "Icon\r", "._photo.jpg", ".Spotlight-V100"] {
assert!(is_system_file(n), "{n}");
}
for n in [".git", ".config", ".zshrc", "Icon", "DS_Store"] {
assert!(!is_system_file(n), "{n}");
}
}
}
/// `UF_HIDDEN` from `<sys/stat.h>`: hidden in Finder without a leading dot (`chflags hidden`).
const UF_HIDDEN: u32 = 0x8000;
fn list(dir: &Path) -> Result<Vec<Entry>, FsError> {
let names: Vec<_> = fs::read_dir(dir)
.map_err(|e| FsError::from_io(dir, e))?
.filter_map(|d| d.ok().map(|d| d.file_name()))
.collect();
// Each stat is its own system call; on a slow volume running them side by side is what
// makes a big folder come up quickly.
Ok(names.par_iter().filter_map(|n| entry(dir, n)).collect())
}
fn entry(dir: &Path, name: &std::ffi::OsStr) -> Option<Entry> {
let name_str = name.to_str()?;
let full = dir.join(name);
let lmeta = fs::symlink_metadata(&full).ok()?;
let link = lmeta.file_type().is_symlink();
// A link to a folder opens like a folder, as in Finder; a broken link stays a file.
let meta = if link { fs::metadata(&full).unwrap_or(lmeta.clone()) } else { lmeta.clone() };
let kind = if meta.is_dir() { EntryKind::Dir } else { EntryKind::File };
let ms = |t: std::io::Result<std::time::SystemTime>| {
t.ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as i64)
};
let mut a = 0;
if name_str.starts_with('.') || flags(&lmeta) & UF_HIDDEN != 0 {
a |= attrs::HIDDEN;
}
if meta.permissions().readonly() {
a |= attrs::READONLY;
}
if link {
a |= attrs::REPARSE_POINT;
}
if kind == EntryKind::Dir {
a |= attrs::DIRECTORY;
}
let size = if kind == EntryKind::Dir { 0 } else { meta.len() };
let mut e = Entry::new(name_str, kind, size, ms(meta.modified()), ms(meta.created()), a);
e.link = link;
Some(e)
}
#[cfg(target_os = "macos")]
fn flags(m: &fs::Metadata) -> u32 {
use std::os::macos::fs::MetadataExt;
m.st_flags()
}
#[cfg(not(target_os = "macos"))]
fn flags(_: &fs::Metadata) -> u32 {
0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lists_sorts_and_hides() {
let d = std::env::temp_dir().join(format!("rf-mac-test-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(d.join("dir10")).unwrap();
fs::create_dir_all(d.join("dir2")).unwrap();
fs::write(d.join("b.txt"), b"12345").unwrap();
fs::write(d.join(".secret"), b"").unwrap();
let f = Folder::open(d.display().to_string(), SortColumn::Name, true, false, false).unwrap();
let names: Vec<String> = (0..f.count()).map(|r| f.item(r).unwrap().name).collect();
assert_eq!(names, ["b.txt", "dir2", "dir10"]);
assert_eq!(f.total(), 4);
f.arrange(SortColumn::Name, true, false, false, "DIR".into(), None, true);
assert_eq!(f.count(), 2);
f.arrange(SortColumn::Name, true, true, false, String::new(), None, true);
assert_eq!(f.item(0).unwrap().name, "dir2", "folders first");
f.arrange(SortColumn::Size, false, false, true, String::new(), None, true);
assert_eq!(f.item(0).unwrap().name, "b.txt");
assert_eq!(f.item(0).unwrap().size, 5);
assert!(f.row_of(".secret".into()).is_some());
assert_eq!(folder_size(d.display().to_string()), 5);
assert!(matches!(Folder::open(d.join("nope").display().to_string(), SortColumn::Name, true, false, false), Err(FsError::NotFound { .. })));
fs::remove_dir_all(&d).unwrap();
}
#[test]
fn a_grouped_list_sorts_each_group_by_the_column_picked() {
let d = tempfile_dir("grouped");
let at = |n: &str, secs: u64| {
let p = d.join(n);
fs::write(&p, b"x").unwrap();
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
fs::File::options().write(true).open(&p).unwrap().set_modified(t).unwrap();
};
at("a.dmg", 1_000);
at("b.dmg", 3_000);
at("c.docx", 2_000);
at("d.docx", 4_000);
let f = Folder::open(d.display().to_string(), SortColumn::Name, true, false, false).unwrap();
// grouped by type (ascending), newest first inside each type
f.arrange(SortColumn::Kind, true, false, false, String::new(), Some(SortColumn::Modified), false);
let names: Vec<String> = (0..f.count()).map(|r| f.item(r).unwrap().name).collect();
assert_eq!(names, ["b.dmg", "a.dmg", "d.docx", "c.docx"]);
f.arrange(SortColumn::Kind, true, false, false, String::new(), Some(SortColumn::Modified), true);
let names: Vec<String> = (0..f.count()).map(|r| f.item(r).unwrap().name).collect();
assert_eq!(names, ["a.dmg", "b.dmg", "c.docx", "d.docx"]);
let _ = fs::remove_dir_all(&d);
}
#[test]
fn a_gathered_listing_keeps_each_items_own_folder() {
let a = tempfile_dir("gathered-a");
let b = tempfile_dir("gathered-b");
fs::write(a.join("one.txt"), b"1").unwrap();
fs::write(b.join("two.txt"), b"22").unwrap();
let paths = vec![a.join("one.txt").display().to_string(), b.join("two.txt").display().to_string(), "/no/such/file".into()];
let f = Folder::gathered("rustyfiles:tag/x".into(), paths, SortColumn::Name, true, true, false);
assert_eq!(f.count(), 2);
assert_eq!(f.child_path(0).unwrap(), a.join("one.txt").display().to_string());
assert_eq!(f.child_path(1).unwrap(), b.join("two.txt").display().to_string());
let _ = (fs::remove_dir_all(&a), fs::remove_dir_all(&b));
}
fn tempfile_dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("rf-mac-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
}