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.

41.1 KB
Raw Blame
//! File operations through the Windows shell copy engine (IFileOperation): same behavior as
//! Explorer (recycle bin, undo record, conflict dialogs, elevation prompts when needed).
//! Blocking — call from a worker thread.
//!
//! The engine is the shell's: with no shell window running it never finishes (seen without Explorer: the engine's own progress window
//! sat on the screen for ever). So every operation first asks `engine_guard::plan`: the engine when a shell window exists (run on a
//! thread of its own with a time limit for its start), a plain file call where one does the same thing (rename, permanent delete), and
//! a true refusal ([`NoShellEngine`]) for what only the shell can do (the Recycle Bin, names the shell makes). See `engine_guard.rs`.

use std::path::{Path, PathBuf};

use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance};
use windows::Win32::UI::Shell::{
    FILEOPERATION_FLAGS, FOF_ALLOWUNDO, FOF_NOCONFIRMMKDIR, FOF_NOERRORUI, FOF_RENAMEONCOLLISION, FOFX_ADDUNDORECORD,
    FOFX_RECYCLEONDELETE, FileOperation, IFileOperation, IShellItem, SHCreateItemFromParsingName,
};
use windows::core::PCWSTR;

use crate::engine_guard::{self as guard, Life, NoShellEngine, Op, Plan};
use crate::shell::ensure_com;
use crate::wide::wide;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transfer {
    Copy,
    Move,
}

fn item(p: &Path) -> anyhow::Result<IShellItem> {
    let w = crate::wide::shell_name(p);
    match unsafe { SHCreateItemFromParsingName(PCWSTR(w.as_ptr()), None) } {
        Ok(item) => Ok(item),
        // a phone's item the shell does not take back by its name (issue 221): found by walking down to it
        Err(_) if crate::shellfolder::is_namespace_name(&p.to_string_lossy()) => crate::shellfolder::bind(&p.to_string_lossy()),
        Err(e) => Err(e.into()),
    }
}

pub(crate) fn new_op(flags: u32) -> anyhow::Result<IFileOperation> {
    ensure_com();
    let op: IFileOperation = unsafe { CoCreateInstance(&FileOperation, None, CLSCTX_ALL)? };
    unsafe { op.SetOperationFlags(FILEOPERATION_FLAGS(flags))? };
    let owner = DIALOG_OWNER.load(std::sync::atomic::Ordering::Relaxed);
    if owner != 0 {
        let hwnd = windows::Win32::Foundation::HWND(owner as *mut _);
        if unsafe { windows::Win32::UI::WindowsAndMessaging::IsWindow(Some(hwnd)) }.as_bool() {
            let _ = unsafe { op.SetOwnerWindow(hwnd) };
        }
    }
    Ok(op)
}

/// The window the shell engine's own windows (Replace or Skip, "Destination Folder Access Denied", its progress) belong to: the
/// app's window the user used last ([`set_dialog_owner`]).
///
/// WHY (issue 187: replacing a file in `C:\Program Files (x86)` "nothing happened", the job stayed "processing" in the Status
/// Center). Such a file is handed to the shell engine, which asks for administrator rights in a window of its own; with no owner
/// that window opened BEHIND rustyfiles (tried: `#32770` "Destination Folder Access Denied", owner none, not in front), and the job
/// waited for an answer nobody could see.
static DIALOG_OWNER: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);

/// Remembers the app's window in front, for the shell engine's windows ([`DIALOG_OWNER`]).
pub fn set_dialog_owner(hwnd: isize) {
    DIALOG_OWNER.store(hwnd, std::sync::atomic::Ordering::Relaxed);
}

/// A tracker nobody listens to and nobody cancels (the untracked operations still attach the progress sink: it is how the supervisor
/// learns that the engine started).
fn quiet_tracker() -> Arc<Tracker> {
    Arc::new(Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))))
}

/// Runs an engine job under supervision (a thread of its own, a limit for its start); the job is given the flag the sink raises.
fn engine<T: Send + 'static>(op: Op, job: impl FnOnce(Arc<Life>) -> anyhow::Result<T> + Send + 'static) -> anyhow::Result<T> {
    let life = Life::new();
    let seen = life.clone();
    guard::supervise(op, life, move || job(seen))
}

/// The answer for an operation that only the shell can do: the engine, or a refusal that says why.
fn needs_shell(op: Op) -> anyhow::Result<()> {
    match guard::plan(op, guard::shell_present()) {
        Plan::Refuse => Err(NoShellEngine { op }.into()),
        _ => Ok(()),
    }
}

/// Copies `sources` into `dest_dir` with the shell's engine and the given FOF_* flags (no undo
/// record unless the flags ask for one).
pub fn shell_copy(sources: &[PathBuf], dest_dir: &Path, flags: u32) -> anyhow::Result<()> {
    needs_shell(Op::Copy)?;
    let (sources, dest_dir) = (sources.to_vec(), dest_dir.to_path_buf());
    engine(Op::Copy, move |life| {
        let op = new_op(flags)?;
        let dest = item(&dest_dir)?;
        for s in &sources {
            let it = item(s)?;
            life.beat();
            unsafe { op.CopyItem(&it, &dest, PCWSTR::null(), None)? };
        }
        anyhow::ensure!(perform_tracked(&op, quiet_tracker(), life)?, "the copy was aborted");
        Ok(())
    })
}

