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.

67.6 KB
Raw Blame
//! rustyfiles as the Open / Save dialog. This DLL is registered (per user, HKCU) as the COM
//! server of Windows' FileOpenDialog and FileSaveDialog classes, so apps that ask Windows for
//! the common file dialog load it.
//!
//! Each object wraps Windows' real dialog (taken straight from comdlg32.dll, whatever the
//! registry says): every call the app makes is recorded and passed on to it. `Show` asks
//! rustyfiles (see `ipc`); if the app added its own controls to the dialog, or rustyfiles
//! can't be reached, the real dialog is shown instead, already set up exactly as the app asked.

#![allow(non_snake_case)]

pub mod proto;
#[cfg(windows)]
// (in tests the picker is answered in place, see `com::tests`)
#[cfg_attr(test, allow(dead_code))]
mod ipc;

/// One line to `%LOCALAPPDATA%/rustyfiles/dialog.log` (kept under 256 KB): which app asked,
/// whether rustyfiles answered, and how the app read the result. For diagnosing apps.
pub(crate) fn log(line: &str) {
    use std::io::Write;
    let Some(base) = std::env::var_os("LOCALAPPDATA") else { return };
    let dir = std::path::PathBuf::from(base).join("rustyfiles");
    let path = dir.join("dialog.log");
    if std::fs::metadata(&path).is_ok_and(|m| m.len() > 256 << 10) {
        let _ = std::fs::remove_file(&path);
    }
    let _ = std::fs::create_dir_all(&dir);
    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
        let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
        let app = std::env::current_exe().ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default();
        let _ = writeln!(f, "{secs} {app}[{}] dll {}-{} {line}", std::process::id(), env!("CARGO_PKG_VERSION"), env!("RUSTYFILES_COMMIT"));
    }
}

#[cfg(windows)]
pub use com::*;

#[cfg(windows)]
mod com {
    use std::cell::RefCell;
    use std::ffi::c_void;

