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.

25.8 KB
Raw Blame
//! Shell actions (open, properties). Each call initializes COM on the calling thread,
//! so run them on a worker thread — shell extensions can block for seconds.

use std::path::Path;

use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, CoInitializeEx};
use windows::Win32::UI::Shell::{
    SEE_MASK_FLAG_NO_UI, SEE_MASK_INVOKEIDLIST, SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW,
};
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
use windows::core::PCWSTR;

use crate::wide::wide;

/// Initializes an STA on the current thread (idempotent; errors ignored when already initialized).
pub fn ensure_com() {
    unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    }
}

thread_local! {
    static UI_THREAD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Marks the calling thread as the interface's (the GPUI thread of the app, DirectLook, the dock), first thing when the app runs.
pub fn mark_ui_thread() {
    UI_THREAD.with(|c| c.set(true));
}

/// Runs `f` on a thread of its own when called on the interface's thread, and waits for it; elsewhere runs it here.
///
/// WHY (a crash log on issue 674, 1.0.5: "RefCell already borrowed", the stack through `ShellExecuteExW`, `CFSFolder`,
/// `CallWindowProcW`): `ShellExecuteEx` can pump the calling thread's messages while it works. On the interface's thread that
/// delivered our own windows' messages while the app was busy handling the click that asked for the launch, and the second borrow
/// of the app panicked. A thread of its own has no windows to pump for; the interface's thread only waits, without pumping.
fn off_ui<R: Send>(f: impl FnOnce() -> R + Send) -> R {
    if !UI_THREAD.with(|c| c.get()) {
        return f();
    }
    std::thread::scope(|s| s.spawn(f).join()).unwrap_or_else(|e| std::panic::resume_unwind(e))
}

fn exec(path: &Path, verb: Option<&str>, args: Option<&str>) -> anyhow::Result<()> {
    off_ui(|| exec_here(path, verb, args))
}

fn exec_here(path: &Path, verb: Option<&str>, args: Option<&str>) -> anyhow::Result<()> {
    ensure_com();
    let file = wide(path);
    let verb_w = verb.map(wide);
    let args_w = args.map(wide);
    let dir = path.parent().map(wide);
    let mut info = SHELLEXECUTEINFOW {
        cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
        fMask: SEE_MASK_INVOKEIDLIST | SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI,
        lpVerb: verb_w.as_ref().map_or(PCWSTR::null(), |v| PCWSTR(v.as_ptr())),
        lpFile: PCWSTR(file.as_ptr()),
        lpParameters: args_w.as_ref().map_or(PCWSTR::null(), |v| PCWSTR(v.as_ptr())),
        lpDirectory: dir.as_ref().map_or(PCWSTR::null(), |v| PCWSTR(v.as_ptr())),
        nShow: SW_SHOWNORMAL.0,
        ..Default::default()
    };
    unsafe { ShellExecuteExW(&mut info)? };
    Ok(())
}

/// Starts a program (an `.exe`, a script, a shortcut) with a command line of its own and a working directory: what "Open with" does
/// for a program the user named. No error box of the shell's: the caller says what went wrong.
pub fn run_program(program: &Path, args: &str, dir: Option<&Path>) -> anyhow::Result<()> {
    off_ui(|| run_program_here(program, args, dir))
}

fn run_program_here(program: &Path, args: &str, dir: Option<&Path>) -> anyhow::Result<()> {
    ensure_com();
    let (file, args_w, dir_w) = (wide(program), wide(args), dir.map(wide));
    let mut info = SHELLEXECUTEINFOW {
        cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
        fMask: SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI,
        lpFile: PCWSTR(file.as_ptr()),
        lpParameters: PCWSTR(args_w.as_ptr()),
        lpDirectory: dir_w.as_ref().map_or(PCWSTR::null(), |v| PCWSTR(v.as_ptr())),
        nShow: SW_SHOWNORMAL.0,
        ..Default::default()
    };
    unsafe { ShellExecuteExW(&mut info)? };
    Ok(())
}

/// Tells Windows that the user opened this file: it goes to Windows' recent items (Home, Start, the jump lists), as a file opened
/// from Explorer does. Windows keeps that list for what Explorer and the file dialogs open; a file opened by another program is in it
/// only when that program says so (issue 341). Nothing happens when the user switched the recent items off.
pub fn note_recent(path: &Path) {
    use windows::Win32::UI::Shell::{SHARD_PATHW, SHAddToRecentDocs};
    // An address (`ftp://user:password@host/...`) is never written to Windows' recent items: it can carry a password, and Windows
    // keeps the list in plain text (a private security report: a closed FTP tab's folder went there).
    if !records_recent(path) {
        return;
    }
    let file = wide(path);
    unsafe { SHAddToRecentDocs(SHARD_PATHW.0 as u32, Some(file.as_ptr().cast())) };
}

/// Whether `path` may go to Windows' recent items: a path on a disk or a share, not an address (anything with `://`).
pub fn records_recent(path: &Path) -> bool {
    !path.to_string_lossy().contains("://")
}

/// Opens a file with its default handler (same as double-click in Explorer).
pub fn open(path: &Path) -> anyhow::Result<()> {
    exec(path, None, None)
}

/// Shows the shell's "Open with" chooser for `path`, and opens the file with the app picked there (with "Always" the app becomes the
/// type's default). Modal: run it on the STA shell thread.
///
/// Through `SHOpenWithDialog`, not the `openas` verb: types such as `.cmd`, `.bat` and `.exe` have no `openas` verb, and asking for
/// it failed without a word (issue 207: "When I do a right click on a .cmd file and select open with, nothing appear"). The verb is
/// still tried when the chooser cannot be shown at all. Cancelling the chooser is not an error.
pub fn open_with(path: &Path) -> anyhow::Result<()> {
    use windows::Win32::Foundation::ERROR_CANCELLED;
    use windows::Win32::UI::Shell::{OAIF_ALLOW_REGISTRATION, OAIF_EXEC, OPENASINFO, SHOpenWithDialog};
    ensure_com();
    let file = wide(path);
    let info = OPENASINFO { pcszFile: PCWSTR(file.as_ptr()), pcszClass: PCWSTR::null(), oaifInFlags: OAIF_ALLOW_REGISTRATION | OAIF_EXEC };
    // SAFETY: info and the path buffer outlive the modal call
    match unsafe { SHOpenWithDialog(None, &info) } {
        Ok(()) => Ok(()),
        Err(e) if e.code() == ERROR_CANCELLED.to_hresult() => Ok(()),
        Err(e) => {
            log::warn!("open with: the chooser could not be shown ({e}); trying the openas verb");
            exec(path, Some("openas"), None)
        }
    }
}

/// Shows the Windows properties dialog for the item.
pub fn properties(path: &Path) -> anyhow::Result<()> {
    exec(path, Some("properties"), None)
}

/// Settings > Developer tools > "Terminal": the program "Open in Terminal" starts (issue 224). Empty: Windows Terminal, else PowerShell.
static TERMINAL: std::sync::Mutex<String> = std::sync::Mutex::new(String::new());

/// Sets the terminal [`open_terminal`] starts: a program's path or name (`cmd.exe`, `pwsh.exe`, `C:\Tools\Cmder\Cmder.exe`), or empty
/// for the automatic one.
pub fn set_terminal(program: &str) {
    *TERMINAL.lock().unwrap_or_else(|e| e.into_inner()) = program.trim().trim_matches('"').to_string();
}

/// The arguments that make a terminal `program` (its file name, lower case) start in `dir`, for the ones that do not take the folder
/// they are started in (Cmder and ConEmu keep their own start folder). Others are only started in `dir`.
///
/// `wt_ps`: Windows Terminal's default profile is Windows PowerShell (see [`ps_misreads`]).
fn terminal_dir_args(program: &str, dir: &str, wt_ps: bool) -> Vec<String> {
    match program {
        "cmder.exe" => vec!["/START".into(), dir.into()],
        "conemu.exe" | "conemu64.exe" => vec!["-Dir".into(), dir.into()],
        "wt.exe" | "windowsterminal.exe" => wt_start_args(dir, wt_ps),
        "wezterm.exe" | "wezterm-gui.exe" => vec!["start".into(), "--cwd".into(), dir.into()],
        "alacritty.exe" => vec!["--working-directory".into(), dir.into()],
        "powershell.exe" => ps_start_args(dir),
        "pwsh.exe" => vec!["-NoExit".into()],
        _ => Vec::new(),
    }
}

/// Opens a terminal in `dir`: the one chosen in Settings, else Windows Terminal if present, else PowerShell.
pub fn open_terminal(dir: &Path) -> anyhow::Result<()> {
    off_ui(|| open_terminal_here(dir))
}

fn open_terminal_here(dir: &Path) -> anyhow::Result<()> {
    let chosen = TERMINAL.lock().unwrap_or_else(|e| e.into_inner()).clone();
    let wt_ps = ps_misreads(&dir.to_string_lossy()) && wt_default_is_windows_powershell();
    if !chosen.is_empty() {
        let name = Path::new(&chosen).file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
        let name = if name.ends_with(".exe") || name.contains('.') { name } else { format!("{name}.exe") };
        let args = terminal_dir_args(&name, &dir.to_string_lossy(), wt_ps);
        match std::process::Command::new(&chosen).args(&args).current_dir(dir).spawn() {
            Ok(_) => return Ok(()),
            // (a terminal that is gone: the automatic one rather than nothing)
            Err(e) => log::warn!("terminal {chosen}: {e}"),
        }
    }
    let d = dir.to_string_lossy();
    let wt = match windows_terminal() {
        Some(wt) => std::process::Command::new(wt).args(wt_start_args(&d, wt_ps)).spawn().is_ok(),
        None => false,
    };
    if !wt {
        std::process::Command::new(powershell()).args(ps_start_args(&d)).current_dir(dir).spawn()?;
    }
    Ok(())
}

/// Whether Windows PowerShell 5.1 does not come up in `dir` when it is only started there.
///
/// WHY (issue 1091: "The Open in Terminal in a tab does not work if the path contains square brackets"). Windows PowerShell 5.1
/// reads the folder it is started in as a wildcard pattern. In `C:\Downloads\[TEST]` the brackets are a set of letters that
/// matches no folder, and it comes up in its own program folder (`System32\WindowsPowerShell\v1.0`) with no error. Measured here on
/// 2026-12-04, started directly and as a tab of Windows Terminal 1.25 (`-d`); a backtick in the name does no harm. Told the folder
/// with `Set-Location -LiteralPath` it lands in it, started either way. PowerShell 7 (`pwsh.exe`) was not tried and is left as it was.
fn ps_misreads(dir: &str) -> bool {
    dir.contains(['[', ']'])
}

/// The PowerShell command that goes to `dir`, whatever letters its name has.
fn ps_go_to(dir: &str) -> String {
    format!("Set-Location -LiteralPath '{}'", ps_single_quoted(dir))
}

/// Windows PowerShell's arguments for a start in `dir` (it is started there too): told the folder itself where it would misread it.
fn ps_start_args(dir: &str) -> Vec<String> {
    let mut args = vec!["-NoExit".to_string()];
    if ps_misreads(dir) {
        args.extend(["-Command".to_string(), ps_go_to(dir)]);
    }
    args
}

/// Windows Terminal's arguments for a tab in `dir`. Where its default profile is Windows PowerShell (`wt_ps`) and that would
/// misread the folder, the tab is given Windows PowerShell with the folder told: a command line with no `-p` still gets the default
/// profile's look, only its program line is replaced. A semicolon is escaped in the command as in `-d` ([`wt_escaped`]).
fn wt_start_args(dir: &str, wt_ps: bool) -> Vec<String> {
    let mut args = vec!["-d".to_string(), wt_escaped(dir)];
    if wt_ps && ps_misreads(dir) {
        args.push(powershell().to_string_lossy().into_owned());
        args.extend(ps_start_args(dir).iter().map(|a| wt_escaped(a)));
    }
    args
}

/// The built-in "Windows PowerShell" profile of Windows Terminal: the same id on every PC.
const WT_WINDOWS_POWERSHELL: &str = "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}";

/// `defaultProfile` out of the text of Windows Terminal's settings.json (an id, or a profile's name). Pure.
fn wt_default_profile(settings: &str) -> Option<&str> {
    const KEY: &str = "\"defaultProfile\"";
    let rest = &settings[settings.find(KEY)? + KEY.len()..];
    let rest = rest.trim_start().strip_prefix(':')?.trim_start().strip_prefix('"')?;
    Some(&rest[..rest.find('"')?])
}

/// Whether a tab of Windows Terminal starts Windows PowerShell: the settings of the installed one, the Preview or an unpackaged
/// copy, in that order. No settings file (never started) or another profile: no, and the tab is opened as before.
fn wt_default_is_windows_powershell() -> bool {
    let Some(local) = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from) else { return false };
    [
        r"Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json",
        r"Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json",
        r"Microsoft\Windows Terminal\settings.json",
    ]
    .iter()
    .find_map(|p| std::fs::read_to_string(local.join(p)).ok())
    .and_then(|s| wt_default_profile(&s).map(|d| d.eq_ignore_ascii_case(WT_WINDOWS_POWERSHELL) || d.eq_ignore_ascii_case("Windows PowerShell")))
    .unwrap_or(false)
}

