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
Preview pane: a handler that stops answering is put away (748)
gelenmedyac8b5e58de541
diff --git a/crates/rf-win/src/preview_host.rs b/crates/rf-win/src/preview_host.rsindex 691b6b10..cf649b75 100644--- a/crates/rf-win/src/preview_host.rs+++ b/crates/rf-win/src/preview_host.rs@@ -33,6 +33,9 @@ const PREVIEW_HANDLER_IID: &str = "{8895b1c6-b41f-4c1c-a562-0d564250836f}";/// CLSID of the preview handler registered for `path`'s type, if any.pub fn handler_for(path: &Path) -> Option<GUID> {+ if stopped_answering(path) {+ return None;+ }let ext = path.extension()?.to_string_lossy().to_string();let ext = wide(format!(".{ext}"));let iid = wide(PREVIEW_HANDLER_IID);@@ -537,12 +540,94 @@ fn ensure_host_window() -> Option<HWND> {fn unload(handler: Option<IPreviewHandler>) {if let Some(ph) = handler {+ // a handler that stopped answering is let go without a word: Unload and even Release would be calls into it and wait+ if ph.as_raw() as usize == ABANDONED.load(Ordering::SeqCst) {+ std::mem::forget(ph);+ return;+ }unsafe {let _ = ph.Unload();}}}+// ------------------------------------------------------------------ a handler that stops answering++/// The types whose preview handler stopped answering while it was shown, this session (lowercase, with the dot). They are not+/// previewed again: the pane shows what it shows for a type without a handler.+static HUNG_TYPES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());+/// The handler that stopped answering (its interface pointer): [`unload`] lets it go without calling it.+static ABANDONED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+/// How long a handler's window may take to answer before it counts as stopped (Windows itself calls a window hung after 5 s).+const ANSWER_WITHIN_MS: u32 = 5000;+/// How often a shown handler is asked.+const WATCH_EVERY: std::time::Duration = std::time::Duration::from_secs(2);++fn type_of(path: &Path) -> Option<String> {+ path.extension().map(|e| format!(".{}", e.to_string_lossy().to_lowercase()))+}++/// Whether `path`'s type had its handler stop answering this session.+pub fn stopped_answering(path: &Path) -> bool {+ type_of(path).is_some_and(|t| HUNG_TYPES.lock().unwrap_or_else(|e| e.into_inner()).contains(&t))+}++/// Watches the handler just shown for `path` in `host` while generation `epoch` lasts: every [`WATCH_EVERY`] each window the handler+/// put in the host is asked to answer. One that does not within [`ANSWER_WITHIN_MS`] (it hangs) has the host taken off the app+/// window and hidden at once, without waiting on any thread, the handler let go, and the type is not previewed again this session.+///+/// WHY (issue 748: right-clicking an .epub froze rustyfiles with the preview pane open; with it closed it never did; the machine has+/// Readest, calibre and SumatraPDF, one of which previews .epub). A preview handler is someone else's code running in Windows'+/// `prevhost.exe`; its window sits in ours, so when it hangs, the window it sits in stops answering too. Whatever the handler does,+/// it must not take the file manager with it (modular isolation).+fn watch_shown(epoch: u64, host: HWND, handler: usize, path: &Path) {+ let (host, kind) = (host.0 as isize, type_of(path).unwrap_or_default());+ let _ = std::thread::Builder::new().name("preview-watch".into()).spawn(move || {+ loop {+ std::thread::sleep(WATCH_EVERY);+ if GEN.load(Ordering::SeqCst) != epoch {+ return;+ }+ let host = HWND(host as *mut _);+ if handler_windows(host).into_iter().all(answers) {+ continue;+ }+ if GEN.load(Ordering::SeqCst) != epoch {+ return;+ }+ log::warn!("preview: the handler for {kind} files stopped answering; its preview is put away and {kind} files are not previewed again until rustyfiles restarts");+ HUNG_TYPES.lock().unwrap_or_else(|e| e.into_inner()).push(kind.clone());+ ABANDONED.store(handler, Ordering::SeqCst);+ GEN.fetch_add(1, Ordering::SeqCst);+ unsafe { detach_window(host) };+ return;+ }+ });+}++/// The windows directly in `host` (the handler's own).+fn handler_windows(host: HWND) -> Vec<HWND> {+ use windows::Win32::UI::WindowsAndMessaging::{GW_CHILD, GW_HWNDNEXT, GetWindow};+ let mut out = Vec::new();+ let mut next = unsafe { GetWindow(host, GW_CHILD) }.ok();+ while let Some(w) = next.filter(|w| !w.0.is_null()) {+ out.push(w);+ if out.len() >= 8 {+ break;+ }+ next = unsafe { GetWindow(w, GW_HWNDNEXT) }.ok();+ }+ out+}++/// Whether `w` takes a message within [`ANSWER_WITHIN_MS`] (a window Windows already knows is hung fails at once).+fn answers(w: HWND) -> bool {+ use windows::Win32::UI::WindowsAndMessaging::{SMTO_ABORTIFHUNG, SMTO_BLOCK, SendMessageTimeoutW, WM_NULL};+ let r = unsafe { SendMessageTimeoutW(w, WM_NULL, WPARAM(0), LPARAM(0), SMTO_ABORTIFHUNG | SMTO_BLOCK, ANSWER_WITHIN_MS, None) };+ // (a window that is gone is not a hang)+ r.0 != 0 || !unsafe { windows::Win32::UI::WindowsAndMessaging::IsWindow(Some(w)) }.as_bool()+}+/// Theme colors for handlers that support it (dark mode text/background).pub struct Colors {pub background: u32,@@ -567,7 +652,7 @@ pub fn show(owner: isize, path: &Path, rect: RECT, colors: &Colors) -> bool {/// Like [`show`], cancelling without attaching if [`begin_show`], [`detach_for_hide`], or/// [`detach_from`] advanced the generation while the handler was loading (issue 471).pub fn show_gen(epoch: u64, owner: isize, path: &Path, rect: RECT, colors: &Colors) -> bool {- if GEN.load(Ordering::SeqCst) != epoch || !is_window_alive(owner) {+ if GEN.load(Ordering::SeqCst) != epoch || !is_window_alive(owner) || stopped_answering(path) {return false;}let Some(hwnd) = ensure_host_window() else { return false };@@ -620,6 +705,7 @@ pub fn show_gen(epoch: u64, owner: isize, path: &Path, rect: RECT, colors: &Colounsafe {let _ = ph.SetRect(&r);}+ watch_shown(epoch, hwnd, ph.as_raw() as usize, path);true}@@ -966,3 +1052,73 @@ mod mf_tests {let _ = std::fs::remove_file(&pdf_path);}}++#[cfg(test)]+mod watch_tests {+ use std::path::Path;++ /// A type whose handler hung is told apart by its extension, in any case, and only that type.+ #[test]+ fn a_hung_type_is_known_by_its_extension_in_any_case() {+ super::HUNG_TYPES.lock().unwrap().push(".rfwatchtest".into());+ assert!(super::stopped_answering(Path::new(r"C:\books\A Book.RFWATCHTEST")));+ assert!(super::handler_for(Path::new(r"C:\books\a.rfwatchtest")).is_none());+ assert!(!super::stopped_answering(Path::new(r"C:\books\a.pdf")));+ assert!(!super::stopped_answering(Path::new(r"C:\books\no extension")));+ }++ /// A handler whose window stops answering (here: a window of another thread that never reads its messages) has its type marked+ /// and the shown generation ended, within the watch's two seconds and the five it waits for an answer. Takes about 7 s.+ #[test]+ #[ignore]+ fn a_handler_window_that_stops_answering_is_put_away() {+ use windows::Win32::UI::WindowsAndMessaging::*;+ use windows::core::w;+ let host = super::ensure_host_window().expect("host window");+ let raw = host.0 as isize;+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || unsafe {+ let child = CreateWindowExW(+ WS_EX_NOPARENTNOTIFY,+ w!("STATIC"),+ w!("hung"),+ WS_CHILD | WS_VISIBLE,+ 0,+ 0,+ 50,+ 50,+ Some(windows::Win32::Foundation::HWND(raw as *mut _)),+ None,+ None,+ None,+ );+ tx.send(child.is_ok()).unwrap();+ // never reads a message again+ std::thread::sleep(std::time::Duration::from_secs(30));+ });+ assert!(rx.recv().unwrap(), "the child window was made");+ let epoch = super::GEN.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;+ let path = Path::new(r"C:\x\book.rfhangtest");+ super::watch_shown(epoch, host, 0x1234, path);+ let until = std::time::Instant::now() + std::time::Duration::from_secs(15);+ while !super::stopped_answering(path) && std::time::Instant::now() < until {+ unsafe {+ let mut m = MSG::default();+ while PeekMessageW(&mut m, None, 0, 0, PM_REMOVE).as_bool() {+ let _ = TranslateMessage(&m);+ DispatchMessageW(&m);+ }+ }+ std::thread::sleep(std::time::Duration::from_millis(20));+ }+ assert!(super::stopped_answering(path), "the type is marked");+ assert_ne!(super::GEN.load(std::sync::atomic::Ordering::SeqCst), epoch, "the shown generation ended");+ assert_eq!(super::ABANDONED.load(std::sync::atomic::Ordering::SeqCst), 0x1234, "the handler is let go");+ }++ /// A window that is gone does not count as hung.+ #[test]+ fn a_window_that_is_gone_is_not_a_hang() {+ assert!(super::answers(windows::Win32::Foundation::HWND(0xdead_0000usize as *mut _)), "no such window: not a hang");+ }+}