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.

6.9 KB
Raw Blame
//! Settings › Advanced › "rustyfiles as the Windows shell" (experimental): the per-user Winlogon `Shell` value, which Windows reads at
//! sign-in instead of starting Explorer. It names `rustyfiles-shellguard.exe`, the watchdog that starts rustyfiles' shell and gives the
//! user Explorer back when it cannot (a crash loop, Safe Mode, Shift held at sign-in: see rf-shellguard's `machine`).
//!
//! Only `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell` is written or deleted: one value of the user's own, no
//! administrator rights, nothing machine-wide. It takes effect at the next sign-in; switching it off and signing out again brings
//! Explorer back. A running Explorer is never closed from here (on this PC, closing Explorer could hang its process: notes of
//! 2026-11-12).

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

const WINLOGON: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Winlogon";

/// The guard's file name, next to rustyfiles.exe in an installed copy.
pub const GUARD_FILE: &str = "rustyfiles-shellguard.exe";

/// The guard next to `exe` (rustyfiles.exe), when there is one: a build without it (a development build) cannot offer the switch.
pub fn guard_next_to(exe: &Path) -> Option<PathBuf> {
    Some(exe.parent()?.join(GUARD_FILE)).filter(|g| g.is_file())
}

/// The value written for `guard`: its path in quotes (a path with spaces is one program to Winlogon then).
pub fn value_for(guard: &Path) -> String {
    format!("\"{}\"", guard.display())
}

/// Whether `value` (the `Shell` value as read) names `guard`, quoted or not, in any letter case.
pub fn names_guard(value: &str, guard: &Path) -> bool {
    let v = value.trim().trim_matches('"');
    v.eq_ignore_ascii_case(&guard.display().to_string())
}

/// The user's `Shell` value now, when there is one.
pub fn current() -> Option<String> {
    windows_registry::CURRENT_USER.open(WINLOGON).ok()?.get_string("Shell").ok().filter(|v| !v.trim().is_empty())
}

/// Whether the switch is on: the user's `Shell` value names this guard.
pub fn is_on(guard: &Path) -> bool {
    current().is_some_and(|v| names_guard(&v, guard))
}

/// Turns it on (from the next sign-in) or off (Explorer at the next sign-in). Off deletes the value only when it names a guard of
/// ours: a shell the user set up some other way is left alone.
pub fn set(guard: &Path, on: bool) -> windows::core::Result<()> {
    let key = windows_registry::CURRENT_USER.create(WINLOGON)?;
    if on {
        key.set_string("Shell", value_for(guard))
    } else {
        match key.get_string("Shell") {
            Ok(v) if v.to_ascii_lowercase().contains(&GUARD_FILE.to_ascii_lowercase()) => key.remove_value("Shell"),
            _ => Ok(()),
        }
    }
}

/// Whether a `Shell` value (as read) is one of ours: it names the guard, wherever that copy was installed. Pure.
pub fn is_ours(value: &str) -> bool {
    value.to_ascii_lowercase().contains(&GUARD_FILE.to_ascii_lowercase())
}

/// Whether Explorer is this session's shell right now: the shell's window is a visible window of an explorer.exe process.
pub fn explorer_is_shell() -> bool {
    use windows::Win32::Foundation::CloseHandle;
    use windows::Win32::System::Threading::{OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW};
    use windows::Win32::UI::WindowsAndMessaging::{GetShellWindow, GetWindowThreadProcessId, IsWindowVisible};
    // SAFETY: plain queries; the process handle is closed here.
    unsafe {
        let hwnd = GetShellWindow();
        if hwnd.0.is_null() || !IsWindowVisible(hwnd).as_bool() {
            return false;
        }
        let mut pid = 0u32;
        GetWindowThreadProcessId(hwnd, Some(&mut pid));
        let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return false };
        let mut buf = [0u16; 1024];
        let mut len = buf.len() as u32;
        let named = QueryFullProcessImageNameW(process, PROCESS_NAME_WIN32, windows::core::PWSTR(buf.as_mut_ptr()), &mut len).is_ok();
        let _ = CloseHandle(process);
        named && Path::new(&String::from_utf16_lossy(&buf[..len as usize])).file_name().is_some_and(|n| n.eq_ignore_ascii_case("explorer.exe"))
    }
}

/// At uninstall: Windows gets Explorer back. Returns whether the switch was on.
///
/// WHY (issue 1086: "Uninstall leaves HKCU\...\Winlogon\Shell pointing to deleted rustyfiles-shellguard.exe"). The uninstall took
/// every other change in Windows back but not this one, so the next sign-in tried to start a file that was gone and the user had
/// no desktop and no taskbar until the value was deleted by hand. The value goes first, which is what the next sign-in reads. And
/// when rustyfiles is the shell of THIS session, Explorer is started so that the session is not left with no shell either: with
/// the value gone and no shell running, a started explorer.exe becomes the shell. When Explorer is the shell already (the switch
/// was only set for the next sign-in) nothing is started: a second explorer.exe would just open a folder window.
/// NOT tried on a session whose shell is rustyfiles (the real shell is never switched on this PC).
pub fn undo_for_uninstall() -> bool {
    if !current().is_some_and(|v| is_ours(&v)) {
        return false;
    }
    if let Err(e) = set(Path::new(""), false) {
        log::warn!("uninstall: the Winlogon Shell value could not be removed: {e}");
    }
    if !explorer_is_shell() {
        let root = std::env::var_os("SystemRoot").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
        if let Err(e) = std::process::Command::new(root.join("explorer.exe")).spawn() {
            log::warn!("uninstall: Explorer could not be started: {e}");
        }
    }
    true
}

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

    #[test]
    fn a_shell_value_is_ours_when_it_names_the_guard_wherever_it_was_installed() {
        assert!(is_ours(r#""C:\Users\Me\AppData\Local\rustyfiles\current\rustyfiles-shellguard.exe""#));
        assert!(is_ours(r"D:\Apps\RUSTYFILES-SHELLGUARD.EXE"));
        assert!(!is_ours("explorer.exe"));
        assert!(!is_ours(r"C:\Program Files\OtherShell\shell.exe"));
    }

    /// (on a developer's or CI's ordinary session Explorer is the shell; where the tests run with no desktop there is no shell
    /// window at all and the answer is no)
    #[test]
    fn the_shell_question_answers_without_failing() {
        let _ = explorer_is_shell();
    }

    #[test]
    fn the_value_is_the_guard_in_quotes_and_is_recognised_either_way() {
        let g = Path::new(r"C:\Users\Me\AppData\Local\rustyfiles\current\rustyfiles-shellguard.exe");
        assert_eq!(value_for(g), r#""C:\Users\Me\AppData\Local\rustyfiles\current\rustyfiles-shellguard.exe""#);
        assert!(names_guard(&value_for(g), g));
        assert!(names_guard(r"c:\users\me\appdata\local\rustyfiles\current\RUSTYFILES-SHELLGUARD.EXE", g));
        assert!(!names_guard("explorer.exe", g));
    }
}