/// Windows Terminal by its full path (the app alias Windows puts in the user's WindowsApps folder), `None` when it is not installed.
///
/// The programs are named by their full paths: a bare name is looked for in more places than Windows' own (issue 422).
fn windows_terminal() -> Option<std::path::PathBuf> {
    let p = std::path::PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join(r"Microsoft\WindowsApps\wt.exe");
    // (the alias is a reparse point of its own kind: looked at itself, not followed)
    std::fs::symlink_metadata(&p).is_ok().then_some(p)
}

/// Windows PowerShell by its full path in the Windows folder (see [`windows_terminal`] for why).
fn powershell() -> std::path::PathBuf {
    let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from(r"C:\Windows"));
    root.join(r"System32\WindowsPowerShell\v1.0\powershell.exe")
}

/// A folder for Windows Terminal's `-d`: Windows Terminal reads `;` as a separator of its own, even inside an argument; `\;` is its
/// escape for a plain semicolon (issue 422).
fn wt_escaped(dir: &str) -> String {
    dir.replace(';', r"\;")
}

/// A text inside a PowerShell single-quoted string: PowerShell takes the typographic single quotes (‘ ’ ‚ ‛) for quote marks as well
/// as `'`, so each of them is doubled, as PowerShell escapes any of them (issue 422).
fn ps_single_quoted(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for c in s.chars() {
        if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
            out.push(c);
        }
        out.push(c);
    }
    out
}

