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
//! Shell folders without a file-system path (an MTP phone, Phone Link's mobile devices):
//! copying items out and the notice for what a first, read-only version leaves out.
use std::path::PathBuf;
use rf_win::shellfolder::ShellChild;
use crate::t;
/// A short message in the Status Center: what was asked for cannot be done in a shell folder.
pub fn read_only_notice(cx: &mut gpui_kit::App) {
crate::status_center::start(cx, t!("Bu klasör salt okunur").to_string(), |_| {
Err(anyhow::anyhow!(t!("Telefon gibi cihazlardaki öğeler burada değiştirilemez; kopyalayıp başka bir klasöre yapıştırabilirsiniz.")))
});
}
/// Ctrl+C on items of a shell folder: they are copied into a fresh temp folder with the shell's
/// copy engine (Status Center shows it), then those copies go on the clipboard. The clipboard is
/// emptied at once so a quick paste cannot paste what was there before, and what the user
/// copies meanwhile is left alone. Items that are real files go on the clipboard as they are.
///
/// `cut`: the copies go on the clipboard to be moved, and once a paste has moved them all away (within an hour, while nothing else
/// was copied) the items are deleted from the device: a move off a phone (issue 221: a cut was a copy and the files stayed there).
/// Copies from a device that have not put their files on the clipboard yet (see [`device_copy_pending`]).
static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// Holds one copy in [`PENDING`] for as long as it runs.
struct Pending;
impl Pending {
fn begin() -> Pending {
PENDING.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Pending
}
}
impl Drop for Pending {
fn drop(&mut self) {
PENDING.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
}
/// Whether a copy from a phone (or another device) is still pulling its files: the clipboard is empty until it has, so a paste must
/// wait for it. Issue 475: a paste made while the pull ran found an empty clipboard and did nothing, without a word; the phone was
/// then unplugged, which stopped the pull too, and nothing had arrived anywhere.
pub fn device_copy_pending() -> bool {
PENDING.load(std::sync::atomic::Ordering::SeqCst) > 0
}
pub fn copy_items(cx: &mut gpui_kit::App, items: Vec<ShellChild>, cut: bool) {
if items.is_empty() {
return;
}
let (tx, rx) = std::sync::mpsc::channel();
rf_win::sta::run(move |owner| {
if let Err(e) = rf_win::clipboard::clear(owner) {
log::warn!("clipboard: {e:#}");
}
let _ = tx.send(rf_win::clipboard::sequence());
});
let names = items.iter().map(|c| c.name.as_str()).collect::<Vec<_>>().join(", ");
let title = format!("{} {}", t!("Cihazdan kopyalanıyor:"), names);
let pending = Pending::begin();
crate::status_center::start(cx, title, move |_| {
// (held until the files are on the clipboard, or the copy gave up)
let _pending = pending;
let seq = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap_or(0);
let real = copy_to_temp(&items)?;
if real.is_empty() {
return Ok(false);
}
if rf_win::clipboard::sequence() != seq {
return Ok(true);
}
let kind = if cut { rf_win::fileops::Transfer::Move } else { rf_win::fileops::Transfer::Copy };
let (tx, rx) = std::sync::mpsc::channel();
let on_clip = real.clone();
rf_win::sta::run(move |owner| {
let _ = tx.send(rf_win::clipboard::set_files(owner, &on_clip, kind).map(|()| rf_win::clipboard::sequence()));
});
let ours = rx.recv().map_err(|_| anyhow::anyhow!("clipboard"))??;
if cut {
// only the device's items (real files were put on the clipboard as they are, and a paste moves those itself)
let originals: Vec<PathBuf> = items.iter().filter(|c| c.fs_path.is_none()).map(|c| PathBuf::from(&c.parsing)).collect();
let copies: Vec<PathBuf> = real.into_iter().filter(|p| !items.iter().any(|c| c.fs_path.as_ref() == Some(p))).collect();
if !originals.is_empty() {
std::thread::spawn(move || {
delete_once_moved(copies, ours, move || {
rf_win::shell::ensure_com();
rf_win::fileops::delete(&originals, true).map(|_| ())
})
});
}
}
Ok(true)
});
}
impl crate::folder_view::FolderView {
/// Right-click in a shell folder (a phone, Libraries…): the shell's own menu for the selected
/// items, found by their parsing names (they have no path), or for the folder's background.
/// The shell carries out what is chosen (copy, delete on the device, properties…); the
/// listing is read again afterwards.
pub fn show_shell_folder_menu(&mut self, background: bool, cx: &mut gpui_kit::Context<Self>) {
let rf_core::history::Location::Shell { parsing, .. } = self.location().clone() else { return };
let mut sel: Vec<u32> = self.selected.iter().copied().collect();
sel.sort_unstable();
let items: Vec<PathBuf> = if background { Vec::new() } else { sel.iter().filter_map(|&i| self.shell_items.get(i as usize)).map(|c| PathBuf::from(&c.parsing)).collect() };
let (tx, rx) = futures::channel::oneshot::channel();
rf_win::sta::run(move |owner| {
let mut pt = windows::Win32::Foundation::POINT::default();
unsafe {
let _ = windows::Win32::UI::WindowsAndMessaging::GetCursorPos(&mut pt);
}
let r = match items.as_slice() {
[] => rf_win::ctxmenu::show_for_background(owner, std::path::Path::new(&parsing), (pt.x, pt.y), false, &[]),
[one] => rf_win::ctxmenu::show_for_one(owner, one, (pt.x, pt.y), false, &[]),
many => rf_win::ctxmenu::show_for_items(owner, many, (pt.x, pt.y), false, &[]),
};
let _ = tx.send(r.map_err(|e| format!("{e:#}")));
});
cx.spawn(async move |this, cx| {
match rx.await {
Ok(Ok(rf_win::ctxmenu::MenuOutcome::Dismissed)) | Err(_) => {}
Ok(Ok(_)) => {
// the device may have changed (a deletion, a new folder): list it again
let _ = this.update(cx, |v, cx| v.refresh(cx));
}
Ok(Err(e)) => log::info!("shell folder menu: {e}"),
}
})
.detach();
}
}
/// Ctrl+C / Ctrl+X on items of an FTP server, (address, is a folder): as a phone's, they are downloaded into a fresh temp folder
/// (by the server's own transfer, Windows' FTP folder cannot be asked for that through its engine) and those copies go on the
/// clipboard; a cut deletes them from the server once a paste has moved the copies away (issue 223: the clipboard got the `ftp://`
/// addresses, which no paste can use).
pub fn copy_ftp(cx: &mut gpui_kit::App, items: Vec<(String, bool)>, cut: bool) {
if items.is_empty() {
return;
}
let (tx, rx) = std::sync::mpsc::channel();
rf_win::sta::run(move |owner| {
if let Err(e) = rf_win::clipboard::clear(owner) {
log::warn!("clipboard: {e:#}");
}
let _ = tx.send(rf_win::clipboard::sequence());
});
let names = items.iter().map(|(u, _)| u.rsplit('/').next().unwrap_or_default()).collect::<Vec<_>>().join(", ");
let title = format!("{} {}", t!("Cihazdan kopyalanıyor:"), names);
let pending = Pending::begin();
crate::status_center::start(cx, title, move |_| {
// (held until the files are on the clipboard, or the copy gave up)
let _pending = pending;
let seq = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap_or(0);
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
let dest = crate::archive_view::temp_root().join(format!("ftp-{stamp:x}"));
std::fs::create_dir_all(&dest)?;
let mut real = Vec::new();
for (url, is_dir) in &items {
real.push(rf_win::ftp::download_into(url, *is_dir, &dest)?);
}
if rf_win::clipboard::sequence() != seq {
return Ok(true);
}
let kind = if cut { rf_win::fileops::Transfer::Move } else { rf_win::fileops::Transfer::Copy };
let (tx, rx) = std::sync::mpsc::channel();
let on_clip = real.clone();
rf_win::sta::run(move |owner| {
let _ = tx.send(rf_win::clipboard::set_files(owner, &on_clip, kind).map(|()| rf_win::clipboard::sequence()));
});
let ours = rx.recv().map_err(|_| anyhow::anyhow!("clipboard"))??;
if cut {
std::thread::spawn(move || {
delete_once_moved(real, ours, move || {
for (url, is_dir) in &items {
rf_win::ftp::delete(url, *is_dir)?;
}
Ok(())
})
});
}
Ok(true)
});
}
/// Waits (up to an hour) for a paste to move the temp `copies` of a cut away, then deletes the originals (`delete_originals`). Gives up
/// when something that is no files was copied while the copies are still there.
fn delete_once_moved(copies: Vec<PathBuf>, ours: u32, delete_originals: impl FnOnce() -> anyhow::Result<()>) {
if copies.is_empty() {
return;
}
let until = std::time::Instant::now() + std::time::Duration::from_secs(3600);
while std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_secs(2));
if copies.iter().all(|p| !p.exists()) {
if let Err(e) = delete_originals() {
log::warn!("move: deleting the originals: {e:#}");
}
return;
}
let seq = rf_win::clipboard::sequence();
if seq != ours && copies.iter().all(|p| p.exists()) && !rf_win::clipboard::has_files() {
return;
}
}
}
/// Real files for the items: file-system items as they are, the others copied (blocking) into
/// a new folder under the temp root that `archive_view::clean_temp` clears after two days.
fn copy_to_temp(items: &[ShellChild]) -> anyhow::Result<Vec<PathBuf>> {
let mut out: Vec<PathBuf> = items.iter().filter_map(|c| c.fs_path.clone()).collect();
let virtual_items: Vec<String> = items.iter().filter(|c| c.fs_path.is_none()).map(|c| c.parsing.clone()).collect();
if virtual_items.is_empty() {
return Ok(out);
}
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
let dest = crate::archive_view::temp_root().join(format!("cihaz-{stamp:x}"));
std::fs::create_dir_all(&dest)?;
if !rf_win::shellfolder::copy_out(&virtual_items, &dest)? {
return Ok(Vec::new());
}
// what arrived: the shell names the copies, so the folder is read rather than guessed at
for e in std::fs::read_dir(&dest)? {
out.push(e?.path());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
/// Items inside a `.zip` have no file-system path, like a phone's: `copy_to_temp` pulls them
/// out into a temp folder and returns real files; items with a path pass through.
#[test]
fn items_without_a_path_become_real_files() {
if rf_win::engine_guard::not_run_without_shell("items_without_a_path_become_real_files") {
return;
}
let dir = std::env::temp_dir().join(format!("rf-shellview-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let src = dir.join("note.txt");
std::fs::write(&src, b"abc").unwrap();
let zip = dir.join("t.zip");
let ok = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command", &format!("Compress-Archive -Path '{}' -DestinationPath '{}'", src.display(), zip.display())])
.status()
.unwrap()
.success();
assert!(ok);
let mut kids = Vec::new();
rf_win::shellfolder::list(&zip.to_string_lossy(), &|| false, &mut |b| kids.extend(b)).unwrap();
let on_disk = ShellChild { name: "x".into(), parsing: src.to_string_lossy().into(), is_folder: false, fs_path: Some(src.clone()), size: None, modified_ms: None };
kids.push(on_disk);
let real = copy_to_temp(&kids).unwrap();
assert_eq!(real.len(), 2, "{real:?}");
assert!(real.iter().all(|p| p.is_file()), "{real:?}");
assert!(real.contains(&src));
let copy = real.iter().find(|p| **p != src).unwrap();
assert_eq!(std::fs::read(copy).unwrap(), b"abc");
let _ = std::fs::remove_dir_all(copy.parent().unwrap());
let _ = std::fs::remove_dir_all(&dir);
}
}