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.

49.1 KB
Raw Blame
//! Hosts Windows preview handlers (IPreviewHandler — what Explorer's preview pane uses for
//! Office documents, PDF, video/audio, fonts, …) in a borderless window owned by the app
//! window and kept over the preview pane.
//!
//! Everything runs on its own dedicated preview STA thread (`crate::sta::run_preview`), and
//! preview handlers are instantiated out-of-process (`CLSCTX_LOCAL_SERVER`, i.e. `prevhost.exe`)
//! first, while the host window stays unowned and hidden throughout `Unload` and `DoPreview`.
//! That prevents cross-thread Win32 deadlocks between the UI thread's window and the preview
//! host when opening or switching away from a previewed PDF (issue 471).

use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicIsize, AtomicU64, Ordering};

use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, CoCreateInstance, STGM_READ, STGM_SHARE_DENY_NONE};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Shell::PropertiesSystem::{IInitializeWithFile, IInitializeWithStream};
use windows::Win32::UI::Shell::{
    ASSOCF_INIT_DEFAULTTOSTAR, ASSOCSTR_SHELLEXTENSION, AssocQueryStringW, IInitializeWithItem, IPreviewHandler,
    IPreviewHandlerVisuals, IShellItem, SHCreateItemFromParsingName, SHCreateStreamOnFileEx,
};
use windows::Win32::UI::WindowsAndMessaging::{
    CreateWindowExW, DefWindowProcW, RegisterClassW, SW_HIDE, SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOOWNERZORDER,
    SWP_NOZORDER, SWP_SHOWWINDOW, SetWindowPos, ShowWindowAsync, WINDOW_EX_STYLE, WNDCLASSW, WS_CLIPCHILDREN,
    WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_POPUP,
};
use windows::core::{GUID, Interface, PCWSTR, w};

use crate::wide::wide;

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);
    let mut buf = [0u16; 64];
    let mut len = buf.len() as u32;
    unsafe {
        AssocQueryStringW(
            ASSOCF_INIT_DEFAULTTOSTAR,
            ASSOCSTR_SHELLEXTENSION,
            PCWSTR(ext.as_ptr()),
            PCWSTR(iid.as_ptr()),
            Some(windows::core::PWSTR(buf.as_mut_ptr())),
            &mut len,
        )
        .ok()
        .ok()?;
    }
    let s = crate::wide::from_wide(&buf);
    let s = s.trim_matches(|c| c == '{' || c == '}');
    GUID::try_from(s).ok()
}

struct Host {
    hwnd: HWND,
    owner: isize,
    path: Option<PathBuf>,
    handler: Option<IPreviewHandler>,
    /// Our own media player (Media Foundation's MFPlay) drawing into the same window, for
    /// audio / video that have no preview handler.
    player: Option<Player>,
}

struct Player {
    path: PathBuf,
    mp: windows::Win32::Media::MediaFoundation::IMFPMediaPlayer,
    /// Play was asked for before the file finished opening: the timer starts it.
    pending_play: u32,
    /// The last play / pause asked for, and when. MFPlay applies both asynchronously: its own
    /// state still says the old thing for a moment, and a second press decided from it would
    /// repeat the first command instead of undoing it.
    asked: Option<(bool, std::time::Instant)>,
    /// Where the first play starts, in seconds (the file was left at this point earlier: `media_play_from`).
    start_at: Option<f64>,
}

const PLAY_TIMER: usize = 1;
/// For this long after a play / pause, what was asked answers "is it playing" (see `Player::asked`).
const ASKED_HOLDS: std::time::Duration = std::time::Duration::from_millis(500);

/// What the video's own window tells the app: clicks on the picture land on that window, never
/// on the app's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaEvent {
    /// Playback was started or paused (by the app or by a click on the picture).
    Playing(bool),
    /// The picture was double-clicked.
    DoubleClick,
}

static MEDIA_EVENTS: std::sync::Mutex<Option<Box<dyn Fn(MediaEvent) + Send>>> = std::sync::Mutex::new(None);

/// Sends the player's events to `f` (called on the shell STA thread; the newest caller wins).
pub fn set_media_events(f: impl Fn(MediaEvent) + Send + 'static) {
    *MEDIA_EVENTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(f));
}

fn emit(e: MediaEvent) {
    if let Some(f) = MEDIA_EVENTS.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
        f(e);
    }
}

thread_local! {
    static HOST: RefCell<Option<Host>> = const { RefCell::new(None) };
}

unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
    use windows::Win32::UI::WindowsAndMessaging::{KillTimer, WM_LBUTTONDBLCLK, WM_LBUTTONUP, WM_PAINT, WM_SIZE, WM_TIMER};
    // the player, if any (never while HOST is borrowed: messages can arrive re-entrantly)
    let player = || HOST.with(|h| h.try_borrow().ok().and_then(|h| h.as_ref().and_then(|x| x.player.as_ref().map(|p| p.mp.clone()))));
    match msg {
        WM_TIMER if wp.0 == PLAY_TIMER => {
            // start playback once the file is open (MFPlay opens it asynchronously)
            let Some(mp) = player() else {
                unsafe {
                    let _ = KillTimer(Some(hwnd), PLAY_TIMER);
                }
                return LRESULT(0);
            };
            // paused meanwhile (a timer message already queued outlives KillTimer): nothing to start
            let wanted = HOST.with(|h| h.try_borrow().ok().and_then(|h| h.as_ref().and_then(|x| x.player.as_ref().map(|p| p.pending_play > 0)))).unwrap_or(true);
            if !wanted {
                unsafe {
                    let _ = KillTimer(Some(hwnd), PLAY_TIMER);
                }
                return LRESULT(0);
            }
            let ready = unsafe { mp.GetMediaItem() }.is_ok();
            let started = ready && {
                if muted_for_tests() {
                    unsafe {
                        let _ = mp.SetMute(true);
                    }
                }
                // (the place it was left at, once: the position can only be set when the file is open)
                let from = HOST.with(|h| h.try_borrow_mut().ok().and_then(|mut h| h.as_mut()?.player.as_mut()?.start_at.take()));
                if let Some(secs) = from {
                    use windows::Win32::Media::MediaFoundation::MFP_POSITIONTYPE_100NS;
                    let at = windows::Win32::System::Com::StructuredStorage::PROPVARIANT::from((secs.max(0.0) * 1e7) as i64);
                    unsafe {
                        let _ = mp.SetPosition(&MFP_POSITIONTYPE_100NS, &at);
                    }
                }
                unsafe { mp.Play() }.is_ok()
            };
            let give_up = HOST.with(|h| {
                h.try_borrow_mut().ok().and_then(|mut h| {
                    let p = h.as_mut()?.player.as_mut()?;
                    p.pending_play = p.pending_play.saturating_sub(1);
                    Some(p.pending_play == 0)
                })
            });
            if started || give_up != Some(false) {
                HOST.with(|h| {
                    if let Ok(mut h) = h.try_borrow_mut() {
                        if let Some(p) = h.as_mut().and_then(|x| x.player.as_mut()) {
                            p.pending_play = 0;
                        }
                    }
                });
                unsafe {
                    let _ = KillTimer(Some(hwnd), PLAY_TIMER);
                }
            }
            LRESULT(0)
        }
        WM_SIZE | WM_PAINT => {
            if let Some(mp) = player() {
                unsafe {
                    let _ = mp.UpdateVideo();
                }
            }
            unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
        }
        // clicking the video toggles play / pause, like most players; a double click (two
        // clicks: paused and resumed, or the other way round) is the app's to answer (fullscreen)
        WM_LBUTTONUP => {
            media_toggle();
            LRESULT(0)
        }
        WM_LBUTTONDBLCLK => {
            emit(MediaEvent::DoubleClick);
            LRESULT(0)
        }
        _ => unsafe { DefWindowProcW(hwnd, msg, wp, lp) },
    }
}

/// Automated UI tests set this: a test must never make a sound.
fn muted_for_tests() -> bool {
    std::env::var_os("RUSTYFILES_MUTE").is_some()
}

/// Whether `path` is audio / video our own player tries (Media Foundation decides in the end).
pub fn is_playable(path: &Path) -> bool {
    let ext = path.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
    matches!(
        ext.as_str(),
        "mp4" | "m4v" | "mov" | "mkv" | "webm" | "avi" | "wmv" | "mpg" | "mpeg" | "ts" | "m2ts" | "mts" | "3gp" | "mp3" | "wav" | "m4a" | "aac" | "flac" | "wma" | "ogg" | "opus"
    )
}

/// Whether Windows has a decoder (hardware or software) for `codec` ("hevc", "h264", "av1",
/// "vp9"; FilmCraft's codec names). HEVC and AV1 come from Store extensions that may be
/// missing; an unknown codec answers false.
pub fn mf_decodes(codec: &str) -> bool {
    use windows::Win32::Media::MediaFoundation::{
        IMFActivate, MFMediaType_Video, MFT_CATEGORY_VIDEO_DECODER, MFT_ENUM_FLAG_ASYNCMFT, MFT_ENUM_FLAG_HARDWARE,
        MFT_ENUM_FLAG_SORTANDFILTER, MFT_ENUM_FLAG_SYNCMFT, MFT_REGISTER_TYPE_INFO, MFTEnumEx, MFVideoFormat_AV1,
        MFVideoFormat_H264, MFVideoFormat_HEVC, MFVideoFormat_VP90,
    };
    let c = codec.to_ascii_lowercase();
    let sub = if c.contains("hevc") || c.contains("265") {
        MFVideoFormat_HEVC
    } else if c.contains("h264") || c.contains("avc") || c.contains("264") {
        MFVideoFormat_H264
    } else if c.contains("av1") || c.contains("av01") {
        MFVideoFormat_AV1
    } else if c.contains("vp9") || c.contains("vp09") {
        MFVideoFormat_VP90
    } else {
        return false;
    };
    let input = MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: sub };
    // DirectLook may ask from a worker thread that has no apartment yet (already in one is fine)
    let _ = unsafe { windows::Win32::System::Com::CoInitializeEx(None, windows::Win32::System::Com::COINIT_MULTITHREADED) };
    unsafe {
        let mut list: *mut Option<IMFActivate> = std::ptr::null_mut();
        let mut n = 0u32;
        let flags = MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_ASYNCMFT | MFT_ENUM_FLAG_SORTANDFILTER;
        if MFTEnumEx(MFT_CATEGORY_VIDEO_DECODER, flags, Some(&input), None, &mut list, &mut n).is_err() || list.is_null() {
            return false;
        }
        for i in 0..n as usize {
            drop(std::ptr::read(list.add(i)));
        }
        windows::Win32::System::Com::CoTaskMemFree(Some(list as *const _));
        n > 0
    }
}