/// Copy or move into `dest_dir`. Pasting into the same folder makes "x - Kopya" names.
pub fn transfer(kind: Transfer, sources: &[PathBuf], dest_dir: &Path) -> anyhow::Result<bool> {
    let same_dir = sources.iter().all(|s| s.parent() == Some(dest_dir));
    if kind == Transfer::Move && same_dir {
        return Ok(true); // moving onto itself: no-op
    }
    let mut flags = FOF_ALLOWUNDO.0 as u32 | FOF_NOCONFIRMMKDIR.0 as u32 | FOFX_ADDUNDORECORD.0;
    if same_dir {
        flags |= FOF_RENAMEONCOLLISION.0 as u32;
    }
    transfer_through_engine(kind, sources, dest_dir, flags, quiet_tracker())
}

/// The engine part of every transfer: `flags` as the caller wants them, `tracker` the one the sink reports to.
fn transfer_through_engine(kind: Transfer, sources: &[PathBuf], dest_dir: &Path, flags: u32, tracker: Arc<Tracker>) -> anyhow::Result<bool> {
    let op_kind = if kind == Transfer::Copy { Op::Copy } else { Op::Move };
    needs_shell(op_kind)?;
    let run = move |sources: &[PathBuf], extra: u32, tracker: Arc<Tracker>| {
        let (sources, dest_dir) = (sources.to_vec(), dest_dir.to_path_buf());
        engine(op_kind, move |life| {
            let op = new_op(flags | extra)?;
            let dest = item(&dest_dir)?;
            for s in &sources {
                let it = item(s)?;
                life.beat();
                unsafe {
                    match kind {
                        Transfer::Copy => op.CopyItem(&it, &dest, PCWSTR::null(), None)?,
                        Transfer::Move => op.MoveItem(&it, &dest, PCWSTR::null(), None)?,
                    }
                }
            }
            perform_tracked(&op, tracker, life)
        })
    };
    // (a copy leaves its sources where they are, so what is left to do cannot be told from them: copies as before)
    match kind {
        Transfer::Move if tracker.in_use.is_some() => quietly(sources.to_vec(), Held::Move, tracker, run),
        _ => run(sources, 0, tracker),
    }
}

/// A delete or a move with the shell's error windows off (`FOF_NOERRORUI`). When items another program holds were left, the app is
/// asked (`Tracker::in_use`, its own "in use" window, which may close those programs) and the items still there are tried again;
/// when other items failed (one that needs administrator rights), the ones still there go once more through the engine with its own
/// windows, as before. What is "left" is told by what still exists of the items asked for: a deleted or moved item is gone from there.
fn quietly(
    mut items: Vec<PathBuf>,
    held: Held,
    tracker: Arc<Tracker>,
    run: impl Fn(&[PathBuf], u32, Arc<Tracker>) -> anyhow::Result<bool>,
) -> anyhow::Result<bool> {
    loop {
        tracker.failures.lock().unwrap().clear();
        let r = run(&items, FOF_NOERRORUI.0 as u32, tracker.clone());
        let failures = std::mem::take(&mut *tracker.failures.lock().unwrap());
        if failures.is_empty() || tracker.cancel.load(Ordering::Relaxed) {
            return r;
        }
        let left: Vec<PathBuf> = items.iter().filter(|p| std::fs::symlink_metadata(p).is_ok()).cloned().collect();
        log::info!("{held:?}: {} failure(s) {:?}, {} item(s) left", failures.len(), failures.iter().map(|(h, _)| h.0).collect::<Vec<_>>(), left.len());
        if left.is_empty() {
            return r;
        }
        if failures.iter().any(|(h, _)| in_use(*h)) {
            if let Some(ask) = &tracker.in_use {
                if ask(&left, held) {
                    items = left;
                    continue;
                }
                return Ok(false);
            }
        }
        return run(&left, 0, tracker);
    }
}

/// Delete to the recycle bin (`permanent = false`) or permanently (Windows asks for confirmation).
pub fn delete(paths: &[PathBuf], permanent: bool) -> anyhow::Result<bool> {
    let flags = if permanent { 0 } else { FOF_ALLOWUNDO.0 as u32 | FOFX_RECYCLEONDELETE.0 | FOFX_ADDUNDORECORD.0 };
    delete_through_engine(paths, permanent, flags, quiet_tracker())
}

/// The engine part of every delete. With no shell: a permanent delete is our own parallel delete alone (what it cannot remove is an
/// error that says so), the Recycle Bin is refused.
fn delete_through_engine(paths: &[PathBuf], permanent: bool, flags: u32, tracker: Arc<Tracker>) -> anyhow::Result<bool> {
    let op_kind = if permanent { Op::PermanentDelete } else { Op::RecycleDelete };
    if guard::plan(op_kind, guard::shell_present()) == Plan::Own {
        let threads = crate::fastdelete::threads_for(paths);
        let done = crate::fastdelete::delete_without_shell(paths, tracker.clone(), threads)?;
        if !done && !tracker.cancel.load(Ordering::Relaxed) {
            // (something may well have been deleted already: this is not the "nothing was changed" refusal)
            return Err(guard::PartlyDone { op: Op::PermanentDelete, left: None }.into());
        }
        return Ok(done);
    }
    needs_shell(op_kind)?;
    let run = move |paths: &[PathBuf], extra: u32, tracker: Arc<Tracker>| {
        let paths = paths.to_vec();
        engine(op_kind, move |life| {
            let op = new_op(flags | extra)?;
            for p in &paths {
                unsafe { op.DeleteItem(&item(p)?, None)? };
                life.beat();
            }
            perform_tracked(&op, tracker, life)
        })
    };
    if tracker.in_use.is_some() { quietly(paths.to_vec(), Held::Delete, tracker, run) } else { run(paths, 0, tracker) }
}

