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.

13.0 KB
Raw Blame
//! The screen's bottom corners as click targets (issue 313): the bottom-left corner for Start, the bottom-right one for Show desktop,
//! as Windows' taskbar has them.
//!
//! WHY: people push the pointer into a corner without aiming. The side islands stand a little in from the edges, so no pixel of the
//! Dock is there.
//!
//! WHAT A CORNER IS: a topmost pop-up of a few pixels, flush in the monitor's corner, never activated by a click, with no taskbar
//! button and not in Alt+Tab. It is layered with alpha 1: all but invisible, and still the mouse's (a window with alpha 0, or with
//! `WS_EX_TRANSPARENT`, lets the mouse through). A click is a left press AND release inside the square, so that a drag that ends in a
//! corner does nothing. It is made topmost once and not raised again: what is put over it later (the snip screen, the switcher)
//! stays over it.
//!
//! WHERE IT RUNS: [`sync`] and [`clear`] on the UI thread, from its message loop, which serves these windows too.

use std::sync::{Mutex, MutexGuard, Once};

use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Dwm::{DWMWA_EXCLUDED_FROM_PEEK, DwmSetWindowAttribute};
use windows::Win32::Graphics::Gdi::{BLACK_BRUSH, GetStockObject, HBRUSH};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Controls::WM_MOUSELEAVE;
use windows::Win32::UI::Input::KeyboardAndMouse::{TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent};
use windows::Win32::UI::WindowsAndMessaging::{
    CreateWindowExW, DefWindowProcW, DestroyWindow, IDC_ARROW, IsWindowVisible, LWA_ALPHA, LoadCursorW, RegisterClassExW, SW_SHOWNOACTIVATE,
    SetLayeredWindowAttributes, ShowWindow, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEACTIVATE, WM_MOUSEMOVE, WM_NCDESTROY, WNDCLASSEXW, WS_EX_LAYERED,
    WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
};
use windows::core::{PCWSTR, w};

use super::layout::{Rect, px};

/// A side of the corner's square, logical px.
pub const ZONE: f32 = 6.0;

/// Not 0: a layered window with alpha 0 lets the mouse through.
const ALPHA: u8 = 1;

/// `MA_NOACTIVATE`: the click is delivered and the window in front keeps the keyboard.
const MA_NOACTIVATE: isize = 3;

/// `MK_LBUTTON` in a mouse message's `wParam`: the left button is down.
const MK_LBUTTON: usize = 0x0001;

const CLASS: PCWSTR = w!("rustyfiles.DockCorner");

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Corner {
    /// Bottom left.
    Start,
    /// Bottom right.
    Desktop,
}

/// Corners are ours only while the Dock has hidden Windows' taskbar (else the taskbar has its own) and no full-screen program is on
/// that monitor.
pub fn wanted(taskbar_hidden: bool, fullscreen: bool) -> bool {
    taskbar_hidden && !fullscreen
}

/// The corner's square on `monitor` (device px, screen coordinates). `scale` is the monitor's DPI scale, not the Dock's size.
pub fn zone(monitor: Rect, scale: f32, corner: Corner) -> Rect {
    let s = px(ZONE, scale).max(2);
    let x = match corner {
        Corner::Start => monitor.left,
        Corner::Desktop => monitor.right - s,
    };
    Rect::from_xywh(x, monitor.bottom - s, s, s)
}

/// One corner window that exists.
#[derive(Clone, Copy)]
struct Win {
    mon: u32,
    corner: Corner,
    hwnd: isize,
    rect: Rect,
    /// The left button went down on it and has not come up.
    pressed: bool,
}

/// A window leaves the list when it goes (`WM_NCDESTROY`), whoever destroyed it.
static WINDOWS: Mutex<Vec<Win>> = Mutex::new(Vec::new());

type Handler = Box<dyn Fn(u32, Corner) + Send>;

static ON_CLICK: Mutex<Option<Handler>> = Mutex::new(None);

// (never held across a call into Windows: creating and destroying come back into the procedure)
fn list() -> MutexGuard<'static, Vec<Win>> {
    WINDOWS.lock().unwrap_or_else(|p| p.into_inner())
}

fn hwnd_of(h: isize) -> HWND {
    HWND(h as *mut _)
}

/// What a click does: given the monitor's id and the corner. Replaces an earlier handler. It is called from the window procedure,
/// so it must only pass the news on.
pub fn on_click(handler: impl Fn(u32, Corner) + Send + 'static) {
    *ON_CLICK.lock().unwrap_or_else(|p| p.into_inner()) = Some(Box::new(handler));
}

/// Whether the point is on the window of that monitor's corner (false while there is none).
pub fn hit(mon: u32, corner: Corner, x: i32, y: i32) -> bool {
    list().iter().any(|w| w.mon == mon && w.corner == corner && w.rect.contains(x, y))
}

