Skip to content

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.

Files dropped on a script or another file with a drop handler go to it (865)

denfry9af5057bde55
diff --git a/crates/rf-app/src/folder_view.rs b/crates/rf-app/src/folder_view.rs
index 6179d028..de7b92c8 100644
--- a/crates/rf-app/src/folder_view.rs
+++ b/crates/rf-app/src/folder_view.rs
@@ -8989,7 +8989,8 @@ impl FolderView {
/// Use the rendered path, so a refresh during a drag cannot retarget it by shifting row indices.
fn file_drop_target(row: Stateful<Div>, target: PathBuf, is_dir: bool, p: &Palette) -> Stateful<Div> {
- if !is_dir && !crate::program_launch::accepts_program(&target) {
+ let program = !is_dir && crate::program_launch::accepts_program(&target);
+ if !is_dir && !program && !crate::program_launch::takes_drops(&target) {
return row;
}
let (color, border) = (p.selection, p.accent);
@@ -9016,8 +9017,10 @@ fn file_drop_target(row: Stateful<Div>, target: PathBuf, is_dir: bool, p: &Palet
}
if is_dir {
crate::workspace::drop_files(paths, target.clone(), cx);
- } else {
+ } else if program {
crate::ops::drop_on_program(target.clone(), paths.paths().to_vec(), window, cx);
+ } else {
+ crate::ops::drop_on_handler(target.clone(), paths.paths().to_vec(), window, cx);
}
})
}
diff --git a/crates/rf-app/src/ops.rs b/crates/rf-app/src/ops.rs
index a574ef4c..4e3761e4 100644
--- a/crates/rf-app/src/ops.rs
+++ b/crates/rf-app/src/ops.rs
@@ -1728,6 +1728,21 @@ pub(crate) fn drop_transfer(sources: &[std::path::PathBuf], dest: &std::path::Pa
if kind == rf_win::fileops::Transfer::Move && dnd_hint::allowed() & dnd_hint::MOVE == 0 { rf_win::fileops::Transfer::Copy } else { kind }
}
+/// Files dropped on a file whose type has a drop handler (`program_launch::takes_drops`): the shell's handler gets them, as Explorer
+/// hands them over (issue 865). On the shell thread, which owns COM; a refusal is told like a program that could not be started.
+pub(crate) fn drop_on_handler(target: PathBuf, files: Vec<PathBuf>, window: &mut Window, cx: &mut App) {
+ let window = window.window_handle();
+ let (tx, rx) = futures::channel::oneshot::channel();
+ rf_win::sta::run(move |owner| {
+ let _ = tx.send(rf_win::sendto::drop_on(owner, &target, &files));
+ });
+ cx.spawn(async move |cx| {
+ if let Ok(Err(err)) = rx.await {
+ let _ = window.update(cx, |_, window, cx| crate::program_launch::launch_error(err, window, cx));
+ }
+ }).detach();
+}
+
pub(crate) fn drop_on_program(program: PathBuf, files: Vec<PathBuf>, window: &mut Window, cx: &mut App) {
use windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_CONTROL, VK_SHIFT};
let ctrl = unsafe { GetAsyncKeyState(VK_CONTROL.0 as i32) < 0 } || gpui_windows::dnd_hint::allowed() & gpui_windows::dnd_hint::MOVE == 0;
diff --git a/crates/rf-app/src/program_launch.rs b/crates/rf-app/src/program_launch.rs
index ffff30f1..407a8522 100644
--- a/crates/rf-app/src/program_launch.rs
+++ b/crates/rf-app/src/program_launch.rs
@@ -34,6 +34,26 @@ pub(crate) fn accepts_program(path: &Path) -> bool {
path.extension().is_some_and(|e| ["exe", "com", "bat", "cmd", "lnk"].iter().any(|ext| e.eq_ignore_ascii_case(ext)))
}
+/// Whether files dropped on `path` go to its type's drop handler, as Explorer gives them (a Python script runs with them, a zip takes
+/// them in; issue 865). Programs and shortcuts are not asked here: [`accepts_program`] starts them itself. Remembered per extension
+/// for a minute: every row of the list asks while it is drawn, and a type installed meanwhile is seen soon enough.
+pub(crate) fn takes_drops(path: &Path) -> bool {
+ use std::collections::HashMap;
+ use std::sync::{Mutex, OnceLock};
+ use std::time::{Duration, Instant};
+ static SEEN: OnceLock<Mutex<HashMap<String, (bool, Instant)>>> = OnceLock::new();
+ let Some(ext) = path.extension().map(|e| e.to_string_lossy().to_lowercase()) else { return false };
+ let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
+ if let Some(&(yes, at)) = seen.get(&ext)
+ && at.elapsed() < Duration::from_secs(60)
+ {
+ return yes;
+ }
+ let yes = rf_win::fileactions::has_drop_handler(path);
+ seen.insert(ext, (yes, Instant::now()));
+ yes
+}
+
/// Starts an executable or a batch script, or returns the directory a shortcut points to.
/// Run off the UI thread. Paths are passed as individual arguments.
pub(crate) fn launch(program: PathBuf, arguments: Vec<OsString>, uses_paths: bool, folder: Option<PathBuf>) -> anyhow::Result<Option<PathBuf>> {
diff --git a/crates/rf-win/src/fileactions.rs b/crates/rf-win/src/fileactions.rs
index 6f6f1afe..09e76096 100644
--- a/crates/rf-win/src/fileactions.rs
+++ b/crates/rf-win/src/fileactions.rs
@@ -56,6 +56,28 @@ pub fn has_verb(p: &Path, verb: &str) -> bool {
})
}
+/// Whether the file's type has a drop handler (`shellex\DropHandler` of the class Windows opens it with, the user's choice
+/// included): the shell then takes files dropped ON such a file, as Explorer does. A Python script runs with them (the Python
+/// launcher's handler), a zip takes them in, a `.vbs` or `.js` gets them as arguments. Registry reads only.
+pub fn has_drop_handler(p: &Path) -> bool {
+ use windows::Win32::System::Registry::{HKEY, KEY_READ, RegCloseKey, RegOpenKeyExW};
+ use windows::Win32::UI::Shell::{ASSOCF_NONE, ASSOCKEY_SHELLEXECCLASS, AssocQueryKeyW};
+ let Some(ext) = p.extension().map(|e| format!(".{}", e.to_string_lossy())) else { return false };
+ let ext = wide(&ext);
+ // SAFETY: the string ends in a zero; every key opened here is closed before returning
+ unsafe {
+ let Ok(class) = AssocQueryKeyW(ASSOCF_NONE, ASSOCKEY_SHELLEXECCLASS, PCWSTR(ext.as_ptr()), PCWSTR::null()) else { return false };
+ let sub = wide(r"shellex\DropHandler");
+ let mut handler = HKEY::default();
+ let found = RegOpenKeyExW(class, PCWSTR(sub.as_ptr()), None, KEY_READ, &mut handler).is_ok();
+ if found {
+ let _ = RegCloseKey(handler);
+ }
+ let _ = RegCloseKey(class);
+ found
+ }
+}
+
pub fn set_wallpaper(path: &Path) -> anyhow::Result<()> {
let mut w = wide(path);
unsafe {
@@ -97,6 +119,15 @@ pub fn install_font_for_user(path: &Path) -> anyhow::Result<PathBuf> {
mod tests {
use super::*;
+ #[test]
+ fn only_a_type_with_a_drop_handler_takes_files_dropped_on_it() {
+ // (every Windows registers one for programs and batch files: they are started with the files)
+ assert!(has_drop_handler(Path::new(r"C:\x\tool.exe")));
+ assert!(has_drop_handler(Path::new(r"C:\x\job.BAT")));
+ assert!(!has_drop_handler(Path::new(r"C:\x\notes.rf-no-such-type")));
+ assert!(!has_drop_handler(Path::new(r"C:\x\no-extension")));
+ }
+
#[test]
fn a_verb_is_found_only_when_the_type_has_it() {
// every Windows gives a program "run as administrator", and nothing gives it a verb of this name
diff --git a/crates/rf-win/src/sendto.rs b/crates/rf-win/src/sendto.rs
index a2b7347d..b70c7183 100644
--- a/crates/rf-win/src/sendto.rs
+++ b/crates/rf-win/src/sendto.rs
@@ -9,7 +9,7 @@ use windows::Win32::Foundation::{HWND, POINTL};
use windows::Win32::Storage::FileSystem::{FILE_ATTRIBUTE_HIDDEN, FILE_ATTRIBUTE_SYSTEM};
use windows::Win32::System::Com::CoTaskMemFree;
use windows::Win32::System::Ole::{DROPEFFECT_COPY, DROPEFFECT_LINK, DROPEFFECT_NONE, IDropTarget};
-use windows::Win32::System::SystemServices::MK_LBUTTON;
+use windows::Win32::System::SystemServices::{MK_LBUTTON, MODIFIERKEYS_FLAGS};
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
use windows::Win32::UI::Shell::{
FOLDERID_SendTo, IShellFolder, IShellItem, KF_FLAG_DEFAULT, SHBindToParent, SHCreateItemFromParsingName, SHGetKnownFolderPath,
@@ -94,6 +94,31 @@ pub fn send(owner: HWND, target: &Path, items: &[PathBuf]) -> anyhow::Result<()>
Ok(())
}
+/// Drops `items` (files of one folder) on the FILE `target`, as a drag let go over it in Explorer: its type's drop handler gets them
+/// (a Python script runs with them; see `fileactions::has_drop_handler`). A copy or a link only, never a move: a handler that takes
+/// files in (an archive) must not take them away from where they are. Call on the shell STA thread with its owner window.
+///
+/// The handler is walked through a whole drag, `DragOver` and a `Drop` with the button already up, unlike [`send`]: the Python
+/// launcher's handler answered a bare enter-and-drop with success and started nothing (measured with the manual test below).
+pub fn drop_on(owner: HWND, target: &Path, items: &[PathBuf]) -> anyhow::Result<()> {
+ let data = crate::dnd::data_object(items)?;
+ let drop = drop_target(owner, target)?;
+ let pt = POINTL::default();
+ let mut effect = DROPEFFECT_COPY | DROPEFFECT_LINK;
+ unsafe { drop.DragEnter(&data, MK_LBUTTON, pt, &mut effect)? };
+ let mut effect = DROPEFFECT_COPY | DROPEFFECT_LINK;
+ unsafe { drop.DragOver(MK_LBUTTON, pt, &mut effect)? };
+ if effect == DROPEFFECT_NONE {
+ unsafe {
+ let _ = drop.DragLeave();
+ }
+ anyhow::bail!("{} takes none of these items", target.display());
+ }
+ let mut effect = DROPEFFECT_COPY | DROPEFFECT_LINK;
+ unsafe { drop.Drop(&data, MODIFIERKEYS_FLAGS(0), pt, &mut effect)? };
+ Ok(())
+}
+
/// The item's drop handler, bound through its real parent in the shell namespace (a drive root's parent is "This PC").
fn drop_target(owner: HWND, path: &Path) -> anyhow::Result<IDropTarget> {
let abs = crate::dnd::parse(path)?;
@@ -122,6 +147,34 @@ mod tests {
assert!(targets().iter().all(|t| !t.path.file_name().is_some_and(|n| n.eq_ignore_ascii_case("desktop.ini"))));
}
+ /// Drops a file on a Python script in a temporary folder and waits for the script to write down what it was given, as Explorer's
+ /// drop runs it (issue 865). Needs Python's launcher with its drop handler. `cargo test -p rf-win drop_on -- --ignored --nocapture`
+ #[test]
+ #[ignore]
+ fn manual_drop_on_a_python_script() {
+ crate::shell::ensure_com();
+ let dir = std::env::temp_dir().join("rf-drop-on-probe");
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let script = dir.join("echo.py");
+ std::fs::write(&script, "import sys, pathlib
+pathlib.Path(sys.argv[0]).with_name('out.txt').write_text('|'.join(sys.argv[1:]))
+").unwrap();
+ let input = dir.join("clip.mp4");
+ std::fs::write(&input, b"x").unwrap();
+ drop_on(HWND::default(), &script, std::slice::from_ref(&input)).unwrap();
+ let out = dir.join("out.txt");
+ for _ in 0..100 {
+ if out.exists() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+ let got = std::fs::read_to_string(&out).unwrap_or_default();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(got.eq_ignore_ascii_case(&input.to_string_lossy()), "the script got {got:?}");
+ }
+
/// Sends a file of a temporary folder to "Compressed (zipped) folder" and waits for the zip to appear next to it, as Explorer's
/// Send to makes it. Touches nothing outside that folder. `cargo test -p rf-win sendto -- --ignored --nocapture`
#[test]
@@ -188,3 +241,4 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
}
+