type MfpCreate = unsafe extern "system" fn(
    windows::core::PCWSTR,
    windows_core::BOOL,
    windows::Win32::Media::MediaFoundation::MFP_CREATION_OPTIONS,
    *mut core::ffi::c_void,
    HWND,
    *mut *mut core::ffi::c_void,
) -> windows_core::HRESULT;

/// Media Foundation is loaded on the first Play, not at start-up: linking MFPCreateMediaPlayer
/// statically made every launch load mfplay.dll and mfplat.dll. Also runs MFStartup once.
fn mf_create() -> Option<MfpCreate> {
    use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
    use windows::core::s;
    static F: std::sync::OnceLock<Option<MfpCreate>> = std::sync::OnceLock::new();
    *F.get_or_init(|| unsafe {
        let plat = LoadLibraryW(w!("mfplat.dll")).ok()?;
        if let Some(startup) = GetProcAddress(plat, s!("MFStartup")) {
            // SAFETY: MFStartup(ULONG Version, DWORD dwFlags) -> HRESULT
            let startup: unsafe extern "system" fn(u32, u32) -> windows_core::HRESULT = std::mem::transmute(startup);
            let _ = startup(windows::Win32::Media::MediaFoundation::MF_VERSION, windows::Win32::Media::MediaFoundation::MFSTARTUP_FULL);
        }
        let play = LoadLibraryW(w!("mfplay.dll")).ok()?;
        let f = GetProcAddress(play, s!("MFPCreateMediaPlayer"))?;
        // SAFETY: the documented signature (see MfpCreate)
        Some(std::mem::transmute::<unsafe extern "system" fn() -> isize, MfpCreate>(f))
    })
}

/// Plays `path` with our own player; `rect` (screen pixels) shows its video over the pane,
/// `None` plays without a visible window (audio). Re-pressing play on the same file resumes.
/// Call on the shell STA thread.
pub fn media_play(owner: isize, path: &Path, rect: Option<RECT>) {
    media_play_from(owner, path, rect, None)
}

/// [`media_play`] that starts a file that is not open yet at `start` seconds instead of at its beginning (the preview pane's "go
/// on where it was left"). A file that is already open goes on from where it is, whatever `start` says.
pub fn media_play_from(owner: isize, path: &Path, rect: Option<RECT>, start: Option<f64>) {
    use windows::Win32::Media::MediaFoundation::{IMFPMediaPlayer, MFP_OPTION_NONE};
    use windows::Win32::UI::WindowsAndMessaging::SetTimer;
    use windows_core::Interface;
    let Some(hwnd) = ensure_host_window() else { return };
    // a shell preview handler shares the window: detach first, then unload it
    let old = HOST.with(|h| h.borrow_mut().as_mut().and_then(|x| {
        x.path = None;
        x.handler.take()
    }));
    if old.is_some() {
        unsafe { detach_window(hwnd) };
        unload(old);
    }
    let same = HOST.with(|h| h.borrow().as_ref().is_some_and(|x| x.player.as_ref().is_some_and(|p| p.path == path)));
    if !same {
        stop_player();
        let Some(create) = mf_create() else {
            log::info!("media player: Media Foundation unavailable");
            return;
        };
        let w = wide(path);
        let mut raw: *mut core::ffi::c_void = std::ptr::null_mut();
        // SAFETY: the documented MFPCreateMediaPlayer signature; `raw` receives an owned reference
        let hr = unsafe { create(PCWSTR(w.as_ptr()), windows_core::BOOL(0), MFP_OPTION_NONE, std::ptr::null_mut(), hwnd, &mut raw) };
        if hr.is_err() || raw.is_null() {
            log::info!("media player: can't open {} ({hr:?})", path.display());
            return;
        }
        // SAFETY: a non-null IMFPMediaPlayer pointer whose reference we now own
        let mp = unsafe { IMFPMediaPlayer::from_raw(raw) };
        HOST.with(|h| {
            if let Some(x) = h.borrow_mut().as_mut() {
                x.player = Some(Player { path: path.to_path_buf(), mp, pending_play: 0, asked: None, start_at: start });
            }
        });
    }
    match rect {
        Some(r) if is_window_alive(owner) => {
            HOST.with(|h| {
                if let Some(x) = h.borrow_mut().as_mut() {
                    x.owner = owner;
                }
            });
            attach_and_position(hwnd, owner, r);
        }
        _ => {
            HOST.with(|h| {
                if let Some(x) = h.borrow_mut().as_mut() {
                    x.owner = 0;
                }
            });
            unsafe { detach_window(hwnd) };
        }
    }
    // ~6 s for the file to open; the timer plays it as soon as it can
    HOST.with(|h| {
        if let Some(p) = h.borrow_mut().as_mut().and_then(|x| x.player.as_mut()) {
            p.pending_play = 200;
            p.asked = Some((true, std::time::Instant::now()));
        }
    });
    unsafe {
        let _ = SetTimer(Some(hwnd), PLAY_TIMER, 30, None);
    }
}

fn current_player() -> Option<windows::Win32::Media::MediaFoundation::IMFPMediaPlayer> {
    HOST.with(|h| h.try_borrow().ok().and_then(|h| h.as_ref().and_then(|x| x.player.as_ref().map(|p| p.mp.clone()))))
}

