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.

9.2 KB
Raw Blame
//! Shared Windows launch path for toolbar commands and file drops.

use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

use gpui_kit::{App, Window};

use crate::i18n::tx;

pub(crate) fn split_arguments(text: &str) -> anyhow::Result<Vec<OsString>> {
    use std::os::windows::ffi::{OsStrExt, OsStringExt};
    use windows::Win32::Foundation::{HLOCAL, LocalFree};
    use windows::Win32::UI::Shell::CommandLineToArgvW;
    use windows::core::PCWSTR;

    // Windows parses argv[0] differently, so supply a dummy executable name.
    anyhow::ensure!(!text.contains('\0'), "Invalid command arguments");
    let line = format!("program {text}");
    let wide: Vec<u16> = OsStr::new(&line).encode_wide().chain([0]).collect();
    let mut count = 0;
    unsafe {
        let argv = CommandLineToArgvW(PCWSTR(wide.as_ptr()), &mut count);
        if argv.is_null() {
            return Err(std::io::Error::last_os_error().into());
        }
        let args = std::slice::from_raw_parts(argv, count as usize).iter().skip(1)
            .map(|p| OsString::from_wide(p.as_wide())).collect();
        let _ = LocalFree(Some(HLOCAL(argv.cast())));
        Ok(args)
    }
}

pub(crate) fn accepts_program(path: &Path) -> bool {
    path.extension().is_some_and(|e| ["exe", "com", "bat", "cmd", "lnk"].iter().any(|ext| e.eq_ignore_ascii_case(ext)))
}

/// Whether files dropped on `path` go to its type's drop handler, as Explorer gives them (a Python script runs with them, a zip takes
/// them in; issue 865). Programs and shortcuts are not asked here: [`accepts_program`] starts them itself. Remembered per extension
/// for a minute: every row of the list asks while it is drawn, and a type installed meanwhile is seen soon enough.
pub(crate) fn takes_drops(path: &Path) -> bool {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};
    use std::time::{Duration, Instant};
    static SEEN: OnceLock<Mutex<HashMap<String, (bool, Instant)>>> = OnceLock::new();
    let Some(ext) = path.extension().map(|e| e.to_string_lossy().to_lowercase()) else { return false };
    let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
    if let Some(&(yes, at)) = seen.get(&ext)
        && at.elapsed() < Duration::from_secs(60)
    {
        return yes;
    }
    let yes = rf_win::fileactions::has_drop_handler(path);
    seen.insert(ext, (yes, Instant::now()));
    yes
}

/// Starts an executable or a batch script, or returns the directory a shortcut points to.
/// Run off the UI thread. Paths are passed as individual arguments.
pub(crate) fn launch(program: PathBuf, arguments: Vec<OsString>, uses_paths: bool, folder: Option<PathBuf>) -> anyhow::Result<Option<PathBuf>> {
    let (exe, existing, working_dir) = if program.extension().is_some_and(|e| e.eq_ignore_ascii_case("lnk")) {
        let shortcut = rf_win::shortcut::resolve(&program)?;
        if shortcut.target.is_dir() {
            return Ok(Some(shortcut.target));
        }
        (shortcut.target, split_arguments(&shortcut.args)?, Some(shortcut.working_dir))
    } else {
        (program, Vec::new(), None)
    };
    anyhow::ensure!(exe.is_absolute() && accepts_program(&exe) && rf_win::runfind::is_program_file(&exe),
        "{}", tx("Program bulunamadı.", "Program not found."));
    // Command can quote paths for an executable or a batch file. Explicit shell command
    // evaluation has its own syntax and must not interpret characters from filenames.
    if uses_paths && exe.file_stem().is_some_and(|s| s.eq_ignore_ascii_case("cmd")) {
        anyhow::ensure!(!arguments.iter().any(|a| a.to_string_lossy().contains(['&', '|', '<', '>', '^', '%', '!', '(', ')', '"', '\r', '\n'])),
            "{}", tx("Bu bağımsız değişkenleri doğrudan bir .bat veya .cmd dosyasına verin.", "Pass these arguments directly to a .bat or .cmd file."));
    }
    if uses_paths && exe.file_stem().is_some_and(|s| s.eq_ignore_ascii_case("powershell") || s.eq_ignore_ascii_case("pwsh")) {
        let all: Vec<String> = existing.iter().chain(&arguments).map(|a| a.to_string_lossy().into_owned()).collect();
        anyhow::ensure!(powershell_runs_a_file(&all), "{}", tx("Dosya yollarını geçirmek için PowerShell -File kullanın.", "Use PowerShell -File to pass file paths."));
    }
    let mut command = std::process::Command::new(&exe);
    command.args(existing).args(arguments);
    if let Some(dir) = working_dir.filter(|p| p.is_dir()).or(folder).or_else(|| exe.parent().map(Path::to_path_buf)) {
        command.current_dir(dir);
    }
    command.spawn()?;
    Ok(None)
}

