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.

12.8 KB
Raw Blame
//! Folder sizes from the index of Everything (voidtools), when it is running and indexes folder sizes
//! (Everything 1.4: Options › Indexes › "Index folder size"). Asked over Everything 1.4's own IPC (`WM_COPYDATA` to its
//! `EVERYTHING_TASKBAR_NOTIFICATION` window, query `EVERYTHING_IPC_COPYDATA_QUERY2W`), the way the Windhawk mod "Better file sizes
//! in Explorer details" asks for them; Everything 1.5's alpha answers on the same window class with "_(1.5a)" after it.
//!
//! One query lists every folder of a parent with its size (`parent:"<dir>" folder:`), so a listing's folders cost one round trip;
//! a folder the parent's query did not give is asked by itself (`folder:wfn:"<path>"`). Everything's reply is a `WM_COPYDATA`
//! sent to a message-only window of ours, on a thread of its own.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Sender, channel};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};

use parking_lot::Mutex;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::DataExchange::COPYDATASTRUCT;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::{
    ChangeWindowMessageFilterEx, CreateWindowExW, DefWindowProcW, DispatchMessageW, FindWindowW, GetMessageW, HWND_MESSAGE, MSG,
    MSGFLT_ALLOW, RegisterClassW, SMTO_ABORTIFHUNG, SMTO_BLOCK, SendMessageTimeoutW, TranslateMessage, WINDOW_EX_STYLE, WM_COPYDATA,
    WNDCLASSW, WS_OVERLAPPED,
};
use windows::core::{PCWSTR, w};

use crate::wide::wide;

const QUERY2W: usize = 18;
const MATCHDIACRITICS: u32 = 0x10;
const MATCHCASE: u32 = 0x01;
const REQUEST_NAME: u32 = 0x01;
const REQUEST_PATH: u32 = 0x02;
const REQUEST_FULL_PATH_AND_NAME: u32 = 0x04;
const REQUEST_EXTENSION: u32 = 0x08;
const REQUEST_SIZE: u32 = 0x10;
const TIMEOUT: Duration = Duration::from_millis(1500);

/// How long a parent folder's answer is reused. A listing asks for its folders' sizes in batches, as they scroll into view (all of
/// them when sorted by size), seconds apart; each batch would otherwise bring the parent's whole list of folders again.
const REUSE_FOR: Duration = Duration::from_secs(10);
const RECENT_MAX: usize = 8;
/// Recent answers: (parent folder in lowercase, when it came, its folders' sizes by lowercase name).
static RECENT: Mutex<Vec<(String, Instant, Arc<HashMap<String, u64>>)>> = Mutex::new(Vec::new());

fn parent_key(parent: &Path) -> String {
    parent.to_string_lossy().trim_end_matches('\\').to_lowercase()
}

/// Forgets Everything's last answer about the folders inside `parent`, so they are asked again (F5).
pub fn forget(parent: &Path) {
    let key = parent_key(parent);
    RECENT.lock().retain(|(p, ..)| *p != key);
}

/// The sizes of the folders inside `parent`, by lowercase name, and whether they are a recent answer reused; a new answer costs
/// one query. `None` when Everything did not answer.
fn sizes_in(parent: &Path) -> Option<(Arc<HashMap<String, u64>>, bool)> {
    let key = parent_key(parent);
    {
        let mut recent = RECENT.lock();
        recent.retain(|(_, at, _)| at.elapsed() < REUSE_FOR);
        if let Some((.., sizes)) = recent.iter().find(|(p, ..)| *p == key) {
            return Some((sizes.clone(), true));
        }
    }
    let search = format!("parent:\"{}\" folder:", parent.to_string_lossy().trim_end_matches('\\'));
    let found = query(&search, REQUEST_NAME | REQUEST_SIZE, false).map_err(|e| log::info!("Everything: {e:#}")).ok()?;
    let sizes: Arc<HashMap<String, u64>> = Arc::new(found.into_iter().filter_map(|f| f.size.map(|s| (f.name.to_lowercase(), s))).collect());
    let mut recent = RECENT.lock();
    recent.retain(|(p, ..)| *p != key);
    if recent.len() >= RECENT_MAX {
        recent.remove(0);
    }
    recent.push((key, Instant::now(), sizes.clone()));
    Some((sizes, false))
}