/// Whether the player plays, as far as the user is concerned: a play still waiting for the file
/// to open counts, and for a moment after a play / pause what was asked does (see `Player::asked`).
fn playing_now(mp: &windows::Win32::Media::MediaFoundation::IMFPMediaPlayer) -> bool {
    use windows::Win32::Media::MediaFoundation::MFP_MEDIAPLAYER_STATE_PLAYING;
    let (pending, asked) =
        HOST.with(|h| h.try_borrow().ok().and_then(|h| h.as_ref().and_then(|x| x.player.as_ref().map(|p| (p.pending_play > 0, p.asked))))).unwrap_or((false, None));
    match asked {
        Some((want, at)) if at.elapsed() < ASKED_HOLDS => want,
        _ => pending || unsafe { mp.GetState() }.is_ok_and(|s| s == MFP_MEDIAPLAYER_STATE_PLAYING),
    }
}

/// Plays (`Some(true)`), pauses (`Some(false)`) or toggles (`None`) and returns whether the
/// player now plays; `None` without a player. The one place play / pause is decided, on the
/// thread that owns the player: the app's button and a click on the picture both end here, so
/// neither works from a stale copy of the state. The video window is left as it is.
fn set_playing(want: Option<bool>) -> Option<bool> {
    use windows::Win32::UI::WindowsAndMessaging::{KillTimer, SetTimer};
    let mp = current_player()?;
    let play = want.unwrap_or_else(|| !playing_now(&mp));
    let ready = unsafe { mp.GetMediaItem() }.is_ok();
    // (never call the player while HOST is borrowed: its calls can re-enter the window procedure)
    let hwnd = HOST.with(|h| {
        let mut h = h.try_borrow_mut().ok()?;
        let x = h.as_mut()?;
        let p = x.player.as_mut()?;
        p.asked = Some((play, std::time::Instant::now()));
        // a pause also calls off a play still waiting for the file to open (the timer would
        // start it a moment later and the pause would be lost); a play before the file is open
        // waits for it the same way the first one does
        p.pending_play = if play && !ready { 200 } else { 0 };
        Some(x.hwnd)
    })?;
    unsafe {
        if play && ready {
            if muted_for_tests() {
                let _ = mp.SetMute(true);
            }
            let _ = mp.Play();
        } else if play {
            let _ = SetTimer(Some(hwnd), PLAY_TIMER, 30, None);
        } else {
            let _ = KillTimer(Some(hwnd), PLAY_TIMER);
            let _ = mp.Pause();
        }
    }
    emit(MediaEvent::Playing(play));
    Some(play)
}

/// Pauses our player. STA thread.
pub fn media_pause() {
    set_playing(Some(false));
}

/// Plays if paused, pauses if playing; returns whether it now plays. STA thread.
pub fn media_toggle() -> Option<bool> {
    set_playing(None)
}

/// Jumps to `fraction` (0..1) of the length. STA thread.
pub fn media_seek(fraction: f64) {
    use windows::Win32::Media::MediaFoundation::MFP_POSITIONTYPE_100NS;
    let Some(mp) = current_player() else { return };
    unsafe {
        let Ok(d) = mp.GetDuration(&MFP_POSITIONTYPE_100NS) else { return };
        let Ok(total) = i64::try_from(&d) else { return };
        let at = windows::Win32::System::Com::StructuredStorage::PROPVARIANT::from((total as f64 * fraction.clamp(0.0, 1.0)) as i64);
        let _ = mp.SetPosition(&MFP_POSITIONTYPE_100NS, &at);
    }
}

/// Playback state for the controls.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MediaState {
    pub playing: bool,
    /// Seconds.
    pub position: f64,
    pub duration: f64,
}

/// The player's state, `None` without a player. STA thread.
pub fn media_state() -> Option<MediaState> {
    use windows::Win32::Media::MediaFoundation::MFP_POSITIONTYPE_100NS;
    let mp = current_player()?;
    unsafe {
        let secs = |v: windows::core::Result<windows::Win32::System::Com::StructuredStorage::PROPVARIANT>| v.ok().and_then(|v| i64::try_from(&v).ok()).map_or(0.0, |t| t as f64 / 1e7);
        Some(MediaState {
            // a play that is about to start counts as playing (the button doesn't flicker)
            playing: playing_now(&mp),
            position: secs(mp.GetPosition(&MFP_POSITIONTYPE_100NS)),
            duration: secs(mp.GetDuration(&MFP_POSITIONTYPE_100NS)),
        })
    }
}

/// Moves the player's video (pane resized / window moved). Preview STA thread.
pub fn media_reposition(rect: RECT) {
    let target = HOST.with(|h| h.borrow().as_ref().filter(|x| x.player.is_some() && x.owner != 0).map(|x| (x.hwnd, x.owner)));
    if let Some((hwnd, owner)) = target {
        attach_and_position(hwnd, owner, rect);
        if let Some(mp) = current_player() {
            unsafe {
                let _ = mp.UpdateVideo();
            }
        }
    }
}

/// Stops and releases our player (the file is closed).
fn stop_player() {
    let p = HOST.with(|h| h.borrow_mut().as_mut().and_then(|x| x.player.take()));
    if let Some(p) = p {
        unsafe {
            let _ = p.mp.Shutdown();
        }
    }
}

fn is_window_alive(hwnd: isize) -> bool {
    use windows::Win32::UI::WindowsAndMessaging::IsWindow;
    hwnd != 0 && unsafe { IsWindow(Some(HWND(hwnd as *mut _))).as_bool() }
}