/// Opens an elevated terminal in `dir` (Windows asks for permission: UAC). Windows Terminal if
/// present, else PowerShell. Declining the permission prompt is not an error.
pub fn open_terminal_admin(dir: &Path) -> anyhow::Result<()> {
    off_ui(|| open_terminal_admin_here(dir))
}

fn open_terminal_admin_here(dir: &Path) -> anyhow::Result<()> {
    let run = |file: &str, args: &str| -> windows::core::Result<()> {
        ensure_com();
        let (file, args, verb, cwd) = (wide(file), wide(args), wide("runas"), wide(dir));
        let mut info = SHELLEXECUTEINFOW {
            cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
            fMask: SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI,
            lpVerb: PCWSTR(verb.as_ptr()),
            lpFile: PCWSTR(file.as_ptr()),
            lpParameters: PCWSTR(args.as_ptr()),
            lpDirectory: PCWSTR(cwd.as_ptr()),
            nShow: SW_SHOWNORMAL.0,
            ..Default::default()
        };
        unsafe { ShellExecuteExW(&mut info) }
    };
    // ERROR_CANCELLED: the user said no at the prompt (asking again with PowerShell would nag)
    let declined = |e: &windows::core::Error| e.code().0 as u32 == 0x8007_04C7;
    // (both by their full paths: see `windows_terminal`)
    let first = match windows_terminal() {
        Some(wt) => run(&wt.to_string_lossy(), &terminal_args(dir, ps_misreads(&dir.to_string_lossy()) && wt_default_is_windows_powershell())),
        None => Err(windows::core::Error::from(windows::Win32::Foundation::ERROR_FILE_NOT_FOUND.to_hresult())),
    };
    match first {
        Ok(()) => Ok(()),
        Err(e) if declined(&e) => Ok(()),
        Err(_) => match run(&powershell().to_string_lossy(), &powershell_args(dir)) {
            Ok(()) => Ok(()),
            Err(e) if declined(&e) => Ok(()),
            Err(e) => Err(e.into()),
        },
    }
}