pub fn rename(path: &Path, new_name: &str) -> anyhow::Result<bool> {
    if guard::plan(Op::Rename, guard::shell_present()) == Plan::Own {
        // no shell: the same rename as a plain file call, failing instead of replacing; the app's own undo list records it as before
        let to = path.with_file_name(new_name);
        log::info!("rename: no shell window, renaming directly");
        rename_no_replace(path, &to)?;
        return Ok(true);
    }
    // First with the shell's error windows off: an item another program holds comes back as `InUse`, and the app says so in its own
    // window, naming the programs (Windows' "Folder In Use" came up instead of ours). Any other failure (a folder
    // that needs administrator rights) goes through the shell's own windows again, as before.
    let tracker = quiet_tracker();
    let quiet = {
        let (path, new_name, tracker) = (path.to_path_buf(), new_name.to_string(), tracker.clone());
        engine(Op::Rename, move |life| rename_op(&path, &new_name, FOF_NOERRORUI.0 as u32, tracker, life))
    };
    let failures = tracker.failures.lock().unwrap().clone();
    log::debug!("rename: quiet try {quiet:?}, failures {failures:?}");
    match quiet {
        Ok(true) if failures.is_empty() => Ok(true),
        Err(e) if failures.iter().any(|(h, _)| in_use(*h)) || e.downcast_ref::<windows::core::Error>().is_some_and(|w| in_use(w.code())) => Err(InUse.into()),
        _ if failures.iter().any(|(h, _)| in_use(*h)) => Err(InUse.into()),
        Ok(false) if failures.is_empty() => Ok(false),
        _ => {
            let (path, new_name) = (path.to_path_buf(), new_name.to_string());
            engine(Op::Rename, move |life| rename_op(&path, &new_name, 0, quiet_tracker(), life))
        }
    }
}

fn rename_op(path: &Path, new_name: &str, extra: u32, tracker: Arc<Tracker>, life: Arc<Life>) -> anyhow::Result<bool> {
    let op = new_op(FOF_ALLOWUNDO.0 as u32 | FOFX_ADDUNDORECORD.0 | extra)?;
    let w = wide(new_name);
    unsafe { op.RenameItem(&item(path)?, PCWSTR(w.as_ptr()), None)? };
    perform_tracked(&op, tracker, life)
}

/// An item is open in another program (or held by one), so it can't be renamed, moved or deleted now: where the shell's engine
/// would have shown its "File In Use" / "Folder In Use" window, the app shows its own (`rf_win::lockers` names the programs).
#[derive(Debug)]
pub struct InUse;

impl std::fmt::Display for InUse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("the item is open in another program")
    }
}

impl std::error::Error for InUse {}

/// The engine's and Windows' codes for an item another program holds.
pub fn in_use(hr: HRESULT) -> bool {
    use windows::Win32::UI::Shell::{COPYENGINE_E_SHARING_VIOLATION_DEST, COPYENGINE_E_SHARING_VIOLATION_SRC};
    const SHARING_VIOLATION: HRESULT = HRESULT(0x80070020_u32 as i32);
    const LOCK_VIOLATION: HRESULT = HRESULT(0x80070021_u32 as i32);
    [SHARING_VIOLATION, LOCK_VIOLATION, COPYENGINE_E_SHARING_VIOLATION_SRC, COPYENGINE_E_SHARING_VIOLATION_DEST].contains(&hr)
}

/// Plain rename that fails instead of silently replacing an existing target
/// (`std::fs::rename` replaces on Windows).
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
    use windows::Win32::Storage::FileSystem::{MOVE_FILE_FLAGS, MoveFileExW};
    let (a, b) = (crate::wide::long_path(from), crate::wide::long_path(to));
    unsafe { MoveFileExW(PCWSTR(a.as_ptr()), PCWSTR(b.as_ptr()), MOVE_FILE_FLAGS(0)) }.map_err(|e| std::io::Error::from_raw_os_error(e.code().0 & 0xFFFF))
}

/// `name`, `name (2)`, … (the caller passes the name in the UI language) — returns the created path.
pub fn new_folder(dir: &Path, name: &str) -> anyhow::Result<PathBuf> {
    let p = unique_name(dir, name, "");
    match std::fs::create_dir(&p) {
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => new_item_by_shell(&p, true)?,
        r => r?,
    }
    Ok(p)
}

pub fn new_text_file(dir: &Path, name: &str) -> anyhow::Result<PathBuf> {
    let p = unique_name(dir, name, ".txt");
    match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) {
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => new_item_by_shell(&p, false)?,
        r => drop(r?),
    }
    Ok(p)
}