/// Hides `hwnd` asynchronously and clears its cross-thread owner without synchronously waiting on
/// either thread's message queue (issues 146 and 471).
unsafe fn detach_window(hwnd: HWND) {
    use windows::Win32::UI::WindowsAndMessaging::{GWLP_HWNDPARENT, SetWindowLongPtrW};
    unsafe {
        let _ = ShowWindowAsync(hwnd, SW_HIDE);
        SetWindowLongPtrW(hwnd, GWLP_HWNDPARENT, 0);
    }
    SHOWN_OWNER.store(0, Ordering::SeqCst);
}

/// Ensures the preview STA's host popup exists, always created unowned and hidden so creation
/// never synchronizes with the UI thread. Ownership is attached only after a preview finishes
/// loading (issue 471).
fn ensure_host_window() -> Option<HWND> {
    HOST.with(|h| {
        let mut h = h.borrow_mut();
        if let Some(host) = h.as_ref() {
            return Some(host.hwnd);
        }
        unsafe {
            let inst = GetModuleHandleW(None).ok()?;
            let class = w!("rustyfiles-preview-host");
            // CS_DBLCLKS: the picture's double click arrives as one (see WM_LBUTTONDBLCLK)
            let wc = WNDCLASSW {
                style: windows::Win32::UI::WindowsAndMessaging::CS_DBLCLKS,
                lpfnWndProc: Some(wndproc),
                hInstance: inst.into(),
                lpszClassName: class,
                ..Default::default()
            };
            RegisterClassW(&wc);
            let hwnd = CreateWindowExW(
                WINDOW_EX_STYLE(WS_EX_TOOLWINDOW.0 | WS_EX_NOACTIVATE.0),
                class,
                w!(""),
                WS_POPUP | WS_CLIPCHILDREN,
                0,
                0,
                10,
                10,
                None,
                None,
                Some(inst.into()),
                None,
            )
            .ok()?;
            // a playing video or a document in this popup lies over the glass window: while there is glass it must not be captured and
            // bent into it (and a video would keep the glass redrawing at its frame rate)
            crate::glass::exclude_from_capture(hwnd.0 as isize, true);
            *h = Some(Host { hwnd, owner: 0, path: None, handler: None, player: None });
            SHOWN.store(hwnd.0 as isize, Ordering::SeqCst);
            SHOWN_OWNER.store(0, Ordering::SeqCst);
            Some(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,
    pub text: u32,
}

/// Starts a new preview generation for `owner` on the UI thread; pass the returned token to
/// [`show_gen`] on `crate::sta::run_preview` so a subsequent hide, switch, or window close cancels
/// an in-flight load before it attaches to `owner`.
pub fn begin_show(owner: isize) -> u64 {
    PENDING_OWNER.store(owner, Ordering::SeqCst);
    GEN.fetch_add(1, Ordering::SeqCst).wrapping_add(1)
}

/// Shows `path` over `rect` (screen pixels). Returns false if no handler could preview it.
/// Call on the preview STA thread.
pub fn show(owner: isize, path: &Path, rect: RECT, colors: &Colors) -> bool {
    let epoch = GEN.load(Ordering::SeqCst);
    show_gen(epoch, owner, path, rect, colors)
}

/// 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) || stopped_answering(path) {
        return false;
    }
    let Some(hwnd) = ensure_host_window() else { return false };
    stop_player();
    let same = HOST.with(|h| h.borrow().as_ref().is_some_and(|x| x.owner == owner && x.path.as_deref() == Some(path) && x.handler.is_some()));
    if same {
        attach_and_position(hwnd, owner, rect);
        HOST.with(|h| {
            if let Some(ph) = h.borrow().as_ref().and_then(|x| x.handler.clone()) {
                let r = client_rect(rect);
                unsafe {
                    let _ = ph.SetRect(&r);
                }
            }
        });
        return true;
    }
    // Detach from the UI window and hide BEFORE unloading the old handler or loading the new one:
    // while `hwnd` has no owner, slow COM/PDF preview teardown or initialization can never form a
    // cross-thread Win32 wait chain with the UI thread (issue 471).
    unsafe { detach_window(hwnd) };
    let old = HOST.with(|h| h.borrow_mut().as_mut().and_then(|x| {
        x.owner = 0;
        x.path = None;
        x.handler.take()
    }));
    unload(old);
    if GEN.load(Ordering::SeqCst) != epoch || !is_window_alive(owner) {
        return false;
    }
    // Size the hidden, unowned host to the target dimensions before SetWindow/DoPreview so the
    // handler lays out its initial view at the right client rect without being visible or owned.
    position_hidden(hwnd, rect);
    let Some(ph) = load(hwnd, path, rect, colors) else {
        return false;
    };
    if GEN.load(Ordering::SeqCst) != epoch || !is_window_alive(owner) {
        unload(Some(ph));
        return false;
    }
    HOST.with(|h| {
        if let Some(x) = h.borrow_mut().as_mut() {
            x.owner = owner;
            x.path = Some(path.to_path_buf());
            x.handler = Some(ph.clone());
        }
    });
    attach_and_position(hwnd, owner, rect);
    let r = client_rect(rect);
    unsafe {
        let _ = ph.SetRect(&r);
    }
    watch_shown(epoch, hwnd, ph.as_raw() as usize, path);
    true
}

fn client_rect(rect: RECT) -> RECT {
    RECT { left: 0, top: 0, right: (rect.right - rect.left).max(1), bottom: (rect.bottom - rect.top).max(1) }
}

/// Sizes and moves `hwnd` while it remains hidden and unowned.
fn position_hidden(hwnd: HWND, rect: RECT) {
    let w = (rect.right - rect.left).max(1);
    let h = (rect.bottom - rect.top).max(1);
    unsafe {
        let _ = SetWindowPos(hwnd, None, rect.left, rect.top, w, h, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);
    }
}

/// Attaches `hwnd` to `owner` (if not already attached), places it over `rect` directly above
/// `owner`, and shows it WITHOUT raising `owner` or jumping above another app that has since come
/// to the front (issues 75 and 471). A window already attached and shown at `rect` is left alone.
fn attach_and_position(hwnd: HWND, owner: isize, rect: RECT) {
    use windows::Win32::UI::WindowsAndMessaging::{
        GW_HWNDPREV, GWL_EXSTYLE, GWLP_HWNDPARENT, GetWindow, GetWindowLongPtrW, GetWindowRect,
        HWND_TOP, HWND_TOPMOST, IsWindowVisible, SetWindowLongPtrW, WS_EX_TOPMOST,
    };
    let w = (rect.right - rect.left).max(1);
    let h = (rect.bottom - rect.top).max(1);
    let already_owned = SHOWN_OWNER.load(Ordering::SeqCst) == owner;
    unsafe {
        let mut now = RECT::default();
        if already_owned
            && IsWindowVisible(hwnd).as_bool()
            && GetWindowRect(hwnd, &mut now).is_ok()
            && (now.left, now.top, now.right - now.left, now.bottom - now.top) == (rect.left, rect.top, w, h)
        {
            return;
        }
        if !already_owned {
            SetWindowLongPtrW(hwnd, GWLP_HWNDPARENT, owner);
            SHOWN_OWNER.store(owner, Ordering::SeqCst);
        }
        let mut flags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_SHOWWINDOW | SWP_ASYNCWINDOWPOS;
        let insert_after = if already_owned && IsWindowVisible(hwnd).as_bool() {
            flags |= SWP_NOZORDER;
            None
        } else {
            let owner_hwnd = HWND(owner as *mut _);
            let owner_topmost = GetWindowLongPtrW(owner_hwnd, GWL_EXSTYLE) as u32 & WS_EX_TOPMOST.0 != 0;
            let above = GetWindow(owner_hwnd, GW_HWNDPREV).ok().filter(|p| !p.0.is_null());
            match above {
                Some(p) if p == hwnd => {
                    flags |= SWP_NOZORDER;
                    None
                }
                // Behind a topmost window would promote a non-topmost host to topmost; a topmost
                // window above an ordinary owner means the owner is already the top ordinary window.
                Some(p) if owner_topmost || (GetWindowLongPtrW(p, GWL_EXSTYLE) as u32 & WS_EX_TOPMOST.0 == 0) => Some(p),
                _ => Some(if owner_topmost { HWND_TOPMOST } else { HWND_TOP }),
            }
        };
        let _ = SetWindowPos(hwnd, insert_after, rect.left, rect.top, w, h, flags);
    }
}

/// Instantiates a preview handler, preferring its out-of-process `prevhost.exe` COM surrogate
/// (`CLSCTX_LOCAL_SERVER`) over in-process activation (`CLSCTX_INPROC_SERVER`).
///
/// WHY (issue 471): Windows' built-in Microsoft Edge PDF preview handler registers both
/// `InProcServer32` (`PdfPreviewHandler.dll`, WebView2) and an AppID surrogate (`prevhost.exe`).
/// Asking for `CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER` caused COM to prefer in-process
/// loading on our STA thread, where WebView2's child HWND and synchronous Win32 calls deadlocked
/// against the main UI window (`EventID 1002, HangType: Cross-thread`). Explorer isolates preview
/// handlers in `prevhost.exe` by activating `CLSCTX_LOCAL_SERVER` first.
unsafe fn create_handler(clsid: &GUID) -> Option<IPreviewHandler> {
    unsafe {
        CoCreateInstance(clsid, None, CLSCTX_LOCAL_SERVER)
            .or_else(|_| CoCreateInstance(clsid, None, CLSCTX_INPROC_SERVER))
            .ok()
    }
}

fn load(hwnd: HWND, path: &Path, rect: RECT, colors: &Colors) -> Option<IPreviewHandler> {
    let clsid = handler_for(path)?;
    unsafe {
        let ph = create_handler(&clsid)?;
        let wpath = wide(path);
        let mut ok = false;
        if let Ok(init) = ph.cast::<IInitializeWithItem>() {
            if let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wpath.as_ptr()), None) {
                ok = init.Initialize(&item, STGM_READ.0).is_ok();
            }
        }
        if !ok {
            if let Ok(init) = ph.cast::<IInitializeWithFile>() {
                ok = init.Initialize(PCWSTR(wpath.as_ptr()), STGM_READ.0).is_ok();
            }
        }
        if !ok {
            if let Ok(init) = ph.cast::<IInitializeWithStream>() {
                if let Ok(stream) = SHCreateStreamOnFileEx(PCWSTR(wpath.as_ptr()), (STGM_READ | STGM_SHARE_DENY_NONE).0, 0, false, None) {
                    ok = init.Initialize(&stream, STGM_READ.0).is_ok();
                }
            }
        }
        if !ok {
            return None;
        }
        if let Ok(vis) = ph.cast::<IPreviewHandlerVisuals>() {
            let _ = vis.SetBackgroundColor(COLORREF(bgr(colors.background)));
            let _ = vis.SetTextColor(COLORREF(bgr(colors.text)));
        }
        let r = client_rect(rect);
        ph.SetWindow(hwnd, &r).ok()?;
        ph.DoPreview().ok()?;
        Some(ph)
    }
}