/// The corner windows become exactly both corners of each `(monitor id, monitor rect, DPI scale)`. Cheap when nothing changed: a
/// window that stays is not touched.
pub fn sync(want: &[(u32, Rect, f32)]) {
    let target: Vec<(u32, Corner, Rect)> = want
        .iter()
        .flat_map(|&(mon, rect, scale)| [Corner::Start, Corner::Desktop].map(|c| (mon, c, zone(rect, scale, c))))
        .collect();
    let have: Vec<Win> = list().clone();
    let gone: Vec<Win> = have.iter().filter(|w| !target.contains(&(w.mon, w.corner, w.rect))).copied().collect();
    let new: Vec<(u32, Corner, Rect)> = target.iter().filter(|t| !have.iter().any(|w| (w.mon, w.corner, w.rect) == **t)).copied().collect();
    if gone.is_empty() && new.is_empty() {
        return;
    }
    for w in &gone {
        // SAFETY: a window of ours, on the thread that made it (the procedure takes it off the list)
        let _ = unsafe { DestroyWindow(hwnd_of(w.hwnd)) };
    }
    for (mon, corner, rect) in new {
        if let Some(hwnd) = create(rect) {
            list().push(Win { mon, corner, hwnd, rect, pressed: false });
        }
    }
    log::info!("dock corners: {} window(s)", list().len());
}

/// All corner windows go.
pub fn clear() {
    sync(&[]);
}

fn create(r: Rect) -> Option<isize> {
    static CLASS_ONCE: Once = Once::new();
    // SAFETY: standard window-class registration and window creation, on the UI thread, which runs a message loop
    unsafe {
        let hinst = GetModuleHandleW(None).ok()?;
        CLASS_ONCE.call_once(|| {
            let wc = WNDCLASSEXW {
                cbSize: size_of::<WNDCLASSEXW>() as u32,
                lpfnWndProc: Some(corner_proc),
                hInstance: hinst.into(),
                lpszClassName: CLASS,
                hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
                hbrBackground: HBRUSH(GetStockObject(BLACK_BRUSH).0),
                ..Default::default()
            };
            RegisterClassExW(&wc);
        });
        let ex = WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE;
        let h = match CreateWindowExW(ex, CLASS, w!(""), WS_POPUP, r.left, r.top, r.width(), r.height(), None, None, Some(hinst.into()), None) {
            Ok(h) => h,
            Err(e) => {
                log::warn!("dock corners: a window could not be made: {e}");
                return None;
            }
        };
        let _ = SetLayeredWindowAttributes(h, COLORREF(0), ALPHA, LWA_ALPHA);
        let on: u32 = 1;
        let _ = DwmSetWindowAttribute(h, DWMWA_EXCLUDED_FROM_PEEK, &on as *const u32 as *const _, size_of::<u32>() as u32);
        // (topmost from its creation. Shown by a call of its own: placed and shown in one `SetWindowPos`, a corner patch came back
        // not shown with no error, see `desktop/cornerpatch.rs`)
        let _ = ShowWindow(h, SW_SHOWNOACTIVATE);
        if !IsWindowVisible(h).as_bool() {
            log::warn!("dock corners: a window was not shown");
        }
        Some(h.0 as isize)
    }
}

/// What the pointer did on a corner's window.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Pointer {
    Down,
    Up,
    /// It went off the window (`WM_MOUSELEAVE`).
    Left,
    /// It moved over the window with the left button up.
    Hover,
}

/// The press after one of these: whether it is held now, and whether this was a click. Pure.
///
/// A window that is never active cannot capture the mouse beyond itself, so a release elsewhere never comes here: the press is
/// dropped when the pointer leaves, and again by a move with the button up, so that a later drag that ends in the corner is no
/// click. (Not by asking for the buttons' state: `GetAsyncKeyState` answers 0 while a window with more rights is in front, and no
/// click in a corner got through.)
fn after(pressed: bool, what: Pointer) -> (bool, bool) {
    match what {
        Pointer::Down => (true, false),
        Pointer::Up => (false, pressed),
        Pointer::Left | Pointer::Hover => (false, false),
    }
}

/// Takes `what` into the window's press: the window, and whether this was a click.
fn pointer(hwnd: isize, what: Pointer) -> Option<(Win, bool)> {
    list().iter_mut().find(|w| w.hwnd == hwnd).map(|w| {
        let (pressed, click) = after(w.pressed, what);
        w.pressed = pressed;
        (*w, click)
    })
}