    use windows::Win32::Foundation::{CLASS_E_CLASSNOTAVAILABLE, CLASS_E_NOAGGREGATION, E_FAIL, E_NOINTERFACE, E_POINTER, ERROR_CANCELLED, HWND, S_FALSE, S_OK};
    use windows::Win32::System::Com::{CoTaskMemAlloc, CoTaskMemFree, IClassFactory, IClassFactory_Impl};
    use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW};
    use windows::Win32::UI::Input::KeyboardAndMouse::EnableWindow;
    use windows::Win32::UI::Shell::Common::{COMDLG_FILTERSPEC, ITEMIDLIST};
    use windows::Win32::UI::Shell::PropertiesSystem::{IPropertyDescriptionList, IPropertyStore};
    use windows::Win32::UI::Shell::*;
    use windows::Win32::System::Ole::IOleWindow;
    use windows::Win32::UI::WindowsAndMessaging::SetForegroundWindow;
    use windows::core::{GUID, HRESULT, IUnknown, Interface, PCWSTR, PWSTR, Ref, Result, implement, w};
    use windows_core::{BOOL as WBOOL, IUnknownImpl as _};

    use crate::proto::{Filter, Mode, Request};

    /// How long to wait before offering a pick to the app again after its OnFileOk said S_FALSE: Firefox's input protection waits
    /// `security.notification_enable_delay`, 500 ms out of the box, after the first folder.
    const SECOND_OFFER_MS: u64 = 700;

    type DllGetClassObjectFn = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT;

    /// comdlg32.dll's own `DllGetClassObject` (our HKCU registration would otherwise point CoCreateInstance back at us).
    fn comdlg32_class_object() -> Result<DllGetClassObjectFn> {
        unsafe {
            let lib = LoadLibraryW(w!("comdlg32.dll"))?;
            let f = GetProcAddress(lib, windows::core::s!("DllGetClassObject")).ok_or_else(|| windows::core::Error::from(E_FAIL))?;
            Ok(std::mem::transmute::<unsafe extern "system" fn() -> isize, DllGetClassObjectFn>(f))
        }
    }

    /// Windows' own dialog class, from comdlg32.dll directly.
    fn real_dialog(clsid: &GUID) -> Result<IFileDialog> {
        unsafe {
            let f = comdlg32_class_object()?;
            let mut factory: *mut c_void = std::ptr::null_mut();
            f(clsid, &IClassFactory::IID, &mut factory).ok()?;
            let factory = IClassFactory::from_raw(factory);
            factory.CreateInstance::<Option<&IUnknown>, IFileDialog>(None)
        }
    }

    fn wstr(p: &PCWSTR) -> String {
        if p.is_null() { String::new() } else { unsafe { p.to_string().unwrap_or_default() } }
    }

    fn co_string(s: &str) -> Result<PWSTR> {
        let w: Vec<u16> = s.encode_utf16().chain(std::iter::once(0)).collect();
        unsafe {
            let p = CoTaskMemAlloc(w.len() * 2) as *mut u16;
            if p.is_null() {
                return Err(E_FAIL.into());
            }
            std::ptr::copy_nonoverlapping(w.as_ptr(), p, w.len());
            Ok(PWSTR(p))
        }
    }

    fn item_path(item: &IShellItem) -> Option<String> {
        unsafe {
            let p = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
            let s = p.to_string().ok();
            CoTaskMemFree(Some(p.0 as *const c_void));
            s
        }
    }

    /// A shell item for a path; a file being saved may not exist yet. Such a file is parsed with
    /// a bind context in create mode, as Windows' own Save dialog does: the item is a real file
    /// system item (windows::Win32::System::SystemServices::SFGAO_FILESYSTEM), which print drivers check ("Microsoft Print to PDF" fell
    /// back to its own "Print to file" prompt with the bare ID list made below).
    fn item_for(path: &str) -> Result<IShellItem> {
        let wide: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
        unsafe {
            if let Ok(i) = SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wide.as_ptr()), None) {
                return Ok(i);
            }
            if let Ok(bc) = windows::Win32::System::Com::CreateBindCtx(0) {
                let opts = windows::Win32::System::Com::BIND_OPTS {
                    cbStruct: std::mem::size_of::<windows::Win32::System::Com::BIND_OPTS>() as u32,
                    grfFlags: 0,
                    grfMode: windows::Win32::System::Com::STGM_CREATE.0,
                    dwTickCountDeadline: 0,
                };
                if bc.SetBindOptions(&opts).is_ok() {
                    if let Ok(i) = SHCreateItemFromParsingName::<_, _, IShellItem>(PCWSTR(wide.as_ptr()), &bc) {
                        return Ok(i);
                    }
                }
            }
            let pidl = SHSimpleIDListFromPath(PCWSTR(wide.as_ptr()));
            if pidl.is_null() {
                return Err(E_FAIL.into());
            }
            let r = SHCreateItemFromIDList::<IShellItem>(pidl);
            CoTaskMemFree(Some(pidl as *const c_void));
            r
        }
    }

    /// The picked paths as an item array, each item made as [`item_for`] makes one: a real item of the file system.
    ///
    /// WHY (issue 1107: Free Download Manager, a Qt 6 app, took no folder from rustyfiles' picker: "dialog.log: GetResults -> ok",
    /// and the path box kept the old folder). The array was made of bare ID lists (`SHSimpleIDListFromPath`), which carry no
    /// attributes: Qt's dialog code asks each item whether it is a file system item (SFGAO_FILESYSTEM) before it reads its path, got
    /// no, and read nothing. Windows' own dialog gives real items, as `GetResult` here already did (print drivers check the same).
    fn items_for(paths: &[String]) -> Result<IShellItemArray> {
        let mut pidls: Vec<*mut ITEMIDLIST> = Vec::new();
        for p in paths {
            // (the item's own ID list; a bare one only where the item cannot be made)
            let pidl = item_for(p).ok().and_then(|i| unsafe { SHGetIDListFromObject(&i) }.ok()).unwrap_or_else(|| {
                let wide: Vec<u16> = p.encode_utf16().chain(std::iter::once(0)).collect();
                unsafe { SHSimpleIDListFromPath(PCWSTR(wide.as_ptr())) }
            });
            if !pidl.is_null() {
                pidls.push(pidl);
            }
        }
        let consts: Vec<*const ITEMIDLIST> = pidls.iter().map(|p| *p as *const _).collect();
        let r = unsafe { SHCreateShellItemArrayFromIDLists(&consts) };
        for p in pidls {
            unsafe { CoTaskMemFree(Some(p as *const c_void)) };
        }
        r
    }

    /// RF_DIALOG_TRACE=1: every call the app makes, to dialog.log (diagnosing an app).
    fn trace(call: &str) {
        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        if *ON.get_or_init(|| std::env::var_os("RF_DIALOG_TRACE").is_some()) {
            crate::log(&format!("call {call}"));
        }
    }

    fn exe_name() -> String {
        std::env::current_exe().ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default()
    }

    #[derive(Default)]
    struct State {
        options: FILEOPENDIALOGOPTIONS,
        title: String,
        ok_label: String,
        filters: Vec<Filter>,
        type_index: u32,
        default_ext: String,
        folder: Option<String>,
        default_folder: Option<String>,
        file_name: String,
        /// The app added its own controls: only the real dialog can show them.
        customized: bool,
        sinks: Vec<(u32, IFileDialogEvents)>,
        /// The properties the app gave with SetProperties (a save dialog hands them back).
        properties: Option<IPropertyStore>,
        /// Picked in rustyfiles (None: not shown by us, the real dialog has the answer).
        result: Option<Vec<String>>,
        /// While the app's event sinks are asked what they do with a selection (`folder_label`): the path that is "selected".
        probe: Option<String>,
        /// While `Show` runs: the window that owns it, which is what the dialog's window is as far as the app can tell (`IOleWindow`).
        showing_owner: Option<isize>,
    }

    // not agile: Windows' dialog answers no to IAgileObject and IMarshal, so apps in another apartment get COM's proxy as they do with it
    #[implement(IFileOpenDialog, IFileSaveDialog, IFileDialog2, IFileDialogCustomize, IOleWindow, windows::Win32::System::Ole::IObjectWithSite, Agile = false)]
    pub struct Dialog {
        save: bool,
        real: IFileDialog,
        st: RefCell<State>,
    }

    impl Dialog {
        /// The paths picked, copied out: the state's borrow is over before a Shell call made with them.
        ///
        /// WHY (issue 1126, a private review: "GetResult, GetResults, GetSelectedItems, GetFolder, and GetCurrentSelection hold
        /// self.st.borrow() across Shell/COM item_for/items_for calls"). A borrow taken in an `if let` lives through its whole
        /// block. A Shell call made there can come back into this dialog (a Shell extension, the app's own event sink), and a
        /// `borrow_mut` then panics, inside the app that asked for the dialog.
        fn picked(&self) -> Option<Vec<String>> {
            self.st.borrow().result.clone()
        }

        fn first_picked(&self) -> Option<String> {
            self.st.borrow().result.as_ref().and_then(|r| r.first().cloned())
        }
    }

    /// Windows' dialog is told to forget the relays this wrapper gave it before the wrapper goes (issue 1126: a relay holds the
    /// wrapper's address without a count, see `Relay`; Windows' dialog could outlive the wrapper while a caller still holds it and
    /// call a relay that points at freed memory). Each app sink still advised is unadvised here.
    impl Drop for Dialog {
        fn drop(&mut self) {
            let cookies: Vec<u32> = self.st.get_mut().sinks.drain(..).map(|(c, _)| c).collect();
            for c in cookies {
                // SAFETY: `real` is alive until this struct is gone, and the cookie came from its own Advise
                let _ = unsafe { self.real.Unadvise(c) };
            }
        }
    }

    /// The interfaces a [`Dialog`] has a table for, with the number of entries in each.
    const TABLES: [(GUID, usize); 7] = [
        (IUnknown::IID, size_of::<windows_core::IInspectable_Vtbl>() / size_of::<usize>()),
        (IFileOpenDialog::IID, size_of::<IFileOpenDialog_Vtbl>() / size_of::<usize>()),
        (IFileSaveDialog::IID, size_of::<IFileSaveDialog_Vtbl>() / size_of::<usize>()),
        (IFileDialog2::IID, size_of::<IFileDialog2_Vtbl>() / size_of::<usize>()),
        (IFileDialogCustomize::IID, size_of::<IFileDialogCustomize_Vtbl>() / size_of::<usize>()),
        (IOleWindow::IID, size_of::<windows::Win32::System::Ole::IOleWindow_Vtbl>() / size_of::<usize>()),
        (windows::Win32::System::Ole::IObjectWithSite::IID, size_of::<windows::Win32::System::Ole::IObjectWithSite_Vtbl>() / size_of::<usize>()),
    ];

    /// Our copies of the tables, one per original: `[original table, QueryInterface without IInspectable, the rest of the original]`.
    static COPIES: std::sync::Mutex<Vec<(usize, usize)>> = std::sync::Mutex::new(Vec::new());

    /// QueryInterface of the copied tables: no to IInspectable, the original's answer otherwise.
    unsafe extern "system" fn query_without_inspectable(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
        unsafe {
            if !iid.is_null() && *iid == windows::core::IInspectable::IID {
                if !out.is_null() {
                    *out = std::ptr::null_mut();
                }
                return E_NOINTERFACE;
            }
            let table = *(this as *const *const usize);
            let original = *table.sub(1) as *const usize;
            let query: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*original);
            query(this, iid, out)
        }
    }

    /// A new dialog as COM sees it. `#[implement]` makes every object an IInspectable, Windows' dialog is not one, and .NET's
    /// WinRT layer (CsWinRT) wraps an IInspectable as a WinRT object that then won't cast to IFileOpenDialog (issue 589,
    /// SyncFolders: "Invalid cast from 'WinRT.IInspectable'"). So each of its tables is swapped for a copy that says no to it.
    fn make(save: bool) -> Result<IUnknown> {
        let unk: IUnknown = Dialog::new(save)?.into();
        let mut copies = COPIES.lock().unwrap_or_else(|e| e.into_inner());
        for (iid, len) in TABLES {
            let mut slot = std::ptr::null_mut();
            if unsafe { unk.query(&iid, &mut slot) }.is_err() || slot.is_null() {
                continue;
            }
            // the reference the query added goes back at once: `unk` keeps the object alive
            let field = unsafe { IUnknown::from_raw(slot) }.as_raw() as *mut usize;
            let table = unsafe { *field };
            if copies.iter().any(|&(_, copy)| copy == table) {
                continue; // two interfaces of one table (IFileDialog's chain)
            }
            let copy = match copies.iter().find(|&&(orig, _)| orig == table) {
                Some(&(_, copy)) => copy,
                None => {
                    let mut t = Vec::with_capacity(len + 1);
                    t.push(table);
                    t.push(query_without_inspectable as *const () as usize);
                    t.extend((1..len).map(|i| unsafe { *(table as *const usize).add(i) }));
                    let copy = unsafe { Box::leak(t.into_boxed_slice()).as_ptr().add(1) } as usize;
                    copies.push((table, copy));
                    copy
                }
            };
            unsafe { *field = copy };
        }
        Ok(unk)
    }

    impl Dialog {
        fn new(save: bool) -> Result<Dialog> {
            let real = real_dialog(if save { &FileSaveDialog } else { &FileOpenDialog })?;
            // Windows' defaults (a Save dialog asks before overwriting): an app that never calls
            // SetOptions relies on them
            let options = unsafe { real.GetOptions() }.unwrap_or_default();
            Ok(Dialog { save, real, st: RefCell::new(State { type_index: 1, options, ..Default::default() }) })
        }

        fn request(&self, owner: HWND) -> Request {
            let st = self.st.borrow();
            let mode = if st.options.0 & FOS_PICKFOLDERS.0 != 0 {
                Mode::Folder
            } else if self.save {
                Mode::Save
            } else {
                Mode::Open
            };
            let (file_dir, clean_file_name) = {
                let p = std::path::Path::new(&st.file_name);
                if p.is_absolute() {
                    (p.parent().map(|d| d.to_string_lossy().into_owned()), p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| st.file_name.clone()))
                } else {
                    (None, st.file_name.clone())
                }
            };
            let folder_from_app = st.folder.is_some() || file_dir.is_some();
            let folder = st
                .folder
                .clone()
                .or_else(|| st.default_folder.clone())
                .or(file_dir)
                .or_else(|| unsafe { self.real.GetFolder() }.ok().and_then(|item| item_path(&item)));
            Request {
                mode,
                multi: st.options.0 & FOS_ALLOWMULTISELECT.0 != 0,
                title: st.title.clone(),
                ok_label: st.ok_label.clone(),
                folder,
                file_name: clean_file_name,
                filters: st.filters.clone(),
                filter_index: st.type_index.max(1),
                default_ext: st.default_ext.trim_start_matches('.').to_string(),
                overwrite_prompt: self.save && st.options.0 & FOS_OVERWRITEPROMPT.0 != 0,
                owner: owner.0 as isize,
                app: exe_name(),
                folder_label: String::new(),
                folder_from_app: Some(folder_from_app),
            }
        }
    }

    /// A folder and a file that every Windows has, for asking an app what its OK button says for each.
    fn probe_paths() -> Option<(String, String)> {
        let dir = std::path::PathBuf::from(std::env::var_os("SystemRoot").or_else(|| std::env::var_os("windir"))?);
        let file = ["win.ini", "notepad.exe", "explorer.exe"].iter().map(|n| dir.join(n)).find(|p| p.is_file())?;
        dir.is_dir().then(|| (dir.to_string_lossy().into_owned(), file.to_string_lossy().into_owned()))
    }

    impl Dialog_Impl {
        /// What the app's OK button says while a FOLDER is selected, when that is something else than for a file: such an app takes
        /// the folder as the answer (`proto::folder_label_from` says why). Asked of the app's own event sinks before the picker is
        /// shown, as Windows' dialog asks them on every change of the selection: once with a folder "selected", once with a file.
        /// Only selection changes are told, never a change of folder: after that one the JetBrains runtime takes a cancelled dialog
        /// for "use the folder that was open". Empty for a Save dialog, a folder picker, and an app that listens to nothing.
        fn folder_label(&self) -> String {
            let (sinks, before, plain_open) = {
                let st = self.st.borrow();
                (st.sinks.iter().map(|(_, s)| s.clone()).collect::<Vec<IFileDialogEvents>>(), st.ok_label.clone(), !self.save && st.options.0 & FOS_PICKFOLDERS.0 == 0)
            };
            if !plain_open || sinks.is_empty() {
                return String::new();
            }
            let Some((folder, file)) = probe_paths() else { return String::new() };
            let Ok(me) = self.to_interface::<IFileOpenDialog>().cast::<IFileDialog>() else { return String::new() };
            let ask = |path: &str| -> String {
                {
                    let mut st = self.st.borrow_mut();
                    st.probe = Some(path.to_string());
                    st.ok_label = String::new();
                }
                for s in &sinks {
                    // (what the app answers does not matter; what it calls the button while it is asked does)
                    let _ = unsafe { (Interface::vtable(s).OnSelectionChange)(Interface::as_raw(s), Interface::as_raw(&me)) };
                }
                self.st.borrow().ok_label.clone()
            };
            let for_folder = ask(&folder);
            let for_file = ask(&file);
            {
                let mut st = self.st.borrow_mut();
                st.probe = None;
                // the button is left as the app names it for a file, or as it was
                st.ok_label = if for_file.trim().is_empty() { before } else { for_file.clone() };
            }
            crate::proto::folder_label_from(&for_folder, &for_file)
        }
    }

    impl IModalWindow_Impl for Dialog_Impl {
        fn Show(&self, owner: HWND) -> Result<()> {
            trace("Show");
            /// Clears `showing_owner` however Show returns.
            struct Shown<'a>(&'a RefCell<State>);
            impl Drop for Shown<'_> {
                fn drop(&mut self) {
                    self.0.borrow_mut().showing_owner = None;
                }
            }
            let _shown = Shown(&self.st);
            let off = std::env::var_os("RUSTYFILES_DIALOG_OFF").is_some();
            if off || self.st.borrow().customized {
                crate::log(&format!("show: Windows' dialog (customized={})", self.st.borrow().customized));
                return unsafe { self.real.Show(Some(owner)) };
            }
            let folder_label = self.folder_label();
            let mut req = self.request(owner);
            if !folder_label.is_empty() {
                crate::log(&format!("show: the app takes a folder too (its button says {folder_label:?} for one)"));
            }
            req.folder_label = folder_label;
            let has_owner = !owner.is_invalid();
            {
                use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
                let mut pid = 0u32;
                unsafe { GetWindowThreadProcessId(owner, Some(&mut pid)) };
                let front = unsafe { GetForegroundWindow() } == owner;
                crate::log(&format!("show: {:?}, owner {:?} of process {pid}, owner in front: {front}", req.mode, owner.0));
            }
            if has_owner {
                unsafe {
                    let _ = EnableWindow(owner, false);
                }
            }
            // Windows' dialog tells its event sinks that its first folder is in place (OnFolderChange) as it opens. Firefox's input
            // protection (FileDialogInputProtector) refuses any OnFileOk that comes before that, or within its delay after it, with
            // S_FALSE: without this every pick in Firefox was refused (issue 116). Told now, before the user is asked.
            {
                let sinks: Vec<IFileDialogEvents> = self.st.borrow().sinks.iter().map(|(_, s)| s.clone()).collect();
                if !sinks.is_empty()
                    && let Ok(me) = self.to_interface::<IFileOpenDialog>().cast::<IFileDialog>()
                {
                    for s in &sinks {
                        let _ = unsafe { (Interface::vtable(s).OnFolderChange)(Interface::as_raw(s), Interface::as_raw(&me)) };
                    }
                }
            }
            // (from here until Show returns the app may ask for the dialog's window: WPF does in OnFileOk, see `IOleWindow_Impl`)
            self.st.borrow_mut().showing_owner = Some(owner.0 as isize);
            #[cfg(test)]
            let answer = tests::CANNED.with(|c| c.borrow_mut().take());
            #[cfg(not(test))]
            let answer = crate::ipc::pick(&req, owner);
            if has_owner {
                unsafe {
                    let _ = EnableWindow(owner, true);
                    let _ = SetForegroundWindow(owner);
                }
            }
            let Some(resp) = answer else {
                // rustyfiles couldn't help: Windows' dialog, set up as the app asked
                crate::log(&format!("show: no answer from rustyfiles ({:?}), Windows' dialog", req.mode));
                return unsafe { self.real.Show(Some(owner)) };
            };
            if resp.windows {
                // "Use Windows' dialog for this app": this time already (later ones are not wrapped at all, see the factory)
                crate::log("show: the user chose Windows' dialog for this app");
                return unsafe { self.real.Show(Some(owner)) };
            }
            if !resp.ok || resp.paths.is_empty() {
                crate::log("show: cancelled");
                return Err(ERROR_CANCELLED.to_hresult().into());
            }
            crate::log(&format!("show: {:?} picked {} item(s), {} event sink(s)", req.mode, resp.paths.len(), self.st.borrow().sinks.len()));
            {
                let mut st = self.st.borrow_mut();
                st.type_index = resp.filter_index.max(1);
                st.file_name = std::path::Path::new(&resp.paths[0]).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
                st.result = Some(resp.paths);
            }
            // The app may still refuse the choice: only S_FALSE from OnFileOk does that (it ends
            // our dialog as cancelled). Anything else accepts, as in Windows' dialog: Chrome's
            // sinks answer E_NOTIMPL, which windows-rs would report as an error.
            let me: IFileDialog = self.to_interface::<IFileOpenDialog>().cast()?;
            let sinks: Vec<IFileDialogEvents> = self.st.borrow().sinks.iter().map(|(_, s)| s.clone()).collect();
            for s in sinks {
                let ok = || unsafe { (Interface::vtable(&s).OnFileOk)(Interface::as_raw(&s), Interface::as_raw(&me)) };
                let mut hr = ok();
                if hr == S_FALSE {
                    // a guard against a click that comes too soon (Firefox's, above) says no to a pick made within its delay: our
                    // window cannot stay open for a second try as Windows' does, so the pick is offered once more after the delay
                    std::thread::sleep(std::time::Duration::from_millis(SECOND_OFFER_MS));
                    hr = ok();
                    crate::log(&format!("show: OnFileOk said S_FALSE, offered again after {SECOND_OFFER_MS} ms: {}", if hr == S_FALSE { "refused" } else { "taken" }));
                }
                if hr == S_FALSE {
                    crate::log("show: the app refused the choice in OnFileOk (S_FALSE)");
                    self.st.borrow_mut().result = None;
                    return Err(ERROR_CANCELLED.to_hresult().into());
                }
                if hr != S_OK {
                    crate::log(&format!("show: OnFileOk answered {hr:?}, taken as accepted"));
                }
            }
            Ok(())
        }
    }

    // WHY (issue 116, Twitch Downloader, a WPF app: "File gets saved with default suggested name (not the chosen path/name) in root
    // of the app"). WPF's dialog code asks for the dialog's window in OnFileOk (`(IOleWindow)dialog`, the parent of its overwrite
    // question) before it reads the result. Our object had no IOleWindow: the cast threw, OnFileOk failed, the failure was taken as
    // "accepted" (Chrome answers E_NOTIMPL), and WPF, which had read nothing, gave the app the name the app had put in itself, with
    // no folder. Windows' dialog object has the interface. While rustyfiles is picking, the "dialog window" is the app's own window
    // that owns it; otherwise Windows' dialog answers.
    impl windows::Win32::System::Ole::IOleWindow_Impl for Dialog_Impl {
        fn GetWindow(&self) -> Result<HWND> {
            trace("GetWindow");
            if let Some(h) = self.st.borrow().showing_owner {
                return Ok(HWND(h as *mut c_void));
            }
            unsafe { self.real.cast::<windows::Win32::System::Ole::IOleWindow>()?.GetWindow() }
        }
        fn ContextSensitiveHelp(&self, enter: WBOOL) -> Result<()> {
            trace("ContextSensitiveHelp");
            unsafe { self.real.cast::<windows::Win32::System::Ole::IOleWindow>()?.ContextSensitiveHelp(enter.as_bool()) }
        }
    }

    // Windows' dialog object has these too; an app that asks for them gets them passed on.
    impl IFileDialog2_Impl for Dialog_Impl {
        fn SetCancelButtonLabel(&self, label: &PCWSTR) -> Result<()> {
            trace("SetCancelButtonLabel");
            unsafe { self.real.cast::<IFileDialog2>()?.SetCancelButtonLabel(*label) }
        }
        fn SetNavigationRoot(&self, psi: Ref<IShellItem>) -> Result<()> {
            trace("SetNavigationRoot");
            unsafe { self.real.cast::<IFileDialog2>()?.SetNavigationRoot(psi.ok()?) }
        }
    }

    impl windows::Win32::System::Ole::IObjectWithSite_Impl for Dialog_Impl {
        fn SetSite(&self, site: Ref<IUnknown>) -> Result<()> {
            trace("SetSite");
            unsafe { self.real.cast::<windows::Win32::System::Ole::IObjectWithSite>()?.SetSite(site.as_ref()) }
        }
        fn GetSite(&self, iid: *const GUID, out: *mut *mut c_void) -> Result<()> {
            trace("GetSite");
            unsafe { (Interface::vtable(&self.real.cast::<windows::Win32::System::Ole::IObjectWithSite>()?).GetSite)(Interface::as_raw(&self.real.cast::<windows::Win32::System::Ole::IObjectWithSite>()?), iid, out).ok() }
        }
    }

    impl IFileDialog_Impl for Dialog_Impl {
        fn SetFileTypes(&self, n: u32, specs: *const COMDLG_FILTERSPEC) -> Result<()> {
            trace("SetFileTypes");
            if specs.is_null() {
                return Err(E_POINTER.into());
            }
            let specs = unsafe { std::slice::from_raw_parts(specs, n as usize) };
            self.st.borrow_mut().filters = specs.iter().map(|s| Filter { name: wstr(&s.pszName), spec: wstr(&s.pszSpec) }).collect();
            unsafe { self.real.SetFileTypes(specs) }
        }
        fn SetFileTypeIndex(&self, i: u32) -> Result<()> {
            trace("SetFileTypeIndex");
            self.st.borrow_mut().type_index = i;
            unsafe { self.real.SetFileTypeIndex(i) }
        }
        fn GetFileTypeIndex(&self) -> Result<u32> {
            trace("GetFileTypeIndex");
            if self.st.borrow().result.is_some() {
                return Ok(self.st.borrow().type_index);
            }
            unsafe { self.real.GetFileTypeIndex() }
        }
        fn Advise(&self, sink: Ref<IFileDialogEvents>) -> Result<u32> {
            trace("Advise");
            let s = sink.ok()?;
            // Windows' dialog is given a relay: what it tells the sink names THIS object, the one the app holds (see `Relay`)
            let me = self.to_interface::<IFileOpenDialog>().cast::<IFileDialog>()?;
            let me_custom = self.to_interface::<IFileDialogCustomize>();
            let relay: IFileDialogEvents = Relay { app: s.clone(), me: me.as_raw(), me_custom: me_custom.as_raw() }.into();
            let cookie = unsafe { self.real.Advise(&relay)? };
            self.st.borrow_mut().sinks.push((cookie, s.clone()));
            Ok(cookie)
        }
        fn Unadvise(&self, cookie: u32) -> Result<()> {
            trace("Unadvise");
            self.st.borrow_mut().sinks.retain(|(c, _)| *c != cookie);
            unsafe { self.real.Unadvise(cookie) }
        }
        fn SetOptions(&self, fos: FILEOPENDIALOGOPTIONS) -> Result<()> {
            trace("SetOptions");
            self.st.borrow_mut().options = fos;
            unsafe { self.real.SetOptions(fos) }
        }
        fn GetOptions(&self) -> Result<FILEOPENDIALOGOPTIONS> {
            trace("GetOptions");
            unsafe { self.real.GetOptions() }
        }
        fn SetDefaultFolder(&self, psi: Ref<IShellItem>) -> Result<()> {
            trace("SetDefaultFolder");
            let i = psi.ok()?;
            self.st.borrow_mut().default_folder = item_path(i);
            unsafe { self.real.SetDefaultFolder(i) }
        }
        fn SetFolder(&self, psi: Ref<IShellItem>) -> Result<()> {
            trace("SetFolder");
            let i = psi.ok()?;
            self.st.borrow_mut().folder = item_path(i);
            unsafe { self.real.SetFolder(i) }
        }
        fn GetFolder(&self) -> Result<IShellItem> {
            trace("GetFolder");
            if let Some(first) = self.first_picked() {
                crate::log("GetFolder");
                if let Some(dir) = std::path::Path::new(&first).parent() {
                    return item_for(&dir.to_string_lossy());
                }
            }
            unsafe { self.real.GetFolder() }
        }
        fn GetCurrentSelection(&self) -> Result<IShellItem> {
            trace("GetCurrentSelection");
            // (while the app is asked what it does with a selection: that selection)
            let probe = self.st.borrow().probe.clone();
            if let Some(p) = probe {
                return item_for(&p);
            }
            if let Some(first) = self.first_picked() {
                return item_for(&first);
            }
            unsafe { self.real.GetCurrentSelection() }
        }
        fn SetFileName(&self, name: &PCWSTR) -> Result<()> {
            trace("SetFileName");
            self.st.borrow_mut().file_name = wstr(name);
            unsafe { self.real.SetFileName(*name) }
        }
        fn GetFileName(&self) -> Result<PWSTR> {
            trace("GetFileName");
            if self.st.borrow().probe.is_some() {
                return co_string(&self.st.borrow().file_name);
            }
            if self.st.borrow().result.is_some() {
                crate::log("GetFileName");
                return co_string(&self.st.borrow().file_name);
            }
            unsafe { self.real.GetFileName() }
        }
        fn SetTitle(&self, title: &PCWSTR) -> Result<()> {
            trace("SetTitle");
            self.st.borrow_mut().title = wstr(title);
            unsafe { self.real.SetTitle(*title) }
        }
        fn SetOkButtonLabel(&self, text: &PCWSTR) -> Result<()> {
            trace("SetOkButtonLabel");
            self.st.borrow_mut().ok_label = wstr(text);
            unsafe { self.real.SetOkButtonLabel(*text) }
        }
        fn SetFileNameLabel(&self, label: &PCWSTR) -> Result<()> {
            trace("SetFileNameLabel");
            unsafe { self.real.SetFileNameLabel(*label) }
        }
        fn GetResult(&self) -> Result<IShellItem> {
            trace("GetResult");
            if let Some(first) = self.first_picked() {
                let r = item_for(&first);
                // whether the app gets a file system item (what print drivers check)
                let fs = r.as_ref().ok().and_then(|i| unsafe { i.GetAttributes(windows::Win32::System::SystemServices::SFGAO_FILESYSTEM) }.ok()).is_some_and(|a| a.0 & windows::Win32::System::SystemServices::SFGAO_FILESYSTEM.0 != 0);
                crate::log(&format!("GetResult -> {}, file system item: {fs}", if r.is_ok() { "ok" } else { "FAILED" }));
                return r;
            }
            unsafe { self.real.GetResult() }
        }
        fn AddPlace(&self, psi: Ref<IShellItem>, fdap: FDAP) -> Result<()> {
            trace("AddPlace");
            unsafe { self.real.AddPlace(psi.ok()?, fdap) }
        }
        fn SetDefaultExtension(&self, ext: &PCWSTR) -> Result<()> {
            trace("SetDefaultExtension");
            self.st.borrow_mut().default_ext = wstr(ext);
            unsafe { self.real.SetDefaultExtension(*ext) }
        }
        fn Close(&self, hr: HRESULT) -> Result<()> {
            trace("Close");
            unsafe { self.real.Close(hr) }
        }
        fn SetClientGuid(&self, guid: *const GUID) -> Result<()> {
            trace("SetClientGuid");
            if guid.is_null() {
                return Err(E_POINTER.into());
            }
            unsafe { self.real.SetClientGuid(&*guid) }
        }
        fn ClearClientData(&self) -> Result<()> {
            trace("ClearClientData");
            unsafe { self.real.ClearClientData() }
        }
        fn SetFilter(&self, filter: Ref<IShellItemFilter>) -> Result<()> {
            trace("SetFilter");
            unsafe { self.real.SetFilter(filter.ok()?) }
        }
    }

    impl IFileOpenDialog_Impl for Dialog_Impl {
        fn GetResults(&self) -> Result<IShellItemArray> {
            trace("GetResults");
            if let Some(r) = self.picked() {
                let a = items_for(&r);
                crate::log(&format!("GetResults -> {}", if a.is_ok() { "ok" } else { "FAILED" }));
                return a;
            }
            unsafe { self.real.cast::<IFileOpenDialog>()?.GetResults() }
        }
        fn GetSelectedItems(&self) -> Result<IShellItemArray> {
            trace("GetSelectedItems");
            if let Some(r) = self.picked() {
                return items_for(&r);
            }
            unsafe { self.real.cast::<IFileOpenDialog>()?.GetSelectedItems() }
        }
    }

    impl IFileSaveDialog_Impl for Dialog_Impl {
        fn SetSaveAsItem(&self, psi: Ref<IShellItem>) -> Result<()> {
            trace("SetSaveAsItem");
            let i = psi.ok()?;
            if let Some(p) = item_path(i) {
                let path = std::path::Path::new(&p);
                let mut st = self.st.borrow_mut();
                st.folder = path.parent().map(|d| d.to_string_lossy().into_owned());
                st.file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
            }
            unsafe { self.real.cast::<IFileSaveDialog>()?.SetSaveAsItem(i) }
        }
        fn SetProperties(&self, store: Ref<IPropertyStore>) -> Result<()> {
            trace("SetProperties");
            let s = store.ok()?;
            self.st.borrow_mut().properties = Some(s.clone());
            unsafe { self.real.cast::<IFileSaveDialog>()?.SetProperties(s) }
        }
        fn SetCollectedProperties(&self, list: Ref<IPropertyDescriptionList>, append_default: WBOOL) -> Result<()> {
            trace("SetCollectedProperties");
            unsafe { self.real.cast::<IFileSaveDialog>()?.SetCollectedProperties(list.ok()?, append_default.as_bool()) }
        }
        fn GetProperties(&self) -> Result<IPropertyStore> {
            trace("GetProperties");
            // Picked in rustyfiles: the real dialog was never shown and has none to give (it
            // fails, and "Microsoft Print to PDF", which asks for them, then gave up on the file
            // and fell back to its "Print to file" prompt). The app's own properties, else an
            // empty store: nothing was edited.
            if self.st.borrow().result.is_some() {
                if let Some(s) = self.st.borrow().properties.clone() {
                    return Ok(s);
                }
                let mut p: *mut c_void = std::ptr::null_mut();
                unsafe { windows::Win32::UI::Shell::PropertiesSystem::PSCreateMemoryPropertyStore(&IPropertyStore::IID, &mut p)? };
                return Ok(unsafe { IPropertyStore::from_raw(p) });
            }
            unsafe { self.real.cast::<IFileSaveDialog>()?.GetProperties() }
        }
        fn ApplyProperties(&self, psi: Ref<IShellItem>, store: Ref<IPropertyStore>, hwnd: HWND, sink: Ref<IFileOperationProgressSink>) -> Result<()> {
            trace("ApplyProperties");
            unsafe { self.real.cast::<IFileSaveDialog>()?.ApplyProperties(psi.ok()?, store.ok()?, hwnd, sink.as_ref()) }
        }
    }

    /// What Windows' dialog tells the app's event sink, passed on with the dialog the app holds (this wrapper) in place of Windows' own
    /// object. An app that keeps its state per dialog (or compares the dialog it is told about with its own) did not recognise
    /// Windows' object: issue 163, SolidWorks' "Save as PDF" (its own controls, so Windows' dialog was shown) failed with rustyfiles
    /// installed. The custom controls' events (`IFileDialogControlEvents`) go the same way when the app's sink takes them.
    ///
    /// `me` and `me_custom` are not counted references: the wrapper owns Windows' dialog, which owns this relay, so the wrapper outlives
    /// every call made here (a counted one would keep the three alive for ever).
    #[implement(IFileDialogEvents, IFileDialogControlEvents)]
    struct Relay {
        app: IFileDialogEvents,
        me: *mut c_void,
        me_custom: *mut c_void,
    }

    /// An HRESULT as the `Result` of an implemented method, keeping a success code other than S_OK (an OnFileOk's S_FALSE refuses the
    /// file).
    fn pass(hr: HRESULT) -> Result<()> {
        if hr == S_OK { Ok(()) } else { Err(windows::core::Error::from_hresult(hr)) }
    }

    impl IFileDialogEvents_Impl for Relay_Impl {
        fn OnFileOk(&self, _: Ref<IFileDialog>) -> Result<()> {
            pass(unsafe { (Interface::vtable(&self.app).OnFileOk)(Interface::as_raw(&self.app), self.me) })
        }
        fn OnFolderChanging(&self, _: Ref<IFileDialog>, folder: Ref<IShellItem>) -> Result<()> {
            let f = folder.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw);
            pass(unsafe { (Interface::vtable(&self.app).OnFolderChanging)(Interface::as_raw(&self.app), self.me, f) })
        }
        fn OnFolderChange(&self, _: Ref<IFileDialog>) -> Result<()> {
            pass(unsafe { (Interface::vtable(&self.app).OnFolderChange)(Interface::as_raw(&self.app), self.me) })
        }
        fn OnSelectionChange(&self, _: Ref<IFileDialog>) -> Result<()> {
            pass(unsafe { (Interface::vtable(&self.app).OnSelectionChange)(Interface::as_raw(&self.app), self.me) })
        }
        fn OnShareViolation(&self, _: Ref<IFileDialog>, item: Ref<IShellItem>) -> Result<FDE_SHAREVIOLATION_RESPONSE> {
            let i = item.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw);
            let mut r = FDE_SHAREVIOLATION_RESPONSE::default();
            pass(unsafe { (Interface::vtable(&self.app).OnShareViolation)(Interface::as_raw(&self.app), self.me, i, &mut r) }).map(|_| r)
        }
        fn OnTypeChange(&self, _: Ref<IFileDialog>) -> Result<()> {
            pass(unsafe { (Interface::vtable(&self.app).OnTypeChange)(Interface::as_raw(&self.app), self.me) })
        }
        fn OnOverwrite(&self, _: Ref<IFileDialog>, item: Ref<IShellItem>) -> Result<FDE_OVERWRITE_RESPONSE> {
            let i = item.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw);
            let mut r = FDE_OVERWRITE_RESPONSE::default();
            pass(unsafe { (Interface::vtable(&self.app).OnOverwrite)(Interface::as_raw(&self.app), self.me, i, &mut r) }).map(|_| r)
        }
    }

    impl IFileDialogControlEvents_Impl for Relay_Impl {
        fn OnItemSelected(&self, _: Ref<IFileDialogCustomize>, id: u32, item: u32) -> Result<()> {
            let c: IFileDialogControlEvents = self.app.cast().map_err(|_| windows::core::Error::from(windows::Win32::Foundation::E_NOTIMPL))?;
            pass(unsafe { (Interface::vtable(&c).OnItemSelected)(Interface::as_raw(&c), self.me_custom, id, item) })
        }
        fn OnButtonClicked(&self, _: Ref<IFileDialogCustomize>, id: u32) -> Result<()> {
            let c: IFileDialogControlEvents = self.app.cast().map_err(|_| windows::core::Error::from(windows::Win32::Foundation::E_NOTIMPL))?;
            pass(unsafe { (Interface::vtable(&c).OnButtonClicked)(Interface::as_raw(&c), self.me_custom, id) })
        }
        fn OnCheckButtonToggled(&self, _: Ref<IFileDialogCustomize>, id: u32, checked: WBOOL) -> Result<()> {
            let c: IFileDialogControlEvents = self.app.cast().map_err(|_| windows::core::Error::from(windows::Win32::Foundation::E_NOTIMPL))?;
            pass(unsafe { (Interface::vtable(&c).OnCheckButtonToggled)(Interface::as_raw(&c), self.me_custom, id, checked) })
        }
        fn OnControlActivating(&self, _: Ref<IFileDialogCustomize>, id: u32) -> Result<()> {
            let c: IFileDialogControlEvents = self.app.cast().map_err(|_| windows::core::Error::from(windows::Win32::Foundation::E_NOTIMPL))?;
            pass(unsafe { (Interface::vtable(&c).OnControlActivating)(Interface::as_raw(&c), self.me_custom, id) })
        }
    }

    /// Every control the app adds marks the dialog as one only Windows' own can show.
    macro_rules! custom {
        ($self:ident, $mark:expr, $call:expr) => {{
            if $mark {
                $self.st.borrow_mut().customized = true;
            }
            let c: IFileDialogCustomize = $self.real.cast()?;
            #[allow(unused_unsafe)]
            unsafe {
                $call(c)
            }
        }};
    }

    impl IFileDialogCustomize_Impl for Dialog_Impl {
        fn EnableOpenDropDown(&self, id: u32) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.EnableOpenDropDown(id))
        }
        fn AddMenu(&self, id: u32, label: &PCWSTR) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddMenu(id, *label))
        }
        fn AddPushButton(&self, id: u32, label: &PCWSTR) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddPushButton(id, *label))
        }
        fn AddComboBox(&self, id: u32) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddComboBox(id))
        }
        fn AddRadioButtonList(&self, id: u32) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddRadioButtonList(id))
        }
        fn AddCheckButton(&self, id: u32, label: &PCWSTR, checked: WBOOL) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddCheckButton(id, *label, checked.as_bool()))
        }
        fn AddEditBox(&self, id: u32, text: &PCWSTR) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddEditBox(id, *text))
        }
        fn AddSeparator(&self, id: u32) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddSeparator(id))
        }
        fn AddText(&self, id: u32, text: &PCWSTR) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.AddText(id, *text))
        }
        fn SetControlLabel(&self, id: u32, label: &PCWSTR) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetControlLabel(id, *label))
        }
        fn GetControlState(&self, id: u32) -> Result<CDCONTROLSTATEF> {
            custom!(self, false, |c: IFileDialogCustomize| c.GetControlState(id))
        }
        fn SetControlState(&self, id: u32, state: CDCONTROLSTATEF) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetControlState(id, state))
        }
        fn GetEditBoxText(&self, id: u32) -> Result<*mut u16> {
            custom!(self, false, |c: IFileDialogCustomize| c.GetEditBoxText(id))
        }
        fn SetEditBoxText(&self, id: u32, text: &PCWSTR) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetEditBoxText(id, *text))
        }
        fn GetCheckButtonState(&self, id: u32) -> Result<WBOOL> {
            custom!(self, false, |c: IFileDialogCustomize| c.GetCheckButtonState(id))
        }
        fn SetCheckButtonState(&self, id: u32, checked: WBOOL) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetCheckButtonState(id, checked.as_bool()))
        }
        fn AddControlItem(&self, id: u32, item: u32, label: &PCWSTR) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.AddControlItem(id, item, *label))
        }
        fn RemoveControlItem(&self, id: u32, item: u32) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.RemoveControlItem(id, item))
        }
        fn RemoveAllControlItems(&self, id: u32) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.RemoveAllControlItems(id))
        }
        fn GetControlItemState(&self, id: u32, item: u32) -> Result<CDCONTROLSTATEF> {
            custom!(self, false, |c: IFileDialogCustomize| c.GetControlItemState(id, item))
        }
        fn SetControlItemState(&self, id: u32, item: u32, state: CDCONTROLSTATEF) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetControlItemState(id, item, state))
        }
        fn GetSelectedControlItem(&self, id: u32) -> Result<u32> {
            custom!(self, false, |c: IFileDialogCustomize| c.GetSelectedControlItem(id))
        }
        fn SetSelectedControlItem(&self, id: u32, item: u32) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetSelectedControlItem(id, item))
        }
        fn StartVisualGroup(&self, id: u32, label: &PCWSTR) -> Result<()> {
            custom!(self, true, |c: IFileDialogCustomize| c.StartVisualGroup(id, *label))
        }
        fn EndVisualGroup(&self) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.EndVisualGroup())
        }
        fn MakeProminent(&self, id: u32) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.MakeProminent(id))
        }
        fn SetControlItemText(&self, id: u32, item: u32, label: &PCWSTR) -> Result<()> {
            custom!(self, false, |c: IFileDialogCustomize| c.SetControlItemText(id, item, *label))
        }
    }

    #[cfg(test)]
    pub(super) mod tests {
        use super::*;
        use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};

        /// Issue 589: as Windows' dialog does, ours says no to IInspectable, IAgileObject and IMarshal from each of its
        /// interfaces, and still works.
        #[test]
        fn a_dialog_is_no_winrt_or_agile_object_as_windows_own_is_not() {
            const NO: [GUID; 3] = [
                windows::core::IInspectable::IID,
                GUID::from_u128(0x94ea2b94_e9cc_49e0_c0ff_ee64ca8f5b90), // IAgileObject
                GUID::from_u128(0x00000003_0000_0000_c000_000000000046), // IMarshal
            ];
            unsafe {
                let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
                for save in [false, true] {
                    let unk = make(save).unwrap();
                    let froms: [IUnknown; 4] = [
                        unk.clone(),
                        unk.cast::<IFileDialog>().unwrap().cast().unwrap(),
                        unk.cast::<IFileDialogCustomize>().unwrap().into(),
                        unk.cast::<IOleWindow>().unwrap().into(),
                    ];
                    for from in &froms {
                        for iid in NO {
                            let mut p = std::ptr::null_mut();
                            assert_eq!(from.query(&iid, &mut p), E_NOINTERFACE, "{iid:?}");
                            assert!(p.is_null());
                        }
                    }
                    let custom: IFileDialogCustomize = unk.cast().unwrap();
                    assert_eq!(custom.cast::<IUnknown>().unwrap(), unk, "one identity");
                    let dialog: IFileDialog = custom.cast().unwrap();
                    dialog.SetTitle(w!("rf-dialog test")).unwrap();
                    dialog.SetOptions(FOS_NOCHANGEDIR).unwrap();
                    assert!(dialog.GetOptions().unwrap().contains(FOS_NOCHANGEDIR));
                    assert!(dialog.cast::<IFileSaveDialog>().is_ok());
                }
            }
        }

        /// Issue 1107: the items of a pick are real file system items, a folder as a folder and a file being saved too, as Qt's
        /// dialog code asks before it reads their paths.
        #[test]
        fn picked_items_are_file_system_items() {
            use windows::Win32::System::SystemServices::{SFGAO_FILESYSTEM, SFGAO_FOLDER};
            let dir = std::env::temp_dir().join(format!("rf-dialog-items-{}", std::process::id()));
            std::fs::create_dir_all(&dir).unwrap();
            let not_yet = dir.join("new file.txt");
            unsafe {
                let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
                let paths = vec![dir.to_string_lossy().into_owned(), not_yet.to_string_lossy().into_owned()];
                let arr = items_for(&paths).unwrap();
                assert_eq!(arr.GetCount().unwrap(), 2);
                let folder = arr.GetItemAt(0).unwrap();
                let attrs = folder.GetAttributes(SFGAO_FILESYSTEM | SFGAO_FOLDER).unwrap();
                assert!(attrs.contains(SFGAO_FILESYSTEM) && attrs.contains(SFGAO_FOLDER), "{attrs:?}");
                assert_eq!(item_path(&folder).map(std::path::PathBuf::from), Some(dir.clone()));
                let file = arr.GetItemAt(1).unwrap();
                assert!(file.GetAttributes(SFGAO_FILESYSTEM).unwrap().contains(SFGAO_FILESYSTEM));
                assert_eq!(item_path(&file).map(std::path::PathBuf::from), Some(not_yet));
            }
            let _ = std::fs::remove_dir_all(&dir);
        }

        /// Issue 977: the shell's own processes are left to Windows' dialog, whatever the case of the name; other apps are not.
        #[test]
        fn the_shell_gets_windows_own_class() {
            for exe in ["explorer.exe", "EXPLORER.EXE", "sihost.exe", "StartMenuExperienceHost.exe", "SearchHost.exe"] {
                assert!(is_shell(exe), "{exe}");
            }
            for exe in ["notepad.exe", "chrome.exe", "WhatsApp.Root.exe", "rustyfiles.exe", "explorer.exe.bak", ""] {
                assert!(!is_shell(exe), "{exe}");
            }
        }

        /// Issue 625: with a DLP agent's hook module in the app, the app gets Windows' class factory itself.
        #[test]
        fn a_process_with_a_hook_module_gets_windows_own_class() {
            use std::os::windows::ffi::OsStrExt;
            assert_eq!(hooked_by(), None);
            let dir = std::env::temp_dir().join(format!("rf-dialog-hook-{}", std::process::id()));
            std::fs::create_dir_all(&dir).unwrap();
            let fake = dir.join("SecurityEv.dll");
            // (any DLL a test has no other use for, under the agent's name)
            std::fs::copy(r"C:\Windows\System32\mscms.dll", &fake).unwrap();
            let wide: Vec<u16> = fake.as_os_str().encode_wide().chain([0]).collect();
            let lib = unsafe { LoadLibraryW(PCWSTR(wide.as_ptr())) }.expect("the copy loads");
            assert_eq!(hooked_by().as_deref(), Some("SecurityEv.dll"));
            let mut out: *mut c_void = std::ptr::null_mut();
            let hr = unsafe { DllGetClassObject(&FileOpenDialog, &IClassFactory::IID, &mut out) };
            assert_eq!(hr, S_OK);
            let factory = unsafe { IClassFactory::from_raw(out) };
            // comdlg32's own factory: its code is in comdlg32.dll, not in this module
            let vtable = unsafe { *(out as *const *const c_void) };
            let mut module = windows::Win32::Foundation::HMODULE::default();
            unsafe {
                windows::Win32::System::LibraryLoader::GetModuleHandleExW(
                    windows::Win32::System::LibraryLoader::GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
                        | windows::Win32::System::LibraryLoader::GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                    PCWSTR(vtable as *const u16),
                    &mut module,
                )
                .unwrap();
                assert_eq!(module, GetModuleHandleW(w!("comdlg32.dll")).unwrap(), "Windows' factory");
            }
            drop(factory);
            unsafe { windows::Win32::Foundation::FreeLibrary(lib).unwrap() };
            assert_eq!(hooked_by(), None);
            let _ = std::fs::remove_dir_all(&dir);
        }

        thread_local! {
            /// What "rustyfiles" answers the next Show with.
            pub static CANNED: RefCell<Option<crate::proto::Response>> = const { RefCell::new(None) };
        }

        /// An app's event sink that does in OnFileOk what WPF's dialog code does: it asks for the dialog's window first, then reads
        /// the result.
        #[implement(IFileDialogEvents)]
        struct WpfLike {
            got: std::rc::Rc<RefCell<Option<(isize, String)>>>,
        }

        #[allow(non_snake_case)]
        impl IFileDialogEvents_Impl for WpfLike_Impl {
            fn OnFileOk(&self, pfd: Ref<IFileDialog>) -> Result<()> {
                let d = pfd.ok()?;
                let window = unsafe { d.cast::<IOleWindow>()?.GetWindow()? };
                let path = unsafe { d.GetResult()?.GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING)?.to_string()? };
                *self.got.borrow_mut() = Some((window.0 as isize, path));
                Ok(())
            }
            fn OnFolderChanging(&self, _: Ref<IFileDialog>, _: Ref<IShellItem>) -> Result<()> {
                Ok(())
            }
            fn OnFolderChange(&self, _: Ref<IFileDialog>) -> Result<()> {
                Ok(())
            }
            fn OnSelectionChange(&self, _: Ref<IFileDialog>) -> Result<()> {
                Ok(())
            }
            fn OnShareViolation(&self, _: Ref<IFileDialog>, _: Ref<IShellItem>) -> Result<FDE_SHAREVIOLATION_RESPONSE> {
                Ok(FDESVR_DEFAULT)
            }
            fn OnTypeChange(&self, _: Ref<IFileDialog>) -> Result<()> {
                Ok(())
            }
            fn OnOverwrite(&self, _: Ref<IFileDialog>, _: Ref<IShellItem>) -> Result<FDE_OVERWRITE_RESPONSE> {
                Ok(FDEOR_DEFAULT)
            }
        }

        /// An app's sink that remembers which dialog it was told about, and refuses the file (S_FALSE) as an app that checks it does.
        #[implement(IFileDialogEvents)]
        struct Remembers {
            told: std::rc::Rc<RefCell<Vec<*mut c_void>>>,
        }

        #[allow(non_snake_case)]
        impl IFileDialogEvents_Impl for Remembers_Impl {
            fn OnFileOk(&self, pfd: Ref<IFileDialog>) -> Result<()> {
                self.told.borrow_mut().push(pfd.ok()?.as_raw());
                Err(windows::core::Error::from_hresult(S_FALSE))
            }
            fn OnFolderChanging(&self, _: Ref<IFileDialog>, _: Ref<IShellItem>) -> Result<()> {
                Ok(())
            }
            fn OnFolderChange(&self, _: Ref<IFileDialog>) -> Result<()> {
                Ok(())
            }
            fn OnSelectionChange(&self, _: Ref<IFileDialog>) -> Result<()> {
                Ok(())
            }
            fn OnShareViolation(&self, _: Ref<IFileDialog>, _: Ref<IShellItem>) -> Result<FDE_SHAREVIOLATION_RESPONSE> {
                Ok(FDESVR_DEFAULT)
            }
            fn OnTypeChange(&self, pfd: Ref<IFileDialog>) -> Result<()> {
                self.told.borrow_mut().push(pfd.ok()?.as_raw());
                Ok(())
            }
            fn OnOverwrite(&self, _: Ref<IFileDialog>, _: Ref<IShellItem>) -> Result<FDE_OVERWRITE_RESPONSE> {
                Ok(FDEOR_DEFAULT)
            }
        }

        /// Issue 163: what Windows' dialog tells the app's sink names the dialog the app holds, and the app's answer comes back whole.
        #[test]
        fn windows_dialog_events_reach_the_app_with_its_own_dialog() {
            unsafe {
                let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
            }
            let dialog: IFileSaveDialog = Dialog::new(true).unwrap().into();
            let mine = dialog.cast::<IFileDialog>().unwrap();
            let told = std::rc::Rc::new(RefCell::new(Vec::new()));
            let sink: IFileDialogEvents = Remembers { told: told.clone() }.into();
            let theirs = real_dialog(&FileSaveDialog).unwrap();
            let relay: IFileDialogEvents =
                Relay { app: sink, me: mine.as_raw(), me_custom: dialog.cast::<IFileDialogCustomize>().unwrap().as_raw() }.into();
            // Windows' dialog calls the relay with ITSELF
            let ok = unsafe { (Interface::vtable(&relay).OnFileOk)(Interface::as_raw(&relay), Interface::as_raw(&theirs)) };
            let _ = unsafe { relay.OnTypeChange(&theirs) };
            assert_eq!(ok, S_FALSE, "the app's refusal reaches Windows' dialog");
            assert_eq!(*told.borrow(), vec![mine.as_raw(), mine.as_raw()], "the app is told about the dialog it holds");
            // and the dialog answers what Windows' does
            assert!(dialog.cast::<IFileDialog2>().is_ok() && dialog.cast::<windows::Win32::System::Ole::IObjectWithSite>().is_ok());
        }

        #[test]
        fn a_wpf_app_reads_the_picked_path_in_on_file_ok() {
            unsafe {
                let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
            }
            let dialog: IFileSaveDialog = Dialog::new(true).unwrap().into();
            let got = std::rc::Rc::new(RefCell::new(None));
            let sink: IFileDialogEvents = WpfLike { got: got.clone() }.into();
            unsafe {
                dialog.Advise(&sink).unwrap();
                dialog.SetFileName(w!("default name.mp4")).unwrap();
            }
            // (the temp folder by its long name: on a machine whose profile folder has a short alias, as GitHub's runners do
            // (`RUNNER~1`), the shell item gives the path back long; issue 186)
            let temp = std::env::temp_dir();
            let temp = temp.canonicalize().map(|p| std::path::PathBuf::from(p.to_string_lossy().trim_start_matches(r"\\?\"))).unwrap_or(temp);
            let picked = temp.join("rf-dialog-wpf-test.mp4").to_string_lossy().into_owned();
            CANNED.with(|c| *c.borrow_mut() = Some(crate::proto::Response { ok: true, paths: vec![picked.clone()], filter_index: 1, windows: false }));
            // (no owner window: the "dialog window" is then the null window, as the app's own would be)
            unsafe { dialog.Show(None).unwrap() };
            let (_, path) = got.borrow().clone().expect("OnFileOk ran and read the result");
            assert_eq!(path, picked, "the app gets the path picked in rustyfiles, not its own default name");
            // outside Show, Windows' dialog answers (it has no window: an error, not a stale owner)
            let _ = unsafe { dialog.cast::<IOleWindow>().unwrap().GetWindow() };
        }

        #[test]
        fn request_extracts_folder_from_absolute_file_name() {
            unsafe {
                let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
            }
            let d = Dialog::new(true).unwrap();
            let full_file = std::path::PathBuf::from(r"C:\Projects\AE\project.aep");
            d.st.borrow_mut().file_name = full_file.to_string_lossy().into_owned();
            let req = d.request(HWND::default());
            assert_eq!(req.folder, Some(r"C:\Projects\AE".to_string()));
            assert_eq!(req.file_name, "project.aep");
        }
    }

    /// Apps that get Windows' own dialog object, untouched (not wrapped), whatever they do with it.
    /// * PickerHost.exe shows the dialog for packaged apps' FileSavePicker / FileOpenPicker (Snipping Tool's Save as). It drives
    ///   Windows' dialog through a private interface ({9EA5491C-89C8-4BEF-93D3-7F665FB82A33}) we can't pass on, and fails the pick
    ///   without it.
    /// * SLDWORKS.exe: SolidWorks' "Save as PDF" failed with the wrapper in between, although Windows' dialog itself was shown (it adds
    ///   its own controls) (issue 163: "Corrupts the ability of my CAD software from being able to save a drawing as a pdf").
    const UNTOUCHED: [&str; 2] = ["PickerHost.exe", "SLDWORKS.exe"];

    /// Modules other programs put into every app that hook Windows' dialog object: where one is loaded, the app gets Windows' own
    /// class straight from comdlg32.dll (not even our factory), so the object it hooks is the one it expects.
    /// * SecurityEv_x64.dll / SecurityEv.dll: Sangfor's DLP agent (EAIO). Word crashed in it on start whenever our dialog was
    ///   registered, and started normally without (issue 625).
    const HOOKED_BY: [PCWSTR; 2] = [w!("SecurityEv_x64.dll"), w!("SecurityEv.dll")];

    /// Windows' own shell processes: they get Windows' class straight from comdlg32.dll, so none of our code runs in them. With the
    /// dialog registered, explorer.exe and sihost.exe crashed again and again on one PC from 1.0.7 on, which took down the Start menu, the
    /// taskbar and packaged apps; with only the dialog turned off they ran normally (issue 977). The shell has no Open / Save dialog a
    /// user would want rustyfiles in, so it is never wrapped there.
    const SHELL: [&str; 12] = [
        "explorer.exe",
        "sihost.exe",
        "ShellExperienceHost.exe",
        "StartMenuExperienceHost.exe",
        "ShellHost.exe",
        "SearchHost.exe",
        "SearchApp.exe",
        "TextInputHost.exe",
        "ApplicationFrameHost.exe",
        "RuntimeBroker.exe",
        "LockApp.exe",
        "taskhostw.exe",
    ];

    fn is_shell(exe: &str) -> bool {
        SHELL.iter().any(|s| exe.eq_ignore_ascii_case(s))
    }

    /// The first of [`HOOKED_BY`] loaded in this process.
    fn hooked_by() -> Option<String> {
        HOOKED_BY.iter().find(|m| unsafe { GetModuleHandleW(**m) }.is_ok()).map(|m| wstr(m))
    }

    #[implement(IClassFactory)]
    struct Factory {
        save: bool,
    }

    impl IClassFactory_Impl for Factory_Impl {
        fn CreateInstance(&self, outer: Ref<IUnknown>, iid: *const GUID, object: *mut *mut c_void) -> Result<()> {
            if object.is_null() || iid.is_null() {
                return Err(E_POINTER.into());
            }
            unsafe { *object = std::ptr::null_mut() };
            if outer.is_some() {
                return Err(CLASS_E_NOAGGREGATION.into());
            }
            // some apps need Windows' own dialog object (see UNTOUCHED), and the user may have chosen it for others (issue 371)
            let exe = exe_name();
            let listed = || {
                crate::proto::windows_apps_path().and_then(|p| std::fs::read_to_string(p).ok()).is_some_and(|t| crate::proto::windows_app_listed(&t, &exe))
            };
            let env_bypass = || crate::env_bypass_enabled(std::env::var("RUSTYFILES_WINDOWS_DIALOG").ok().as_deref());
            if let Some(app) = UNTOUCHED
                .iter()
                .copied()
                .find(|a| exe.eq_ignore_ascii_case(a))
                .or_else(|| env_bypass().then_some("RUSTYFILES_WINDOWS_DIALOG"))
                .or_else(|| listed().then_some("listed by the user"))
            {
                crate::log(&format!("create: {app}, Windows' dialog"));
                let real = real_dialog(if self.save { &FileSaveDialog } else { &FileOpenDialog })?;
                return unsafe { real.query(iid, object).ok() };
            }
            let unk = make(self.save)?;
            unsafe { unk.query(iid, object).ok() }
        }
        fn LockServer(&self, _lock: WBOOL) -> Result<()> {
            Ok(())
        }
    }

    /// COM entry point: our two classes.
    ///
    /// # Safety
    /// Called by COM with valid pointers.
    #[unsafe(no_mangle)]
    pub unsafe extern "system" fn DllGetClassObject(clsid: *const GUID, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
        if clsid.is_null() || iid.is_null() || out.is_null() {
            return E_POINTER;
        }
        unsafe { *out = std::ptr::null_mut() };
        let save = match unsafe { *clsid } {
            c if c == FileOpenDialog => false,
            c if c == FileSaveDialog => true,
            _ => return CLASS_E_CLASSNOTAVAILABLE,
        };
        if is_shell(&exe_name()) {
            return match comdlg32_class_object() {
                Ok(f) => unsafe { f(clsid, iid, out) },
                Err(e) => e.code(),
            };
        }
        if let Some(m) = hooked_by() {
            crate::log(&format!("create: {m} is loaded, Windows' dialog class"));
            return match comdlg32_class_object() {
                Ok(f) => unsafe { f(clsid, iid, out) },
                Err(e) => e.code(),
            };
        }
        let f: IClassFactory = Factory { save }.into();
        unsafe { f.query(iid, out) }
    }

    /// Kept loaded: the app may still hold objects, and loading is cheap.
    #[unsafe(no_mangle)]
    pub extern "system" fn DllCanUnloadNow() -> HRESULT {
        S_FALSE
    }

    #[allow(dead_code)]
    const _: (HRESULT, HRESULT) = (S_OK, E_NOINTERFACE);
}

/// Whether `RUSTYFILES_WINDOWS_DIALOG` enables native Windows dialogs for this process and its children.
pub(crate) fn env_bypass_enabled(val: Option<&str>) -> bool {
    val.map(str::trim).is_some_and(|v| v.eq_ignore_ascii_case("1") || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes") || v.eq_ignore_ascii_case("on"))
}

#[cfg(test)]
mod tests {
    use super::env_bypass_enabled;

    #[test]
    fn env_bypass_parses_truthy_values_only() {
        assert!(env_bypass_enabled(Some("1")));
        assert!(env_bypass_enabled(Some(" true ")));
        assert!(env_bypass_enabled(Some("YES")));
        assert!(env_bypass_enabled(Some("On")));
        assert!(!env_bypass_enabled(None));
        assert!(!env_bypass_enabled(Some("")));
        assert!(!env_bypass_enabled(Some("0")));
        assert!(!env_bypass_enabled(Some("false")));
    }
}