/// 0xRRGGBB → COLORREF 0x00BBGGRR
fn bgr(c: u32) -> u32 {
    ((c & 0xFF) << 16) | (c & 0xFF00) | ((c >> 16) & 0xFF)
}

/// Hides the host and unloads the handler (frees the document). Call on the preview STA thread.
pub fn hide() {
    stop_player();
    let (hwnd, handler) = HOST.with(|h| match h.borrow_mut().as_mut() {
        Some(x) => {
            x.owner = 0;
            x.path = None;
            (Some(x.hwnd), x.handler.take())
        }
        None => (None, None),
    });
    if let Some(hwnd) = hwnd {
        unsafe { detach_window(hwnd) };
    }
    unload(handler);
}

/// The host window, its currently attached owner, and the latest owner with a pending show —
/// readable from any thread (the host itself lives on the preview STA thread). 0: none.
static SHOWN: AtomicIsize = AtomicIsize::new(0);
static SHOWN_OWNER: AtomicIsize = AtomicIsize::new(0);
static PENDING_OWNER: AtomicIsize = AtomicIsize::new(0);
/// Monotonic generation counter bumped on show/hide/detach so stale in-flight loads abort.
static GEN: AtomicU64 = AtomicU64::new(0);

/// Immediately cancels any in-flight preview load and detaches/hides the host window from the UI
/// thread without waiting on the preview STA thread. Call before queuing [`hide`] on
/// `crate::sta::run_preview`.
pub fn detach_for_hide() {
    GEN.fetch_add(1, Ordering::SeqCst);
    PENDING_OWNER.store(0, Ordering::SeqCst);
    let host = SHOWN.load(Ordering::SeqCst);
    if host != 0 {
        unsafe { detach_window(HWND(host as *mut _)) };
    }
}

