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.

10.0 KB
Raw Blame
//! Volume details and safe removal. Blocking (disks can stall): call off the UI thread.

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

use windows::Win32::Foundation::HWND;
use windows::Win32::Storage::FileSystem::{GetDiskFreeSpaceExW, GetDriveTypeW, GetVolumeInformationW};
use windows::Win32::System::Com::CoTaskMemFree;
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
use windows::Win32::UI::Shell::{CMF_NORMAL, CMINVOKECOMMANDINFO, IContextMenu, IShellFolder, SHBindToParent, SHParseDisplayName};
use windows::Win32::UI::WindowsAndMessaging::{CreatePopupMenu, DestroyMenu, SW_SHOWNORMAL};
use windows::core::{PCSTR, PCWSTR, s};

use crate::shell::ensure_com;
use crate::wide::{from_wide, wide};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VolumeInfo {
    pub root: PathBuf,
    pub label: String,
    pub filesystem: String,
    pub serial: u32,
    pub total: u64,
    pub free: u64,
    /// Turkish, e.g. "Yerel Disk".
    pub drive_type: String,
}

impl VolumeInfo {
    /// "A1B2-C3D4", as shown by `vol`.
    pub fn serial_string(&self) -> String {
        format!("{:04X}-{:04X}", self.serial >> 16, self.serial & 0xFFFF)
    }
}

/// Turkish name for a `GetDriveTypeW` result.
pub fn drive_type_name(t: u32) -> &'static str {
    match t {
        2 => "Çıkarılabilir Disk",
        3 => "Yerel Disk",
        4 => "Ağ Sürücüsü",
        5 => "Optik Sürücü (CD/DVD)",
        6 => "RAM Disk",
        1 => "Bağlı Değil",
        _ => "Bilinmiyor",
    }
}

/// Details of the volume at `root` (e.g. `C:\`). Size fields stay 0 when the media is missing.
pub fn volume_info(root: &Path) -> anyhow::Result<VolumeInfo> {
    let mut r = root.to_string_lossy().to_string();
    if !r.ends_with('\\') {
        r.push('\\');
    }
    let w = wide(&r);
    let drive_type = drive_type_name(unsafe { GetDriveTypeW(PCWSTR(w.as_ptr())) }).to_string();
    let mut label = [0u16; 261];
    let mut fs = [0u16; 261];
    let mut serial = 0u32;
    let has_vol = unsafe {
        GetVolumeInformationW(PCWSTR(w.as_ptr()), Some(&mut label), Some(&mut serial), None, None, Some(&mut fs))
    };
    let (mut free, mut total) = (0u64, 0u64);
    if has_vol.is_ok() {
        unsafe {
            let _ = GetDiskFreeSpaceExW(PCWSTR(w.as_ptr()), Some(&mut free), Some(&mut total), None);
        }
    } else if drive_type != "Optik Sürücü (CD/DVD)" {
        has_vol?; // media-less optical drives are reported with empty details instead of failing
    }
    Ok(VolumeInfo {
        root: PathBuf::from(r),
        label: from_wide(&label),
        filesystem: from_wide(&fs),
        serial,
        total,
        free,
        drive_type,
    })
}

struct Pidl(*mut ITEMIDLIST);
impl Drop for Pidl {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { CoTaskMemFree(Some(self.0 as *const _)) }
        }
    }
}

/// Ejects a removable (or optical) drive by invoking the shell's "Eject" verb, which is exactly
/// what Explorer does (flushes, locks, dismounts and asks the device to power down).
/// Gives the volume a new label (empty = none). Windows lets a standard user rename removable
/// drives; a fixed drive usually needs an administrator and fails with "access denied" here
/// (nothing asks for elevation).
pub fn set_label(root: &Path, label: &str) -> std::io::Result<()> {
    use windows::Win32::Storage::FileSystem::SetVolumeLabelW;
    let mut r = root.to_string_lossy().into_owned();
    if !r.ends_with('\\') {
        r.push('\\');
    }
    let (wr, wl) = (crate::wide::wide(&r), crate::wide::wide(label));
    let label = if label.is_empty() { windows::core::PCWSTR::null() } else { windows::core::PCWSTR(wl.as_ptr()) };
    unsafe { SetVolumeLabelW(windows::core::PCWSTR(wr.as_ptr()), label) }.map_err(|e| std::io::Error::from_raw_os_error(e.code().0 & 0xffff))
}

/// BitLocker's state of a drive as the shell gives it (`System.Volume.BitLockerProtection`): 6 is "locked". Read without
/// administrator rights, from the same property Explorer draws its lock from. `None` when the shell has no value.
pub fn bitlocker_state(letter: char) -> Option<u32> {
    use windows::Win32::System::Com::StructuredStorage::PropVariantToUInt32;
    use windows::Win32::UI::Shell::PropertiesSystem::{GPS_DEFAULT, IPropertyStore, PSGetPropertyKeyFromName, SHGetPropertyStoreFromParsingName};
    use windows::core::w;
    ensure_com();
    let root = wide(&format!("{letter}:\\"));
    unsafe {
        let store: IPropertyStore = SHGetPropertyStoreFromParsingName(PCWSTR(root.as_ptr()), None, GPS_DEFAULT).ok()?;
        let mut key = Default::default();
        PSGetPropertyKeyFromName(w!("System.Volume.BitLockerProtection"), &mut key).ok()?;
        let v = store.GetValue(&key).ok()?;
        PropVariantToUInt32(&v).ok()
    }
}

/// Whether the drive is locked by BitLocker (its contents can't be read until it is unlocked).
pub fn bitlocker_locked(letter: char) -> bool {
    bitlocker_state(letter) == Some(6)
}