/// `-d "C:\some dir"` for Windows Terminal. A trailing backslash would escape the closing
/// quote (`"C:\"`), so it is doubled. With `wt_ps`, for a folder Windows PowerShell would misread, the tab is given Windows
/// PowerShell with the folder told, as in [`wt_start_args`] (issue 1091; this line was tried without the elevation only).
fn terminal_args(dir: &Path, wt_ps: bool) -> String {
    let d = wt_escaped(&dir.to_string_lossy());
    let tail = if d.ends_with('\\') { "\\" } else { "" };
    let ps = if wt_ps && ps_misreads(&d) { format!(" \"{}\" {}", powershell().display(), wt_escaped(&powershell_args(dir))) } else { String::new() };
    format!("-d \"{d}{tail}\"{ps}")
}

/// An elevated process starts in System32 whatever directory is asked for: PowerShell is told
/// to go to the folder itself (single quotes doubled, as PowerShell escapes them).
fn powershell_args(dir: &Path) -> String {
    format!("-NoExit -Command \"{}\"", ps_go_to(&dir.to_string_lossy()))
}

/// `shell:Downloads`, `shell:startup`, `shell:sendto`… → file-system path (None for virtual
/// folders like `shell:RecycleBinFolder`). Blocking (shell namespace): off the UI thread.
pub fn resolve_shell_path(s: &str) -> Option<std::path::PathBuf> {
    use windows::Win32::UI::Shell::{IShellItem, SHCreateItemFromParsingName, SIGDN_FILESYSPATH};
    ensure_com();
    let w = crate::wide::wide(s.trim());
    unsafe {
        let item: IShellItem = SHCreateItemFromParsingName(windows::core::PCWSTR(w.as_ptr()), None).ok()?;
        let p = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
        let out = p.to_string().ok();
        windows::Win32::System::Com::CoTaskMemFree(Some(p.0 as *const _));
        out.map(std::path::PathBuf::from)
    }
}