unsafe extern "system" fn corner_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
    let key = hwnd.0 as isize;
    match msg {
        WM_MOUSEACTIVATE => return LRESULT(MA_NOACTIVATE),
        WM_LBUTTONDOWN => {
            if let Some((w, _)) = pointer(key, Pointer::Down) {
                log::info!("dock corners: pressed {:?} on monitor {}", w.corner, w.mon);
                let mut leave = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };
                // SAFETY: a valid structure of the right size for our own window
                if let Err(e) = unsafe { TrackMouseEvent(&mut leave) } {
                    log::warn!("dock corners: the pointer's leaving is not told: {e}");
                }
            }
            return LRESULT(0);
        }
        // A release comes here only over the square, and counts only after a press here: a drag that started elsewhere has none.
        WM_LBUTTONUP => {
            if let Some((w, true)) = pointer(key, Pointer::Up)
                && let Some(handler) = ON_CLICK.lock().unwrap_or_else(|p| p.into_inner()).as_ref()
            {
                handler(w.mon, w.corner);
            }
            return LRESULT(0);
        }
        WM_MOUSELEAVE => {
            pointer(key, Pointer::Left);
            return LRESULT(0);
        }
        WM_MOUSEMOVE if wp.0 & MK_LBUTTON == 0 => {
            pointer(key, Pointer::Hover);
        }
        WM_NCDESTROY => list().retain(|w| w.hwnd != key),
        _ => {}
    }
    // SAFETY: the default procedure, with the message as it arrived
    unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
}

#[cfg(test)]
mod tests {
    use super::super::layout::{SIDE_HEIGHT, Widths, islands_with};
    use super::*;

    const FULL_HD: Rect = Rect::new(0, 0, 1920, 1080);

    #[test]
    fn corners_only_with_the_taskbar_hidden_and_nothing_full_screen() {
        assert!(wanted(true, false));
        assert!(!wanted(true, true));
        assert!(!wanted(false, false));
        assert!(!wanted(false, true));
    }

    #[test]
    fn each_square_lies_flush_in_its_corner() {
        assert_eq!(zone(FULL_HD, 1.0, Corner::Start), Rect::new(0, 1074, 6, 1080));
        assert_eq!(zone(FULL_HD, 1.0, Corner::Desktop), Rect::new(1914, 1074, 1920, 1080));
        assert_eq!(zone(FULL_HD, 1.5, Corner::Start), Rect::new(0, 1071, 9, 1080));
        assert_eq!(zone(FULL_HD, 1.5, Corner::Desktop), Rect::new(1911, 1071, 1920, 1080));
        // a monitor left of and above the primary one
        let m = Rect::new(-2560, -360, 0, 1080);
        assert_eq!(zone(m, 2.0, Corner::Start), Rect::new(-2560, 1068, -2548, 1080));
        assert_eq!(zone(m, 2.0, Corner::Desktop), Rect::new(-12, 1068, 0, 1080));
        // never too small to hit
        assert_eq!(zone(FULL_HD, 0.1, Corner::Start).width(), 2);
        // the pointer pushed into the corner is inside
        assert!(zone(FULL_HD, 1.0, Corner::Start).contains(0, 1079));
        assert!(zone(FULL_HD, 1.0, Corner::Desktop).contains(1919, 1079));
    }

    #[test]
    fn the_squares_stay_clear_of_the_side_islands_at_every_dock_size() {
        let widths = Widths { left: 330.0, middle: 600.0, right: 280.0 };
        for dpi_scale in [1.0, 1.25, 1.5, 2.0] {
            for size in [0.75, 1.0, 1.5] {
                let islands = islands_with(FULL_HD, dpi_scale * size, widths, SIDE_HEIGHT);
                assert!(zone(FULL_HD, dpi_scale, Corner::Start).right <= islands.left.left, "{dpi_scale} {size}");
                assert!(zone(FULL_HD, dpi_scale, Corner::Desktop).left >= islands.right.right, "{dpi_scale} {size}");
            }
        }
    }

    /// Whether these, in order, give a click at the end.
    fn clicks(what: &[Pointer]) -> bool {
        what.iter().fold((false, false), |(pressed, _), &w| after(pressed, w)).1
    }

    #[test]
    fn a_click_is_a_press_and_a_release_on_the_square() {
        use Pointer::{Down, Hover, Left, Up};
        assert!(clicks(&[Down, Up]));
        assert!(clicks(&[Hover, Down, Up]));
        assert!(!clicks(&[Up]), "a drag from elsewhere that ends here");
        assert!(!clicks(&[Down, Left, Up]), "pressed here, released elsewhere, then a drag back");
        assert!(!clicks(&[Down, Hover, Up]), "the release went unheard");
        assert!(!clicks(&[Down, Up, Up]));
    }

    #[test]
    fn with_no_window_no_point_is_a_corner() {
        assert!(!hit(7, Corner::Start, 0, 1079));
    }
}