/// The app window `owner` is about to close. Call on ITS thread, before it is destroyed.
///
/// WHY (issue 146: an app's Open dialog, a PDF previewed in it, "after opening the preview window stays. I have to quit the program
/// to close it"; issue 471: cross-thread hang with PDF preview). The host is owned by the app window but lives on the preview STA
/// thread. Destroying an owner destroys its owned windows, and for one of another thread Windows asks that thread and WAITS: while
/// the STA thread was busy in the PDF preview handler, the app window's thread hung inside its own DestroyWindow. So the host is
/// detached and hidden asynchronously first (and any in-flight load for `owner` is cancelled via `GEN`), and the preview STA thread
/// unloads the handler and destroys it when it gets to it.
pub fn detach_from(owner: isize) {
    let attached = SHOWN_OWNER.load(Ordering::SeqCst);
    let pending = PENDING_OWNER.load(Ordering::SeqCst);
    if attached != owner && pending != owner {
        return;
    }
    GEN.fetch_add(1, Ordering::SeqCst);
    let _ = PENDING_OWNER.compare_exchange(owner, 0, Ordering::SeqCst, Ordering::SeqCst);
    let host = SHOWN.load(Ordering::SeqCst);
    if host != 0 && attached == owner {
        unsafe { detach_window(HWND(host as *mut _)) };
    }
    crate::sta::run_preview(move |_| owner_closed(owner));
}

/// The app window `owner` is gone: if the host is its, the handler is unloaded and the host window destroyed. Call on the preview STA
/// thread. (The host is owned by the app window but lives on this thread, and Windows does not destroy an owned window of another
/// thread with its owner: a file picker's PDF preview stayed on the screen after the picker closed, issue 146.)
pub fn owner_closed(owner: isize) {
    let old = HOST.with(|h| {
        let mut h = h.borrow_mut();
        if h.as_ref().is_some_and(|x| x.owner == owner) { h.take() } else { None }
    });
    let Some(old) = old else { return };
    unsafe { detach_window(old.hwnd) };
    unload(old.handler);
    if let Some(p) = old.player {
        unsafe {
            let _ = p.mp.Shutdown();
        }
    }
    crate::glass::exclude_from_capture(old.hwnd.0 as isize, false);
    let _ = SHOWN.compare_exchange(old.hwnd.0 as isize, 0, Ordering::SeqCst, Ordering::SeqCst);
    unsafe {
        let _ = windows::Win32::UI::WindowsAndMessaging::DestroyWindow(old.hwnd);
    }
}

/// Moves the visible host (window moved / pane resized) without reloading.
pub fn reposition(rect: RECT) {
    HOST.with(|h| {
        if let Some(x) = h.borrow().as_ref() {
            if x.handler.is_some() && x.owner != 0 {
                attach_and_position(x.hwnd, x.owner, rect);
                if let Some(ph) = &x.handler {
                    unsafe {
                        let _ = ph.SetRect(&client_rect(rect));
                    }
                }
            }
        }
    });
}

#[cfg(test)]
mod mf_tests {
    use super::*;