#[cfg(test)]
mod shell_path_tests {
    #[test]
    fn resolves_known_shell_paths() {
        let p = super::resolve_shell_path("shell:Windows").expect("shell:Windows");
        assert!(p.to_string_lossy().to_lowercase().ends_with("windows"), "{p:?}");
        assert!(super::resolve_shell_path("shell:RecycleBinFolder").is_none());
    }
}

/// No "There is no disk in the drive" / "Insert a disk" system boxes when touching an empty
/// card reader or an ejected disc: such calls just fail (and the app shows "drive not ready").
/// Process-wide; call once at startup.
pub fn suppress_critical_error_dialogs() {
    use windows::Win32::System::Diagnostics::Debug::{SEM_FAILCRITICALERRORS, SEM_NOOPENFILEERRORBOX, SetErrorMode};
    unsafe {
        SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
    }
}

/// Tells the shell (Explorer windows, desktop, file dialogs) that `dir`'s contents changed,
/// the way the shell's own copy engine does when it finishes.
pub fn notify_updated(dir: &std::path::Path) {
    use windows::Win32::UI::Shell::{SHCNE_UPDATEDIR, SHCNF_PATHW, SHChangeNotify};
    let w = crate::wide::wide(dir);
    // SAFETY: a NUL-terminated wide path, read during the call
    unsafe { SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATHW, Some(w.as_ptr() as *const _), None) };
}