/// Makes the folder or empty file `p` with the shell's engine: for a folder only administrators may write to (`Program Files`,
/// `Windows`), where the plain call is refused. The engine asks for the rights in its own window ("Destination Folder Access Denied",
/// which belongs to the app's window: [`DIALOG_OWNER`]), as Explorer does (issue 195: "Trying to create a new folder ... in
/// C:\Program Files (x86) or C:\Program Files doesn't work, nothing happens"). An error when the user says no.
fn new_item_by_shell(p: &Path, folder: bool) -> anyhow::Result<()> {
    use windows::Win32::Storage::FileSystem::{FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL};
    needs_shell(Op::Copy)?;
    let dir = p.parent().ok_or_else(|| anyhow::anyhow!("no parent folder"))?.to_path_buf();
    let name = wide(p.file_name().unwrap_or_default());
    let target = p.to_path_buf();
    engine(Op::Copy, move |life| {
        let op = new_op(FOF_NOCONFIRMMKDIR.0 as u32)?;
        let attrs = if folder { FILE_ATTRIBUTE_DIRECTORY } else { FILE_ATTRIBUTE_NORMAL };
        unsafe { op.NewItem(&item(&dir)?, attrs.0, PCWSTR(name.as_ptr()), PCWSTR::null(), None)? };
        anyhow::ensure!(perform_tracked(&op, quiet_tracker(), life)?, "making the new item was cancelled");
        anyhow::ensure!(target.exists(), "the new item was not made");
        Ok(())
    })
}

pub fn unique_name(dir: &Path, stem: &str, ext: &str) -> PathBuf {
    let first = dir.join(format!("{stem}{ext}"));
    if !first.exists() {
        return first;
    }
    (2..)
        .map(|i| dir.join(format!("{stem} ({i}){ext}")))
        .find(|p| !p.exists())
        .unwrap()
}


// ---------------------------------------------------------------------------------------------
// Tracked operations (in-app Status Center): progress callback + cancellation, no shell
// progress window (conflict / elevation dialogs still come from Windows).
// ---------------------------------------------------------------------------------------------

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use windows::Win32::Foundation::E_ABORT;
use windows::Win32::UI::Shell::{FOF_SILENT, IFileOperationProgressSink, IFileOperationProgressSink_Impl, SIGDN_NORMALDISPLAY};
use windows_core::{HRESULT, Ref, implement};

/// Bytes done and bytes in all, for an operation whose engine knows them (our copy engine,
/// the archive code). `on_progress` only carries abstract units, which is enough for a
/// percentage but not for a speed in MB/s; the interface reads this when a progress report
/// arrives. Both stay 0 for the shell's engine and for operations counted in items.
#[derive(Default)]
pub struct ByteProgress {
    done: std::sync::atomic::AtomicU64,
    total: std::sync::atomic::AtomicU64,
}

impl ByteProgress {
    pub fn set(&self, done: u64, total: u64) {
        // total first: a reader that sees the new `done` never pairs it with an older, smaller total
        self.total.store(total, std::sync::atomic::Ordering::Relaxed);
        self.done.store(done.min(total), std::sync::atomic::Ordering::Relaxed);
    }

    /// `(done, total)`; `total == 0` means the engine does not count bytes.
    pub fn get(&self) -> (u64, u64) {
        let done = self.done.load(std::sync::atomic::Ordering::Relaxed);
        let total = self.total.load(std::sync::atomic::Ordering::Relaxed);
        (done.min(total), total)
    }
}

/// Progress reporting for one operation. `on_progress(total, done, current_item)`;
/// `total`/`done` are the shell's abstract work units (use done/total as a fraction).
pub struct Tracker {
    /// Bytes, when the engine counts them (see [`ByteProgress`]). Shared so the interface can
    /// keep a handle while the worker owns the tracker.
    pub bytes: Arc<ByteProgress>,
    pub on_progress: Box<dyn Fn(u32, u32, Option<String>) + Send + Sync>,
    pub cancel: Arc<AtomicBool>,
    /// (source, result) for every item the shell finished: the new copy/moved location, or the
    /// item's path inside the Recycle Bin for deletes. Used to build undo records.
    pub results: std::sync::Mutex<Vec<(PathBuf, PathBuf)>>,
    /// The work waits while this is set: our engine in its own loops, the shell's engine in its progress sink (`Sink::check`).
    pub paused: Arc<AtomicBool>,
    /// Copy speed limit in bytes per second; 0 = none (our engine only).
    pub limit: std::sync::atomic::AtomicU64,
    /// Check copies after writing them (our engine only); see [`Tracker::set_verify`].
    pub verify: std::sync::atomic::AtomicU8,
    /// Asked (on the worker thread, blocking) what to do with names that already exist at the
    /// destination; `None` cancels the operation. Without it, both are kept.
    #[allow(clippy::type_complexity)]
    pub ask: Option<Box<dyn Fn(&[crate::fastcopy::Conflict]) -> Option<Vec<crate::fastcopy::Resolve>> + Send + Sync>>,
    /// What the shell's engine said for each item it could not do, and the item (with `FOF_NOERRORUI` it says nothing on the screen).
    pub failures: std::sync::Mutex<Vec<(HRESULT, Option<PathBuf>)>>,
    /// Asked (on the worker thread, blocking) about items another program holds, which a delete or a move could not do: the app
    /// shows its own "in use" window (it may close the programs) and answers whether to try them again. Without it, the shell's own
    /// "File In Use" window comes up as before.
    pub in_use: Option<Box<dyn Fn(&[PathBuf], Held) -> bool + Send + Sync>>,
}

/// What a delete or a move was doing when an item turned out to be held by another program (for the app's "in use" window).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Held {
    Delete,
    Move,
}

impl Tracker {
    pub fn set_verify(&self, v: crate::fastcopy::Verify) {
        self.verify.store(v as u8, Ordering::Relaxed);
    }

    pub fn verify_mode(&self) -> crate::fastcopy::Verify {
        match self.verify.load(Ordering::Relaxed) {
            1 => crate::fastcopy::Verify::Quick,
            2 => crate::fastcopy::Verify::Full,
            _ => crate::fastcopy::Verify::Off,
        }
    }