    /// Serializes tests that touch the process-global preview host state (`GEN`, `SHOWN`, `SHOWN_OWNER`).
    static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn h264_has_a_decoder_and_unknown_codecs_dont() {
        // Windows always ships an H.264 decoder
        assert!(super::mf_decodes("h264"));
        assert!(!super::mf_decodes("prores"));
        // HEVC comes from a Store extension: print, don't assert
        eprintln!("hevc decoder: {}", super::mf_decodes("hevc"));
    }

    #[test]
    fn detach_for_hide_advances_generation_so_stale_show_is_skipped() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let epoch = begin_show(0x1234);
        detach_for_hide();
        assert_ne!(GEN.load(Ordering::SeqCst), epoch);
        // Stale generation exits immediately without requiring a real HWND or handler
        assert!(!show_gen(epoch, 0x1234, Path::new(r"C:\nonexistent.pdf"), RECT { left: 0, top: 0, right: 100, bottom: 100 }, &Colors { background: 0, text: 0 }));
    }

    #[test]
    fn pdf_preview_isolates_out_of_process_and_detaches_cleanly_across_threads() {
        use std::time::Duration;
        use windows::Win32::UI::WindowsAndMessaging::{
            CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetWindow, GetWindowThreadProcessId,
            GW_CHILD, GW_OWNER, MSG, PM_REMOVE, PeekMessageW, RegisterClassW, TranslateMessage, WINDOW_EX_STYLE,
            WNDCLASSW, WS_OVERLAPPEDWINDOW,
        };

        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let pdf_path = std::env::temp_dir().join(format!("rf-preview-test-{}.pdf", std::process::id()));
        let tiny_pdf = b"%PDF-1.4\n1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>endobj\nxref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n0000000115 00000 n \ntrailer<< /Size 4 /Root 1 0 R >>\nstartxref\n190\n%%EOF\n";
        std::fs::write(&pdf_path, tiny_pdf).unwrap();

        let Some(clsid) = handler_for(&pdf_path) else {
            let _ = std::fs::remove_file(&pdf_path);
            return;
        };
        let edge_pdf_clsid = GUID::try_from("3A84F9C2-6164-485C-A7D9-4B27F8AC009E").unwrap();

        unsafe extern "system" fn test_wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
            unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
        }
        // Create a real owner window on this thread (simulating the UI thread)
        let owner_hwnd = unsafe {
            let inst = GetModuleHandleW(None).unwrap();
            let class = w!("rustyfiles-preview-test-owner");
            let wc = WNDCLASSW { lpfnWndProc: Some(test_wndproc), hInstance: inst.into(), lpszClassName: class, ..Default::default() };
            RegisterClassW(&wc);
            CreateWindowExW(WINDOW_EX_STYLE(0), class, w!(""), WS_OVERLAPPEDWINDOW, 40, 40, 400, 300, None, None, Some(inst.into()), None).unwrap()
        };
        let owner = owner_hwnd.0 as isize;
        let epoch = begin_show(owner);
        let path_for_sta = pdf_path.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        crate::sta::run_preview(move |_| {
            let ok = show_gen(epoch, owner, &path_for_sta, RECT { left: 60, top: 60, right: 320, bottom: 260 }, &Colors { background: 0xFFFFFF, text: 0x000000 });
            let host = SHOWN.load(Ordering::SeqCst);
            let child_pid = if host != 0 {
                unsafe {
                    GetWindow(HWND(host as *mut _), GW_CHILD).ok().filter(|c| !c.0.is_null()).map(|c| {
                        let mut pid = 0u32;
                        GetWindowThreadProcessId(c, Some(&mut pid));
                        pid
                    })
                }
            } else {
                None
            };
            let _ = tx.send((ok, host, child_pid));
        });

        // Pump messages on the owner thread while preview_host loads on rf-preview-sta
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        let (ok, host, child_pid) = loop {
            if let Ok(res) = rx.try_recv() {
                break res;
            }
            assert!(std::time::Instant::now() < deadline, "PDF preview hung across threads");
            unsafe {
                let mut msg = MSG::default();
                while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
                    let _ = TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }
            }
            std::thread::sleep(Duration::from_millis(10));
        };

        if ok {
            assert_ne!(host, 0);
            let actual_owner = unsafe { GetWindow(HWND(host as *mut _), GW_OWNER).map(|h| h.0 as isize).unwrap_or(0) };
            assert_eq!(actual_owner, owner, "host attaches to owner once loaded");
            // Edge's surrogated PDF handler must run its child HWND out-of-process in prevhost.exe
            if clsid == edge_pdf_clsid
                && let Some(pid) = child_pid
            {
                assert_ne!(pid, std::process::id(), "Edge PDF preview handler should run out-of-process in prevhost.exe");
            }
        }

        // Detach and destroy the owner window without blocking on rf-preview-sta
        detach_from(owner);
        if host != 0 {
            let detached_owner = unsafe { GetWindow(HWND(host as *mut _), GW_OWNER).map(|h| h.0 as isize).unwrap_or(0) };
            assert_eq!(detached_owner, 0, "detach_from clears owner immediately");
        }
        unsafe {
            let _ = DestroyWindow(owner_hwnd);
        }
        // Wait for owner_closed cleanup on rf-preview-sta so the temp PDF can be removed
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        crate::sta::run_preview(move |_| {
            let _ = done_tx.send(());
        });
        done_rx.recv_timeout(Duration::from_secs(10)).expect("preview STA finished teardown cleanly");
        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");
    }
}