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.3 KB
Raw Blame
//! What becomes of a drag's picture when the window it is over is destroyed (issue 80: "the file icon remains stuck on the screen"
//! after Alt+Tab in the middle of a drag, with the pointer inside the Dock's switcher).
//!
//! No mouse is needed: the shell's drop target helper is told by hand what a drop target tells it. A window of ours gets
//! `IDropTargetHelper::DragEnter` with a data object that carries a picture, and is then destroyed: once as the switcher was
//! (nothing more said to the helper), once after `DragLeave`. Each time the visible `SysDragImage` windows of this process are
//! counted. Run: `cargo run -p rf-win --example dragimage_probe -- <x> <y>` (where the picture shows for a moment).

use std::path::PathBuf;

use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, LRESULT, POINT, SIZE, TRUE, WPARAM};
use windows::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS, HBITMAP};
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::Ole::{DROPEFFECT_COPY, OleInitialize};
use windows::Win32::System::Threading::GetCurrentProcessId;
use windows::Win32::UI::Shell::{CLSID_DragDropHelper, IDragSourceHelper, IDropTargetHelper, SHDRAGIMAGE};
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::core::{BOOL, w};

unsafe extern "system" fn proc_(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
    unsafe { DefWindowProcW(h, m, wp, lp) }
}

fn pump(ms: u64) {
    let until = std::time::Instant::now() + std::time::Duration::from_millis(ms);
    unsafe {
        let mut msg = MSG::default();
        while std::time::Instant::now() < until {
            while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
                let _ = TranslateMessage(&msg);
                DispatchMessageW(&msg);
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }
}

/// The visible drag pictures of this process: (how many, the first one's place).
fn pictures() -> (usize, Option<(i32, i32)>) {
    unsafe extern "system" fn each(hwnd: HWND, lp: LPARAM) -> BOOL {
        unsafe {
            let mut pid = 0u32;
            GetWindowThreadProcessId(hwnd, Some(&mut pid));
            if pid == GetCurrentProcessId() && IsWindowVisible(hwnd).as_bool() {
                let mut buf = [0u16; 32];
                let n = GetClassNameW(hwnd, &mut buf) as usize;
                if String::from_utf16_lossy(&buf[..n]) == "SysDragImage" {
                    let out = &mut *(lp.0 as *mut (usize, Option<(i32, i32)>));
                    out.0 += 1;
                    let mut r = windows::Win32::Foundation::RECT::default();
                    let _ = GetWindowRect(hwnd, &mut r);
                    out.1.get_or_insert((r.left, r.top));
                }
            }
        }
        TRUE
    }
    let mut out = (0usize, None);
    unsafe {
        let _ = EnumWindows(Some(each), LPARAM(&mut out as *mut _ as isize));
    }
    out
}

/// A 48 px orange square, as the picture of the drag.
unsafe fn square() -> HBITMAP {
    let info = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: 48, biHeight: -48, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
    let mut bits = std::ptr::null_mut();
    let bmp = unsafe { CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0).unwrap() };
    let px = unsafe { std::slice::from_raw_parts_mut(bits as *mut u32, 48 * 48) };
    px.fill(0xFFFF_6A1A);
    bmp
}

fn main() -> anyhow::Result<()> {
    let args: Vec<i32> = std::env::args().skip(1).filter_map(|a| a.parse().ok()).collect();
    let (x, y) = (args.first().copied().unwrap_or(200), args.get(1).copied().unwrap_or(200));
    let dir = std::env::temp_dir().join(format!("rf-dragimage-{}", std::process::id()));
    std::fs::create_dir_all(&dir)?;
    let file: PathBuf = dir.join("a.txt");
    std::fs::write(&file, b"x")?;
    unsafe {
        OleInitialize(None)?;
        let hinst = GetModuleHandleW(None)?;
        let wc = WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hinst.into(), lpszClassName: w!("rustyfiles.DragImageProbe"), ..Default::default() };
        RegisterClassW(&wc);
        let make = || {
            let h = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("rustyfiles.DragImageProbe"), w!(""), WS_POPUP, x, y, 300, 200, None, None, Some(hinst.into()), None).unwrap();
            let _ = ShowWindow(h, SW_SHOWNOACTIVATE);
            h
        };
        for leave_first in [false, true] {
            // (a new data object and helper pair each round, as each drag has)
            let data = rf_win::dnd::data_object(std::slice::from_ref(&file))?;
            let source: IDragSourceHelper = CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)?;
            let image = SHDRAGIMAGE { sizeDragImage: SIZE { cx: 48, cy: 48 }, ptOffset: POINT { x: 24, y: 24 }, hbmpDragImage: square(), crColorKey: COLORREF(0xFFFF_FFFF) };
            source.InitializeFromBitmap(&image, &data)?;
            let helper: IDropTargetHelper = CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)?;
            let hwnd = make();
            pump(100);
            println!("--- the window is destroyed {}", if leave_first { "after DragLeave" } else { "with nothing said to the helper" });
            println!("before the drag enters:      {:?}", pictures());
            let pt = POINT { x: x + 150, y: y + 100 };
            println!("DragEnter -> {:?}", helper.DragEnter(hwnd, &data, &pt, DROPEFFECT_COPY));
            pump(400);
            println!("over the window:             {:?}", pictures());
            if leave_first {
                println!("DragLeave -> {:?}", helper.DragLeave());
            }
            let _ = DestroyWindow(hwnd);
            pump(600);
            println!("after the window is gone:    {:?}", pictures());
            drop(helper);
            drop(source);
            drop(data);
            pump(600);
            println!("after the drag's objects go: {:?}", pictures());
            let hidden = rf_win::dnd::hide_drag_images();
            println!("the sweep hid {hidden}");
        }
    }
    let _ = std::fs::remove_dir_all(&dir);
    Ok(())
}