    pub fn new(on_progress: Box<dyn Fn(u32, u32, Option<String>) + Send + Sync>, cancel: Arc<AtomicBool>) -> Self {
        Self {
            bytes: Default::default(),
            on_progress,
            cancel,
            results: Default::default(),
            paused: Default::default(),
            limit: Default::default(),
            verify: Default::default(),
            ask: None,
            failures: Default::default(),
            in_use: None,
        }
    }
}

fn fs_path(item: Ref<IShellItem>) -> Option<PathBuf> {
    let it = item.as_ref()?;
    unsafe {
        let p = it.GetDisplayName(windows::Win32::UI::Shell::SIGDN_FILESYSPATH).ok()?;
        let s = p.to_string().ok();
        windows::Win32::System::Com::CoTaskMemFree(Some(p.0 as *const _));
        s.map(PathBuf::from)
    }
}

#[implement(IFileOperationProgressSink)]
struct Sink {
    tracker: Arc<Tracker>,
    last: std::sync::Mutex<(u32, u32)>,
    /// Raised at the engine's first sign of life (see `engine_guard::supervise`).
    life: Arc<Life>,
}

impl Sink {
    fn check(&self) -> windows_core::Result<()> {
        self.life.signal();
        // "Pause": the shell's engine has no pause of its own, but it calls its sink on the thread that does the work, before and
        // after every item and for its progress, so waiting here holds it. WHY (issue 322): the card's Pause button did nothing
        // for the copies this engine makes (to and from network shares and other places that are no plain disk path, and a paste
        // into the items' own folder): the card said "Paused" and the copy went on.
        while self.tracker.paused.load(Ordering::Relaxed) && !self.tracker.cancel.load(Ordering::Relaxed) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        if self.tracker.cancel.load(Ordering::Relaxed) { Err(E_ABORT.into()) } else { Ok(()) }
    }
    fn record(&self, hr: HRESULT, src: Ref<IShellItem>, created: Ref<IShellItem>) {
        if hr.is_err() {
            self.tracker.failures.lock().unwrap().push((hr, fs_path(src)));
            return;
        }
        {
            if let (Some(a), Some(b)) = (fs_path(src), fs_path(created)) {
                self.tracker.results.lock().unwrap().push((a, b));
            }
        }
    }
    fn item(&self, item: Ref<IShellItem>) {
        if let Some(it) = item.as_ref() {
            if let Ok(name) = unsafe { it.GetDisplayName(SIGDN_NORMALDISPLAY) } {
                let s = unsafe { name.to_string().unwrap_or_default() };
                unsafe { windows::Win32::System::Com::CoTaskMemFree(Some(name.0 as *const _)) };
                let (t, d) = *self.last.lock().unwrap();
                (self.tracker.on_progress)(t, d, Some(s));
            }
        }
    }
}

#[allow(non_snake_case)]
impl IFileOperationProgressSink_Impl for Sink_Impl {
    fn StartOperations(&self) -> windows_core::Result<()> { self.life.signal(); Ok(()) }
    fn FinishOperations(&self, _hr: HRESULT) -> windows_core::Result<()> { Ok(()) }
    fn PreRenameItem(&self, _f: u32, item: Ref<IShellItem>, _n: &PCWSTR) -> windows_core::Result<()> { self.item(item); self.check() }
    fn PostRenameItem(&self, _f: u32, i: Ref<IShellItem>, _n: &PCWSTR, hr: HRESULT, _c: Ref<IShellItem>) -> windows_core::Result<()> {
        if hr.is_err() {
            self.tracker.failures.lock().unwrap().push((hr, fs_path(i)));
        }
        self.check()
    }
    fn PreMoveItem(&self, _f: u32, item: Ref<IShellItem>, _d: Ref<IShellItem>, _n: &PCWSTR) -> windows_core::Result<()> { self.item(item); self.check() }
    fn PostMoveItem(&self, _f: u32, i: Ref<IShellItem>, _d: Ref<IShellItem>, _n: &PCWSTR, hr: HRESULT, c: Ref<IShellItem>) -> windows_core::Result<()> { self.record(hr, i, c); self.check() }
    fn PreCopyItem(&self, _f: u32, item: Ref<IShellItem>, _d: Ref<IShellItem>, _n: &PCWSTR) -> windows_core::Result<()> { self.item(item); self.check() }
    fn PostCopyItem(&self, _f: u32, i: Ref<IShellItem>, _d: Ref<IShellItem>, _n: &PCWSTR, hr: HRESULT, c: Ref<IShellItem>) -> windows_core::Result<()> { self.record(hr, i, c); self.check() }
    fn PreDeleteItem(&self, _f: u32, item: Ref<IShellItem>) -> windows_core::Result<()> { self.item(item); self.check() }
    fn PostDeleteItem(&self, _f: u32, i: Ref<IShellItem>, hr: HRESULT, c: Ref<IShellItem>) -> windows_core::Result<()> { self.record(hr, i, c); self.check() }
    fn PreNewItem(&self, _f: u32, _d: Ref<IShellItem>, _n: &PCWSTR) -> windows_core::Result<()> { self.check() }
    fn PostNewItem(&self, _f: u32, _d: Ref<IShellItem>, _n: &PCWSTR, _t: &PCWSTR, _a: u32, _hr: HRESULT, _c: Ref<IShellItem>) -> windows_core::Result<()> { self.check() }
    fn UpdateProgress(&self, total: u32, done: u32) -> windows_core::Result<()> {
        *self.last.lock().unwrap() = (total, done);
        (self.tracker.on_progress)(total, done, None);
        self.check()
    }
    fn ResetTimer(&self) -> windows_core::Result<()> { Ok(()) }
    fn PauseTimer(&self) -> windows_core::Result<()> { Ok(()) }
    fn ResumeTimer(&self) -> windows_core::Result<()> { Ok(()) }
}