/// Everything's IPC window, if it is running.
fn everything_window() -> Option<HWND> {
    unsafe {
        FindWindowW(w!("EVERYTHING_TASKBAR_NOTIFICATION_(1.5a)"), PCWSTR::null())
            .ok()
            .filter(|h| !h.is_invalid())
            .or_else(|| FindWindowW(w!("EVERYTHING_TASKBAR_NOTIFICATION"), PCWSTR::null()).ok().filter(|h| !h.is_invalid()))
    }
}

/// Whether Everything is running (its IPC window is there).
pub fn available() -> bool {
    everything_window().is_some()
}

/// The reply awaited now: (its `dwData`, where the reply's bytes go).
static AWAITED: Mutex<Option<(usize, Sender<Vec<u8>>)>> = Mutex::new(None);
/// One query at a time.
static QUERY: Mutex<u32> = Mutex::new(0);

extern "system" fn receiver_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    if msg == WM_COPYDATA {
        let cds = unsafe { &*(lparam.0 as *const COPYDATASTRUCT) };
        let mut awaited = AWAITED.lock();
        if let Some((id, tx)) = awaited.as_ref()
            && *id == cds.dwData
        {
            let bytes = unsafe { std::slice::from_raw_parts(cds.lpData as *const u8, cds.cbData as usize) }.to_vec();
            let _ = tx.send(bytes);
            *awaited = None;
        }
        return LRESULT(1);
    }
    unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
}

/// Our message-only window that receives Everything's replies (made once, on a thread of its own with a message loop).
fn receiver() -> Option<isize> {
    static HWND_: OnceLock<Option<isize>> = OnceLock::new();
    *HWND_.get_or_init(|| {
        let (tx, rx) = channel();
        std::thread::Builder::new()
            .name("rf-everything".into())
            .spawn(move || unsafe {
                let class = w!("rustyfiles_everything_reply");
                let wc = WNDCLASSW {
                    lpfnWndProc: Some(receiver_proc),
                    hInstance: GetModuleHandleW(None).map(Into::into).unwrap_or_default(),
                    lpszClassName: class,
                    ..Default::default()
                };
                RegisterClassW(&wc);
                let hwnd = CreateWindowExW(WINDOW_EX_STYLE(0), class, PCWSTR::null(), WS_OVERLAPPED, 0, 0, 0, 0, Some(HWND_MESSAGE), None, None, None);
                let Ok(hwnd) = hwnd else {
                    let _ = tx.send(None);
                    return;
                };
                // (Everything may run with more rights than we do: let its message in)
                let _ = ChangeWindowMessageFilterEx(hwnd, WM_COPYDATA, MSGFLT_ALLOW, None);
                let _ = tx.send(Some(hwnd.0 as isize));
                let mut msg = MSG::default();
                while GetMessageW(&mut msg, None, 0, 0).as_bool() {
                    let _ = TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }
            })
            .ok()?;
        rx.recv().ok().flatten()
    })
}

/// One folder found by a query: its full path and its size in bytes.
struct Found {
    name: String,
    size: Option<u64>,
}

/// Runs `search` and returns each result's name (as `request` asks: the name, or the full path) and size.
fn query(search: &str, request: u32, match_case: bool) -> anyhow::Result<Vec<Found>> {
    let everything = everything_window().ok_or_else(|| anyhow::anyhow!("Everything is not running"))?;
    let reply_to = receiver().ok_or_else(|| anyhow::anyhow!("no window for Everything's reply"))?;
    let mut serial = QUERY.lock();
    *serial = serial.wrapping_add(1).max(1);
    let id = *serial as usize + 0x5246_0000;

    let text = wide(search);
    let header: [u32; 7] = [
        reply_to as u32,                                                        // reply_hwnd
        id as u32,                                                              // reply_copydata_message
        MATCHDIACRITICS | if match_case { MATCHCASE } else { 0 },               // search_flags
        0,                                                                      // offset
        u32::MAX,                                                               // max_results
        request,                                                                // request_flags
        1,                                                                      // sort_type: name ascending
    ];
    let mut buf: Vec<u8> = Vec::with_capacity(28 + text.len() * 2);
    for v in header {
        buf.extend_from_slice(&v.to_le_bytes());
    }
    for c in &text {
        buf.extend_from_slice(&c.to_le_bytes());
    }
    let cds = COPYDATASTRUCT { dwData: QUERY2W, cbData: buf.len() as u32, lpData: buf.as_mut_ptr().cast() };

    let (tx, rx) = channel();
    *AWAITED.lock() = Some((id, tx));
    let sent = unsafe {
        SendMessageTimeoutW(
            everything,
            WM_COPYDATA,
            WPARAM(reply_to as usize),
            LPARAM(&cds as *const _ as isize),
            SMTO_BLOCK | SMTO_ABORTIFHUNG,
            TIMEOUT.as_millis() as u32,
            None,
        )
    };
    if sent.0 == 0 {
        *AWAITED.lock() = None;
        anyhow::bail!("Everything did not take the query");
    }
    let reply = rx.recv_timeout(TIMEOUT);
    *AWAITED.lock() = None;
    parse(&reply.map_err(|_| anyhow::anyhow!("Everything did not answer"))?)
}