/// Explorer's "Change..." next to "Opens with": the shell's app chooser for `path`, which on OK makes the
/// chosen app the default for the extension (OAIF_REGISTER_EXT + OAIF_FORCE_REGISTRATION) without opening the
/// file (no OAIF_EXEC). Modal: run it on the STA shell thread.
pub fn open_with_dialog(owner: windows::Win32::Foundation::HWND, path: &Path) -> anyhow::Result<()> {
    use windows::Win32::UI::Shell::{OAIF_ALLOW_REGISTRATION, OAIF_FORCE_REGISTRATION, OAIF_REGISTER_EXT, OPENASINFO, SHOpenWithDialog};
    ensure_com();
    let file = wide(path);
    let info = OPENASINFO { pcszFile: PCWSTR(file.as_ptr()), pcszClass: PCWSTR::null(), oaifInFlags: OAIF_ALLOW_REGISTRATION | OAIF_REGISTER_EXT | OAIF_FORCE_REGISTRATION };
    // SAFETY: info and the path buffer outlive the modal call
    unsafe { SHOpenWithDialog(Some(owner), &info)? };
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    /// a private security report: an FTP address (which can hold a password) never goes to Windows' recent items.
    #[test]
    fn addresses_are_not_recorded_as_recent() {
        assert!(super::records_recent(Path::new(r"C:\Users\me\Documents")));
        assert!(super::records_recent(Path::new(r"\\nas\share\folder")));
        assert!(!super::records_recent(Path::new("ftp://user:[email protected]/pub")));
        assert!(!super::records_recent(Path::new("ftp://example.com/pub")));
    }

    #[test]
    fn elevated_terminal_arguments() {
        assert_eq!(super::terminal_args(Path::new(r"C:\Users\a b"), false), r#"-d "C:\Users\a b""#);
        // a drive root: the backslash must not escape the closing quote
        assert_eq!(super::terminal_args(Path::new(r"D:\"), false), r#"-d "D:\\""#);
        assert_eq!(super::powershell_args(Path::new(r"C:\it's")), r#"-NoExit -Command "Set-Location -LiteralPath 'C:\it''s'""#);
    }

    /// Issue 422: a folder's name stays one folder name in the terminal's arguments.
    #[test]
    fn a_folder_name_stays_a_folder_name_in_the_elevated_terminal() {
        // PowerShell's typographic single quotes are doubled like the plain one
        let ps = super::powershell_args(Path::new("C:\\x\u{2019}y\u{2018}"));
        assert_eq!(ps, "-NoExit -Command \"Set-Location -LiteralPath 'C:\\x\u{2019}\u{2019}y\u{2018}\u{2018}'\"");
        for q in ['\u{201A}', '\u{201B}'] {
            assert_eq!(super::ps_single_quoted(&q.to_string()), format!("{q}{q}"));
        }
        // Windows Terminal's separator is escaped
        assert_eq!(super::terminal_args(Path::new(r"C:\a;b"), false), r#"-d "C:\a\;b""#);
        // and the programs are named by their full paths
        assert!(super::powershell().is_absolute());
        assert!(super::powershell().ends_with(r"WindowsPowerShell\v1.0\powershell.exe"));
    }
}

#[cfg(test)]
mod terminal_tests {
    use super::terminal_dir_args;

    #[test]
    fn terminals_that_keep_their_own_start_folder_are_told_the_folder() {
        assert_eq!(terminal_dir_args("cmder.exe", r"C:\work", false), ["/START", r"C:\work"]);
        assert_eq!(terminal_dir_args("conemu64.exe", r"C:\work", false), ["-Dir", r"C:\work"]);
        assert_eq!(terminal_dir_args("wt.exe", r"C:\work", false), ["-d", r"C:\work"]);
        assert!(terminal_dir_args("cmd.exe", r"C:\work", false).is_empty());
    }

    /// Issue 1091: Windows PowerShell 5.1 comes up in its own folder when it is only started in `C:\dl\[TEST]`.
    #[test]
    fn windows_powershell_is_told_a_folder_with_square_brackets_itself() {
        let go = r"Set-Location -LiteralPath 'C:\dl\[TEST]'";
        assert_eq!(terminal_dir_args("powershell.exe", r"C:\dl\[TEST]", false), ["-NoExit", "-Command", go]);
        // any other folder: started there and nothing more, as before
        assert_eq!(terminal_dir_args("powershell.exe", r"C:\dl\a`b", false), ["-NoExit"]);
        assert_eq!(terminal_dir_args("pwsh.exe", r"C:\dl\[TEST]", false), ["-NoExit"]);
        // Windows Terminal: only where its tab is Windows PowerShell
        let ps = super::powershell().to_string_lossy().into_owned();
        assert_eq!(terminal_dir_args("wt.exe", r"C:\dl\[TEST]", true), ["-d", r"C:\dl\[TEST]", ps.as_str(), "-NoExit", "-Command", go]);
        assert_eq!(terminal_dir_args("wt.exe", r"C:\dl\[TEST]", false), ["-d", r"C:\dl\[TEST]"]);
        assert_eq!(terminal_dir_args("wt.exe", r"C:\work", true), ["-d", r"C:\work"]);
        // its separator is escaped in the command as in the folder, and a quote is doubled for PowerShell
        let args = terminal_dir_args("wt.exe", r"C:\it's [a;b]", true);
        assert_eq!(args[1], r"C:\it's [a\;b]");
        assert_eq!(args[5], r"Set-Location -LiteralPath 'C:\it''s [a\;b]'");
        // the elevated line
        assert_eq!(
            super::terminal_args(std::path::Path::new(r"C:\dl\[TEST]"), true),
            format!(r#"-d "C:\dl\[TEST]" "{ps}" -NoExit -Command "{go}""#)
        );
        assert_eq!(super::terminal_args(std::path::Path::new(r"C:\work"), true), r#"-d "C:\work""#);
    }

    #[test]
    fn the_default_profile_is_read_out_of_windows_terminals_settings() {
        let text = "{\n    \"$help\": \"x\",\n    \"defaultProfile\": \"{61C54BBD-c2c6-5271-96e7-009a87ff44bf}\",\n    \"profiles\": {}\n}";
        assert!(super::wt_default_profile(text).is_some_and(|d| d.eq_ignore_ascii_case(super::WT_WINDOWS_POWERSHELL)));
        assert_eq!(super::wt_default_profile("{ \"defaultProfile\" : \"Ubuntu\" }"), Some("Ubuntu"));
        assert_eq!(super::wt_default_profile("{ \"profiles\": {} }"), None);
        assert_eq!(super::wt_default_profile("{ \"defaultProfile\": 3 }"), None);
    }
}

#[cfg(test)]
mod recent_tests {
    /// Live: one shortcut is written to this PC's recent items and taken out again. Windows leaves out files in the temporary
    /// folder, so the file stands beside the test program.
    #[test]
    #[ignore = "writes one entry to this PC's recent items and removes it again"]
    fn a_noted_file_is_one_of_windows_recent_items() {
        let dir = std::env::current_exe().unwrap().parent().unwrap().join("rf-recent-probe");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("rf-recent-probe-341.txt");
        std::fs::write(&file, "probe").unwrap();
        let link = crate::dock::startrecent::recent_dir().unwrap().join("rf-recent-probe-341.txt.lnk");
        let _ = std::fs::remove_file(&link);
        super::note_recent(&file);
        let t = std::time::Instant::now();
        while !link.exists() && t.elapsed() < std::time::Duration::from_secs(5) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        let there = link.exists();
        let _ = std::fs::remove_file(&link);
        let _ = std::fs::remove_dir_all(&dir);
        assert!(there, "no shortcut in the recent items after {:?}", t.elapsed());
    }
}