/// Performs the operation with the progress sink attached. Ok(true) when everything completed, Ok(false) when the user cancelled part of it.
fn perform_tracked(op: &IFileOperation, tracker: Arc<Tracker>, life: Arc<Life>) -> anyhow::Result<bool> {
    let sink: IFileOperationProgressSink = Sink { tracker: tracker.clone(), last: std::sync::Mutex::new((0, 0)), life }.into();
    let cookie = unsafe { op.Advise(&sink)? };
    let r = (|| -> anyhow::Result<bool> {
        unsafe {
            op.PerformOperations()?;
            Ok(!op.GetAnyOperationsAborted()?.as_bool())
        }
    })();
    unsafe {
        let _ = op.Unadvise(cookie);
    }
    if tracker.cancel.load(Ordering::Relaxed) {
        return Ok(false);
    }
    r
}

/// `transfer` with in-app progress (no shell progress window).
pub fn transfer_tracked(kind: Transfer, sources: &[PathBuf], dest_dir: &Path, tracker: Arc<Tracker>) -> anyhow::Result<bool> {
    let same_dir = sources.iter().all(|s| s.parent() == Some(dest_dir));
    if kind == Transfer::Move && same_dir {
        return Ok(true);
    }
    let mut flags = FOF_ALLOWUNDO.0 as u32 | FOF_NOCONFIRMMKDIR.0 as u32 | FOFX_ADDUNDORECORD.0 | FOF_SILENT.0 as u32;
    if same_dir {
        flags |= FOF_RENAMEONCOLLISION.0 as u32;
    }
    transfer_through_engine(kind, sources, dest_dir, flags, tracker)
}