/// Reads an `EVERYTHING_IPC_LIST2` reply: the header (5 DWORDs), the items (flags, offset of their data), and for each item its
/// data in the order of the request's flags (texts: a DWORD length, then that many UTF-16 units and a terminating 0).
fn parse(b: &[u8]) -> anyhow::Result<Vec<Found>> {
    let u32_at = |o: usize| -> anyhow::Result<u32> {
        b.get(o..o + 4).map(|s| u32::from_le_bytes(s.try_into().unwrap())).ok_or_else(|| anyhow::anyhow!("short reply"))
    };
    let numitems = u32_at(4)? as usize;
    let request = u32_at(12)?;
    let mut out = Vec::with_capacity(numitems);
    for i in 0..numitems {
        let mut p = u32_at(20 + i * 8 + 4)? as usize;
        let mut name = String::new();
        let text = |p: &mut usize| -> anyhow::Result<String> {
            let len = u32_at(*p)? as usize;
            let s = b.get(*p + 4..*p + 4 + len * 2).ok_or_else(|| anyhow::anyhow!("short reply"))?;
            let units: Vec<u16> = s.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
            *p += 4 + (len + 1) * 2;
            Ok(String::from_utf16_lossy(&units))
        };
        if request & REQUEST_NAME != 0 {
            name = text(&mut p)?;
        }
        if request & REQUEST_PATH != 0 {
            text(&mut p)?;
        }
        if request & REQUEST_FULL_PATH_AND_NAME != 0 {
            name = text(&mut p)?;
        }
        if request & REQUEST_EXTENSION != 0 {
            text(&mut p)?;
        }
        let size = if request & REQUEST_SIZE != 0 {
            let s = b.get(p..p + 8).ok_or_else(|| anyhow::anyhow!("short reply"))?;
            let v = i64::from_le_bytes(s.try_into().unwrap());
            // (-1: Everything does not know this folder's size)
            (v >= 0).then_some(v as u64)
        } else {
            None
        };
        out.push(Found { name, size });
    }
    Ok(out)
}

/// The sizes Everything knows of `dirs`, in bytes (the sum of the files' sizes, as rustyfiles counts them). A folder Everything
/// does not index or has no size for is left out. Blocks for a few milliseconds per parent folder: call off the UI thread.
pub fn folder_sizes(dirs: &[PathBuf]) -> HashMap<PathBuf, u64> {
    let t0 = std::time::Instant::now();
    let mut out = HashMap::new();
    if !available() {
        return out;
    }
    // one query per parent folder: all its sub-folders at once
    let mut by_parent: HashMap<&Path, Vec<&PathBuf>> = HashMap::new();
    for d in dirs {
        if let Some(parent) = d.parent() {
            by_parent.entry(parent).or_default().push(d);
        }
    }
    let (mut queries, mut reused) = (0, 0);
    for (parent, wanted) in by_parent {
        let sizes = match sizes_in(parent) {
            Some((sizes, true)) => {
                reused += 1;
                sizes
            }
            Some((sizes, false)) => {
                queries += 1;
                sizes
            }
            None => {
                queries += 1;
                Arc::default()
            }
        };
        for d in wanted {
            let name = d.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
            if let Some(&s) = sizes.get(&name) {
                out.insert(d.clone(), s);
                continue;
            }
            // not in the parent's answer (a drive's root, say): the folder by itself
            queries += 1;
            if let Ok(found) = query(&format!("folder:wfn:\"{}\"", d.to_string_lossy()), REQUEST_SIZE, true)
                && let Some(s) = found.first().and_then(|f| f.size)
            {
                out.insert(d.clone(), s);
            }
        }
    }
    log::debug!(
        "Everything: {} of {} folder sizes in {} ms ({queries} queries, {reused} answers reused)",
        out.len(),
        dirs.len(),
        t0.elapsed().as_millis()
    );
    out
}