/// Whether PowerShell, given `args`, runs a script FILE with what follows as its arguments, so that a file name among them is never
/// read as PowerShell (`$(calc).txt`). An allowlist (a private security report showed a list of refused switches missed `/c`, `–c` with
/// another dash, `-cwa`, `-commandw` and plain arguments, which Windows PowerShell takes as a command): the `-File` switch must come,
/// and before it only switches that are not a command and the values of the few that take one.
pub(crate) fn powershell_runs_a_file(args: &[String]) -> bool {
    // a switch's name: after `-`, `/` or another dash (PowerShell takes the en and em dashes and the horizontal bar too)
    let switch = |a: &str| -> Option<String> {
        let t = a.trim_start_matches(['-', '/', '\u{2013}', '\u{2014}', '\u{2015}']);
        (t.len() < a.len() && !t.is_empty()).then(|| t.to_ascii_lowercase())
    };
    let is = |name: &str, full: &str, shortest: usize| name.len() >= shortest && full.starts_with(name);
    // switches that take a value (the next argument)
    let takes_value = |n: &str| {
        is(n, "executionpolicy", 2) || n == "ep" || is(n, "windowstyle", 1) || is(n, "workingdirectory", 2) || n == "wd" || is(n, "configurationname", 4)
            || is(n, "inputformat", 2) || is(n, "outputformat", 2) || is(n, "settingsfile", 2) || is(n, "version", 1)
    };
    let mut value_next = false;
    for a in args {
        if value_next {
            value_next = false;
            continue;
        }
        let Some(n) = switch(a) else { return false };
        // -File: what follows is the script and its arguments
        if is(&n, "file", 1) {
            return true;
        }
        if takes_value(&n) {
            value_next = true;
            continue;
        }
        // anything that is or may be a command
        if n.starts_with('c') || n.starts_with('e') || n == "cwa" {
            return false;
        }
    }
    false
}

pub(crate) fn launch_error(error: anyhow::Error, window: &mut Window, cx: &mut App) {
    crate::prompt::notice(tx("Program başlatılamadı", "Could not start the program"), error.to_string(), window, cx);
}

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

    #[test]
    fn powershell_takes_paths_only_after_file() {
        let ok = |v: &[&str]| super::powershell_runs_a_file(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>());
        assert!(ok(&["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "C:/s.ps1", "$(calc).txt"]));
        assert!(ok(&["-f", "C:/s.ps1", "x"]));
        assert!(ok(&["/File", "C:/s.ps1"]));
        assert!(!ok(&["C:/x/$(calc).txt"]), "a plain argument is a command to Windows PowerShell");
        assert!(!ok(&["-Command", "Get-Item", "x"]));
        assert!(!ok(&["/c", "x"]));
        assert!(!ok(&["\u{2013}c", "x"]), "another dash");
        assert!(!ok(&["-cwa", "x"]));
        assert!(!ok(&["-commandw", "x"]));
        assert!(!ok(&["-EncodedCommand", "AAA"]));
        assert!(!ok(&["-NoProfile"]), "no -File at all");
    }

    #[test]
    fn batch_shortcut_receives_a_file_path_with_spaces_and_ampersand() {
        let dir = std::env::temp_dir().join(format!("rf-quick-command-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let input = dir.join("file & name.txt");
        let output = dir.join("copied.txt");
        let batch = dir.join("receive.bat");
        let shortcut = dir.join("receive.lnk");
        std::fs::write(&input, "test data").unwrap();
        std::fs::write(&batch, b"@copy /Y \"%~1\" \"%~dp0copied.txt\" >nul\r\n").unwrap();
        rf_win::shortcut::create(&shortcut, &batch).unwrap();
        assert_eq!(launch(shortcut, vec![input.into_os_string()], true, None).unwrap(), None);
        let until = std::time::Instant::now() + std::time::Duration::from_secs(4);
        let copied = loop {
            if let Ok(contents) = std::fs::read_to_string(&output)
                && !contents.is_empty()
            {
                break contents;
            }
            assert!(std::time::Instant::now() < until, "the batch file did not copy the argument");
            std::thread::sleep(std::time::Duration::from_millis(20));
        };
        assert_eq!(copied, "test data");

        // cmd.exe can still hold the batch file open after writing the output.
        let until = std::time::Instant::now() + std::time::Duration::from_secs(4);
        loop {
            match std::fs::remove_dir_all(&dir) {
                Ok(()) => break,
                Err(err) if err.raw_os_error() == Some(32) && std::time::Instant::now() < until => {
                    std::thread::sleep(std::time::Duration::from_millis(20));
                }
                Err(err) => panic!("could not clean up the batch test: {err}"),
            }
        }
    }
}