/// `delete` with in-app progress.
pub fn delete_tracked(paths: &[PathBuf], permanent: bool, tracker: Arc<Tracker>) -> anyhow::Result<bool> {
    let mut flags = if permanent { 0 } else { FOF_ALLOWUNDO.0 as u32 | FOFX_RECYCLEONDELETE.0 | FOFX_ADDUNDORECORD.0 };
    flags |= FOF_SILENT.0 as u32;
    delete_through_engine(paths, permanent, flags, tracker)
}

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

    #[test]
    fn unique() {
        // the shell's engine never finishes without a shell window (seen without Explorer): say so and return, so the suite ends
        if guard::not_run_without_shell("fileops::tests::unique") {
            return;
        }
        let d = std::env::temp_dir().join(format!("rf-uniq-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let a = new_folder(&d, "Yeni klasör").unwrap();
        let b = new_folder(&d, "Yeni klasör").unwrap();
        assert!(a.ends_with("Yeni klasör"));
        assert!(b.ends_with("Yeni klasör (2)"));
        let f = new_text_file(&d, "Yeni Metin Belgesi").unwrap();
        assert!(rename(&f, "x.txt").unwrap());
        assert!(d.join("x.txt").exists());
        assert!(transfer(Transfer::Copy, &[d.join("x.txt")], &d).unwrap());
        let n = std::fs::read_dir(&d).unwrap().count();
        assert_eq!(n, 4); // 2 folders, x.txt, x - Kopya.txt
        // tracked copy reports progress
        let calls = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let c2 = calls.clone();
        let t = Arc::new(Tracker::new(
            Box::new(move |_, _, _| {
                c2.fetch_add(1, Ordering::Relaxed);
            }),
            Arc::new(AtomicBool::new(false)),
        ));
        std::fs::create_dir_all(d.join("dst")).unwrap();
        assert!(transfer_tracked(Transfer::Copy, &[d.join("x.txt")], &d.join("dst"), t.clone()).unwrap());
        assert!(d.join("dst").join("x.txt").exists());
        assert!(calls.load(Ordering::Relaxed) > 0);
        let res = t.results.lock().unwrap().clone();
        assert_eq!(res.len(), 1);
        assert!(res[0].1.ends_with("dst\\x.txt"), "{res:?}");
        std::fs::remove_dir_all(&d).unwrap();
    }

    fn scratch(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("rf-noshell-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn a_paused_copy_of_the_shells_engine_waits_until_it_is_resumed() {
        if guard::not_run_without_shell("fileops::tests::a_paused_copy_of_the_shells_engine_waits_until_it_is_resumed") {
            return;
        }
        let d = scratch("pause");
        std::fs::write(d.join("a.txt"), b"x").unwrap();
        std::fs::create_dir_all(d.join("dst")).unwrap();
        let t = Arc::new(Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
        t.paused.store(true, Ordering::Relaxed);
        let (t2, d2) = (t.clone(), d.clone());
        let work = std::thread::spawn(move || transfer_tracked(Transfer::Copy, &[d2.join("a.txt")], &d2.join("dst"), t2));
        std::thread::sleep(std::time::Duration::from_millis(1500));
        assert!(!d.join("dst").join("a.txt").exists(), "nothing is copied while paused");
        assert!(!work.is_finished(), "the copy waits");
        t.paused.store(false, Ordering::Relaxed);
        assert!(work.join().unwrap().unwrap());
        assert!(d.join("dst").join("a.txt").exists());
        let _ = std::fs::remove_dir_all(&d);
    }

    /// By hand only (it writes 3 GB, three times over): `cargo test -p rf-win --lib in_the_middle_of_one_big_file -- --ignored --nocapture`.
    /// The case of issue 322: one big file pasted into its own folder, paused part way.
    #[test]
    #[ignore]
    fn a_pause_holds_the_shells_engine_in_the_middle_of_one_big_file() {
        use std::io::Write;
        use std::time::{Duration, Instant};
        let d = scratch("pause-big");
        let big = d.join("big.bin");
        {
            let mut f = std::fs::File::create(&big).unwrap();
            let block = vec![0x5Au8; 8 << 20];
            for _ in 0..384 {
                f.write_all(&block).unwrap();
            }
        }
        // how long the whole copy takes when nothing holds it
        let plain = Arc::new(Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
        let t0 = Instant::now();
        assert!(transfer_tracked(Transfer::Copy, std::slice::from_ref(&big), &d, plain).unwrap());
        let whole = t0.elapsed();
        // the same copy, paused at its first progress report
        let started = Arc::new(AtomicBool::new(false));
        let last = Arc::new(std::sync::Mutex::new((0u32, 0u32)));
        let (s2, l2) = (started.clone(), last.clone());
        let t = Arc::new(Tracker::new(
            Box::new(move |total, done, _| {
                *l2.lock().unwrap() = (total, done);
                if done > 0 && done < total {
                    s2.store(true, Ordering::Relaxed);
                }
            }),
            Arc::new(AtomicBool::new(false)),
        ));
        let (t2, d2, b2) = (t.clone(), d.clone(), big.clone());
        let work = std::thread::spawn(move || transfer_tracked(Transfer::Copy, std::slice::from_ref(&b2), &d2, t2));
        while !started.load(Ordering::Relaxed) {
            assert!(!work.is_finished(), "the copy ended before it reported any progress");
            std::thread::sleep(Duration::from_millis(2));
        }
        t.paused.store(true, Ordering::Relaxed);
        std::thread::sleep(Duration::from_millis(500));
        let at_pause = *last.lock().unwrap();
        std::thread::sleep(Duration::from_secs(6));
        let after = *last.lock().unwrap();
        let held = !work.is_finished();
        let r0 = Instant::now();
        t.paused.store(false, Ordering::Relaxed);
        assert!(work.join().unwrap().unwrap());
        let rest = r0.elapsed();
        println!("whole {whole:?}, paused at {at_pause:?}, after 6 s {after:?}, held {held}, rest after resume {rest:?}");
        let _ = std::fs::remove_dir_all(&d);
        assert!(held, "the copy finished while it was paused");
        assert_eq!(at_pause, after, "progress moved while paused");
        // had the engine gone on copying behind the held call, nothing would be left to do after the resume
        let part = at_pause.1 as f64 / at_pause.0.max(1) as f64;
        assert!(rest.as_secs_f64() > whole.as_secs_f64() * (1.0 - part) * 0.3, "the rest took {rest:?} of a {whole:?} copy paused at {part:.2}");
    }

    #[test]
    fn without_a_shell_a_rename_is_a_plain_rename_that_does_not_replace() {
        let d = scratch("rename");
        std::fs::write(d.join("a.txt"), b"a").unwrap();
        std::fs::write(d.join("b.txt"), b"b").unwrap();
        guard::with_no_shell(|| {
            assert!(rename(&d.join("a.txt"), "c.txt").unwrap());
            assert!(!d.join("a.txt").exists() && d.join("c.txt").exists());
            // an existing target is an error and nothing is replaced
            assert!(rename(&d.join("c.txt"), "b.txt").is_err());
            assert_eq!(std::fs::read(d.join("b.txt")).unwrap(), b"b");
            assert!(d.join("c.txt").exists());
        });
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn without_a_shell_the_recycle_bin_and_the_shells_copy_are_refused_and_nothing_is_touched() {
        let d = scratch("refuse");
        let f = d.join("keep.txt");
        std::fs::write(&f, b"x").unwrap();
        std::fs::create_dir_all(d.join("dst")).unwrap();
        guard::with_no_shell(|| {
            let t = Arc::new(Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
            let e = delete_tracked(std::slice::from_ref(&f), false, t.clone()).expect_err("the bin needs the shell");
            assert_eq!(e.downcast_ref::<NoShellEngine>().map(|n| n.op), Some(Op::RecycleDelete), "{e:#}");
            let e = delete(std::slice::from_ref(&f), false).expect_err("same, untracked");
            assert!(e.downcast_ref::<NoShellEngine>().is_some());
            let e = transfer_tracked(Transfer::Copy, std::slice::from_ref(&f), &d.join("dst"), t.clone()).expect_err("the engine copy needs the shell");
            assert_eq!(e.downcast_ref::<NoShellEngine>().map(|n| n.op), Some(Op::Copy));
            let e = transfer(Transfer::Move, std::slice::from_ref(&f), &d.join("dst")).expect_err("and so does a move");
            assert_eq!(e.downcast_ref::<NoShellEngine>().map(|n| n.op), Some(Op::Move));
            let e = shell_copy(std::slice::from_ref(&f), &d.join("dst"), 0).expect_err("and the plain shell copy");
            assert!(e.downcast_ref::<NoShellEngine>().is_some());
        });
        assert!(f.exists(), "a refused operation leaves the file where it is");
        assert!(std::fs::read_dir(d.join("dst")).unwrap().next().is_none());
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn without_a_shell_a_permanent_delete_is_our_own_and_a_missing_item_is_done() {
        let d = scratch("permanent");
        std::fs::create_dir_all(d.join("tree/sub")).unwrap();
        std::fs::write(d.join("tree/sub/f.txt"), b"1").unwrap();
        std::fs::write(d.join("lone.txt"), b"2").unwrap();
        let t = Arc::new(Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
        guard::with_no_shell(|| {
            let gone = d.join("never-existed.txt");
            assert!(delete_tracked(&[d.join("tree"), d.join("lone.txt"), gone], true, t.clone()).unwrap());
        });
        assert!(!d.join("tree").exists() && !d.join("lone.txt").exists());
        let _ = std::fs::remove_dir_all(&d);
    }

    /// Issue 187: what the shell's engine shows when a copy into a protected folder needs administrator rights, and whether that
    /// window can be seen (visible, in front). Every window it opens is CANCELLED (WM_CLOSE) after a look: nothing is written, no
    /// elevation is asked. A look: `cargo test -p rf-win --lib fileops::tests::protected_copy_look -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn protected_copy_look() {
        use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
        use windows::Win32::UI::WindowsAndMessaging::{
            EnumWindows, GW_OWNER, GetClassNameW, GetForegroundWindow, GetWindow, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible,
            PostMessageW, WM_CLOSE,
        };
        let src = std::env::temp_dir().join("rf-187-look.txt");
        std::fs::write(&src, "x").unwrap();
        let dest = PathBuf::from(r"C:\Program Files (x86)");
        let watcher = std::thread::spawn(|| {
            let me = std::process::id();
            let mut seen = std::collections::HashSet::new();
            for _ in 0..40 {
                std::thread::sleep(std::time::Duration::from_millis(150));
                let mut found: Vec<isize> = Vec::new();
                unsafe extern "system" fn each(h: HWND, l: LPARAM) -> windows::core::BOOL {
                    let v = unsafe { &mut *(l.0 as *mut (u32, Vec<isize>)) };
                    let mut pid = 0;
                    unsafe { GetWindowThreadProcessId(h, Some(&mut pid)) };
                    if pid == v.0 && unsafe { IsWindowVisible(h) }.as_bool() {
                        v.1.push(h.0 as isize);
                    }
                    true.into()
                }
                let mut st: (u32, Vec<isize>) = (me, Vec::new());
                unsafe {
                    let _ = EnumWindows(Some(each), LPARAM(&mut st as *mut _ as isize));
                }
                found.extend(st.1);
                for h in found {
                    let hw = HWND(h as *mut _);
                    if seen.insert(h) {
                        let mut c = [0u16; 64];
                        let mut t = [0u16; 128];
                        let n = unsafe { GetClassNameW(hw, &mut c) } as usize;
                        let m = unsafe { GetWindowTextW(hw, &mut t) } as usize;
                        let owner = unsafe { GetWindow(hw, GW_OWNER) }.map(|o| o.0 as isize).unwrap_or(0);
                        let front = unsafe { GetForegroundWindow() }.0 as isize == h;
                        println!("window {h:#x} class={} title={:?} owner={owner:#x} in_front={front}", String::from_utf16_lossy(&c[..n]), String::from_utf16_lossy(&t[..m]));
                    }
                    std::thread::sleep(std::time::Duration::from_millis(400));
                    let _ = unsafe { PostMessageW(Some(hw), WM_CLOSE, WPARAM(0), LPARAM(0)) };
                }
            }
        });
        // an owner of our own, as the app's window is (`RF_187_OWNER=1`): a plain window, not shown in front of anything
        if std::env::var("RF_187_OWNER").is_ok() {
            use windows::Win32::UI::WindowsAndMessaging::{CreateWindowExW, WINDOW_EX_STYLE, WS_OVERLAPPEDWINDOW};
            // (on a thread that pumps its messages, as the app's window thread does: the dialog talks to its owner)
            let (tx, rx) = std::sync::mpsc::channel::<isize>();
            std::thread::spawn(move || {
                use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, GetMessageW, MSG};
                let owner = unsafe {
                    CreateWindowExW(WINDOW_EX_STYLE(0), windows::core::w!("STATIC"), windows::core::w!("rf-187 owner"), WS_OVERLAPPEDWINDOW, 0, 0, 200, 100, None, None, None, None)
                }
                .unwrap();
                let _ = tx.send(owner.0 as isize);
                let mut msg = MSG::default();
                while unsafe { GetMessageW(&mut msg, None, 0, 0) }.as_bool() {
                    unsafe { DispatchMessageW(&msg) };
                }
            });
            let owner = rx.recv().unwrap();
            println!("owner window {owner:#x}");
            set_dialog_owner(owner);
        }
        if std::env::var("RF_195_NEW_FOLDER").is_ok() {
            // issue 195: a new folder there (the plain call is refused, the engine asks; the watcher cancels its question)
            let r = new_folder(&dest, "rf-195-look");
            println!("new folder: {r:?}; made: {}", dest.join("rf-195-look").exists());
        } else {
            let t = Arc::new(Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
            let r = transfer_tracked(Transfer::Copy, &[src.clone()], &dest, t);
            println!("result: {r:?}; written: {}", dest.join("rf-187-look.txt").exists());
        }
        watcher.join().unwrap();
        let _ = std::fs::remove_file(&src);
    }
}