/// Windows' own "enter the password to unlock this drive" window (bdeunlock.exe, what Explorer opens for a locked drive); returns
/// once it is closed, unlocked or not. Blocking: call it off the UI thread.
pub fn bitlocker_unlock_prompt(letter: char) -> std::io::Result<()> {
    let system = std::env::var_os("SystemRoot").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
    std::process::Command::new(system.join("System32").join("bdeunlock.exe")).arg(format!("{letter}:")).status().map(|_| ())
}

/// The removable drives that hold a volume now (a USB stick, a card in a reader): letter and label, in letter order. An empty card
/// reader is left out. Blocks briefly (one call for each drive letter in use, one more for each removable one): off the UI thread.
/// (A USB hard disk reports itself as a fixed drive and is not in this list yet.)
pub fn removable_drives() -> Vec<(char, String)> {
    let mask = unsafe { windows::Win32::Storage::FileSystem::GetLogicalDrives() };
    (0..26u32)
        .filter(|i| mask & (1 << i) != 0)
        .filter_map(|i| {
            let letter = (b'A' + i as u8) as char;
            let root = format!("{letter}:\\");
            let rw = wide(&root);
            if unsafe { GetDriveTypeW(PCWSTR(rw.as_ptr())) } != 2 {
                return None;
            }
            volume_info(Path::new(&root)).ok().map(|v| (letter, v.label))
        })
        .collect()
}

/// Whether a drive of this type (`GetDriveTypeW`) may be asked to eject: one with removable media (2), a disc drive (5), and a
/// fixed disk (3) on an outside bus.
///
/// WHY the last one (issue 622, the log of 2026-12-04: "E: sürücüsü çıkarılabilir değil"). An external hard disk or SSD reports
/// itself as a FIXED disk. The sidebar and the Dock have offered to eject such a disk since discussion 762, as File Explorer
/// does, but this check still took only removable media, so the eject of an external disk was refused before Windows was even
/// asked, every time. Pure.
pub fn may_eject(drive_type: u32, external: bool) -> bool {
    matches!(drive_type, 2 | 5) || (drive_type == 3 && external)
}

/// Fails when files are still open on the drive.
pub fn eject(drive_letter: char) -> anyhow::Result<()> {
    let letter = drive_letter.to_ascii_uppercase();
    anyhow::ensure!(letter.is_ascii_uppercase(), "Geçersiz sürücü harfi");
    let root = format!("{letter}:\\");
    let rw = wide(&root);
    let t = unsafe { GetDriveTypeW(PCWSTR(rw.as_ptr())) };
    anyhow::ensure!(may_eject(t, t == 3 && crate::drives::external_bus(letter)), "{letter}: sürücüsü çıkarılabilir değil");
    // an external hard disk or SSD: asked of the device manager, which says who refuses; the shell's verb below answered for such
    // a disk with a box of its own and nothing a program can read (see `device_eject`)
    if t == 3 {
        return crate::device_eject::eject(letter);
    }

    ensure_com();
    unsafe {
        let mut pidl: *mut ITEMIDLIST = std::ptr::null_mut();
        SHParseDisplayName(PCWSTR(rw.as_ptr()), None, &mut pidl, 0, None)?;
        let pidl = Pidl(pidl);
        let mut child: *mut ITEMIDLIST = std::ptr::null_mut();
        let parent: IShellFolder = SHBindToParent(pidl.0, Some(&mut child))?;
        let cm: IContextMenu = parent.GetUIObjectOf(HWND::default(), &[child as *const ITEMIDLIST], None)?;
        let menu = CreatePopupMenu()?;
        let res = (|| -> anyhow::Result<()> {
            cm.QueryContextMenu(menu, 0, 1, 0x7FFF, CMF_NORMAL).ok()?;
            let info = CMINVOKECOMMANDINFO {
                cbSize: std::mem::size_of::<CMINVOKECOMMANDINFO>() as u32,
                // (no window of the shell's own: a refused eject put up Windows' "An error occurred while ejecting" box, with a
                // name of garbage letters on an external disk, behind or beside our own "in use" message: issue 622, 2026-12-05)
                fMask: 0x0000_0400, // CMIC_MASK_FLAG_NO_UI
                lpVerb: PCSTR(s!("eject").as_ptr()),
                nShow: SW_SHOWNORMAL.0,
                ..Default::default()
            };
            cm.InvokeCommand(&info)?;
            Ok(())
        })();
        let _ = DestroyMenu(menu);
        res
    }
}

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

    #[test]
    fn c_drive_info() {
        let v = volume_info(Path::new("C:\\")).unwrap();
        assert_eq!(v.drive_type, "Yerel Disk");
        assert!(v.total > 0 && v.free <= v.total);
        assert!(!v.filesystem.is_empty());
        assert_eq!(v.serial_string().len(), 9);
    }

    #[test]
    fn an_external_disk_may_be_ejected_and_an_internal_one_may_not() {
        assert!(may_eject(2, false), "a USB stick, a card");
        assert!(may_eject(5, false), "a disc drive");
        assert!(may_eject(3, true), "an external hard disk: fixed, on an outside bus (issue 622)");
        assert!(!may_eject(3, false), "an internal disk");
        assert!(!may_eject(4, false) && !may_eject(4, true), "a network drive");
        assert!(!may_eject(0, true) && !may_eject(1, true));
    }

    #[test]
    fn eject_rejects_fixed_drive() {
        // Safe: C: is a fixed disk, so this must fail before touching the shell.
        assert!(eject('C').is_err());
    }
}