Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
19.5 KB
Raw Blame
//! encaixe.cpp: encaixe nas bordas, como no macOS Sequoia: arrastar uma janela até a borda esquerda/direita = metade, até
//! um canto = um quarto, até a barra de menus = preencher; a prévia do Mac (retângulo arredondado translúcido) aparece
//! atrás da janela enquanto arrasta. Arrastar uma encaixada a devolve ao tamanho de antes. O encaixe do Windows fica
//! desligado só enquanto o Shell roda (SPI_SETWINARRANGING, sem gravar). Janela com a nossa barra: a DLL encaixa
//! ("MacJanelaEncaixar"); as outras o Shell move direto. encaixe_windows=1 deixa o encaixe com o Windows.
#![allow(dead_code)]

use std::collections::HashMap;

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{anim, apps, log, shell, ui};

const WM_EN_FRAME: u32 = WM_APP + 140;
struct S {
    ev: HWINEVENTHOOK,
    prev: HWND,
    timer: usize,
    drag: HWND,
    start: RECT,
    kind: i32,
    target: RECT,
    alpha: u8,
    turned_off: bool,
    win_before: bool,
    fade_at: f64,
    before: HashMap<isize, RECT>,
    tiled: HashMap<isize, RECT>,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
    SS.get().get_or_insert_with(|| S { ev: HWINEVENTHOOK::default(), prev: HWND::default(), timer: 0, drag: HWND::default(), start: RECT::default(), kind: 0, target: RECT::default(), alpha: 0, turned_off: false, win_before: true, fade_at: 0.0, before: HashMap::new(), tiled: HashMap::new() })
}
/// o interruptor do Windows ("Ajustar janelas")
fn windows_snap_on() -> bool {
    let mut v = [0u16; 8];
    let mut n = 16u32;
    let ok = unsafe { RegGetValueW(HKEY_CURRENT_USER, w!("Control Panel\\Desktop"), w!("WindowArrangementActive"), RRF_RT_REG_SZ, None, Some(v.as_mut_ptr() as *mut _), Some(&mut n)).is_ok() };
    !ok || v[0] != '0' as u16
}
fn use_windows_snap() -> bool {
    shell::setting("encaixe_windows", "0") == "1"
}
fn enabled() -> bool {
    windows_snap_on() && !use_windows_snap()
}
fn get_arranging() -> bool {
    let mut cur = BOOL(1);
    unsafe {
        let _ = SystemParametersInfoW(SPI_GETWINARRANGING, 0, Some(&mut cur as *mut _ as *mut _), SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0));
    }
    cur.as_bool()
}
fn set_arranging(on: bool) {
    unsafe {
        let _ = SystemParametersInfoW(SPI_SETWINARRANGING, on as u32, None, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0));
    }
}
/// o encaixe do Windows desligado só nesta sessão (sem gravar)
fn silence_windows() {
    let st = s();
    if !get_arranging() {
        return;
    }
    if !st.turned_off {
        st.win_before = true;
        st.turned_off = true;
    }
    set_arranging(false);
}
fn visible(h: HWND, wr: &mut RECT) -> RECT {
    unsafe {
        let _ = GetWindowRect(h, wr);
        let mut vis = *wr;
        if DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, &mut vis as *mut _ as *mut _, std::mem::size_of::<RECT>() as u32).is_err() {
            vis = *wr;
        }
        let mut bx = RECT::default();
        if !GetPropW(h, w!("MacJanela")).is_invalid() && GetWindowRgnBox(h, &mut bx).0 != 0 && bx.right > bx.left {
            vis = RECT { left: wr.left + bx.left, top: wr.top + bx.top, right: wr.left + bx.right, bottom: wr.top + bx.bottom };
        }
        vis
    }
}
/// alvo pelo ponteiro: 0 nada, 1 metade/quarto em t, 2 preencher (a área de trabalho)
fn target(h: HWND, t: &mut RECT) -> i32 {
    unsafe {
        let mut c = POINT::default();
        if GetCursorPos(&mut c).is_err() {
            return 0;
        }
        let hm = MonitorFromPoint(c, MONITOR_DEFAULTTONEAREST);
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        if !GetMonitorInfoW(hm, &mut mi).as_bool() {
            return 0;
        }
        let m = mi.rcMonitor;
        // PR #355: a área útil que o Shell calcula para o monitor (barra de menus e Dock dele) e o DPI do próprio
        // monitor; zonas de canto maiores (15% do lado menor) para os quartos, como no Windows
        let mut wa = crate::principal::work_area_for(hm);
        if wa.right <= wa.left || wa.bottom <= wa.top {
            wa = mi.rcWork;
        }
        let k = {
            use comum::windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};
            let (mut dx, mut dy) = (0u32, 0u32);
            if GetDpiForMonitor(hm, MDT_EFFECTIVE_DPI, &mut dx, &mut dy).is_ok() && dx > 0 { dx as f32 / 96.0 } else { ui::scale(h) }
        };
        let edge = ((12.0 * k) as i32).max(1);
        let available = (wa.right - wa.left).min(wa.bottom - wa.top);
        let corner = ((available as f32 * 0.15) as i32).clamp((72.0 * k) as i32, (160.0 * k) as i32);
        let (left, right) = (m.left.max(wa.left) + edge, m.right.min(wa.right) - 1 - edge);
        let (top, bottom) = (m.top.max(wa.top) + edge, m.bottom.min(wa.bottom) - 1 - edge);
        let (mx, my) = (wa.left + (wa.right - wa.left) / 2, wa.top + (wa.bottom - wa.top) / 2);
        let (left_side, right_side) = (c.x <= left, c.x >= right);
        let (near_top, near_bottom) = (c.y <= top + corner, c.y >= bottom - corner);
        let left_corner = (left_side && (near_top || near_bottom)) || ((c.y <= top || c.y >= bottom) && c.x <= left + corner);
        let right_corner = (right_side && (near_top || near_bottom)) || ((c.y <= top || c.y >= bottom) && c.x >= right - corner);
        if left_corner || right_corner {
            let lower = near_bottom && (!near_top || c.y > my);
            *t = if left_corner { RECT { left: wa.left, top: wa.top, right: mx, bottom: wa.bottom } } else { RECT { left: mx, top: wa.top, right: wa.right, bottom: wa.bottom } };
            if lower {
                t.top = my;
            } else {
                t.bottom = my;
            }
            return 1;
        }
        if left_side || right_side {
            *t = if left_side { RECT { left: wa.left, top: wa.top, right: mx, bottom: wa.bottom } } else { RECT { left: mx, top: wa.top, right: wa.right, bottom: wa.bottom } };
            return 1;
        }
        if c.y <= top {
            *t = wa;
            return 2;
        }
        0
    }
}
unsafe extern "system" fn prev_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    if m == WM_NCHITTEST {
        return LRESULT(HTTRANSPARENT as isize);
    }
    if m == WM_EN_FRAME {
        // aparecendo: ~90 ms, um passo por quadro da tela
        let st = s();
        ui::frame_ack(h, WM_EN_FRAME);
        if st.kind == 0 || st.alpha == 255 {
            ui::frame_clock(h, WM_EN_FRAME, false);
            return LRESULT(0);
        }
        let t = ((anim::now() - st.fade_at) / 90.0).clamp(0.0, 1.0);
        st.alpha = (60.0 + 195.0 * (1.0 - (1.0 - t) * (1.0 - t))) as u8;
        let bf = BLENDFUNCTION { BlendOp: 0, BlendFlags: 0, SourceConstantAlpha: st.alpha, AlphaFormat: 1 };
        let _ = UpdateLayeredWindow(h, None, None, None, None, None, COLORREF(0), Some(&bf), ULW_ALPHA);
        return LRESULT(0);
    }
    DefWindowProcW(h, m, w_, l)
}
/// a prévia: retângulo arredondado translúcido com borda clara e um contorno escuro fino, com margem, como no Sequoia
fn draw(mut t: RECT, h: HWND) {
    let st = s();
    let k = ui::scale(h);
    let g = (6.0 * k) as i32;
    t = RECT { left: t.left + g, top: t.top + g, right: t.right - g, bottom: t.bottom - g };
    let (ww, hh) = (t.right - t.left, t.bottom - t.top);
    if ww <= 0 || hh <= 0 {
        return;
    }
    unsafe {
        let mem = CreateCompatibleDC(None);
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: ww, biHeight: -hh, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
        let mut bits = std::ptr::null_mut();
        let Ok(bmp) = CreateDIBSection(None, &bi, DIB_RGB_COLORS, &mut bits, None, 0) else {
            let _ = DeleteDC(mem);
            return;
        };
        let px = std::slice::from_raw_parts_mut(bits as *mut u32, (ww * hh) as usize);
        let (r, hw, hh2) = (14.0 * k, ww as f32 / 2.0, hh as f32 / 2.0);
        let cov = |d: f32| (0.5 - d).clamp(0.0, 1.0);
        let (fill_a, line_a, dark_a) = (0.26f32, 0.70f32, 0.22f32);
        let lw = k.max(1.0);
        for y in 0..hh {
            let qy = (y as f32 + 0.5 - hh2).abs() - (hh2 - r);
            let edge_y = qy > -2.0 * lw - 2.0;
            for x in 0..ww {
                let qx = (x as f32 + 0.5 - hw).abs() - (hw - r);
                let out = if !edge_y && qx <= -2.0 * lw - 2.0 {
                    let v = (fill_a * 255.0).round() as u32; // miolo: só o preenchimento (rápido)
                    v << 24 | v << 16 | v << 8 | v
                } else {
                    let d = (qx.max(0.0)).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - r;
                    let (outer, inner1, inner2) = (cov(d), cov(d + lw), cov(d + 2.0 * lw));
                    let (dark, light, fill) = (outer - inner1, inner1 - inner2, inner2);
                    let a = dark * dark_a + light * line_a + fill * fill_a;
                    let white = light * line_a + fill * fill_a; // pré-multiplicada
                    let (aa, v) = ((a * 255.0).round() as u32, (white * 255.0).round() as u32);
                    aa << 24 | v << 16 | v << 8 | v
                };
                px[(y * ww + x) as usize] = out;
            }
        }
        let old = SelectObject(mem, bmp);
        let (src, dst, sz) = (POINT::default(), POINT { x: t.left, y: t.top }, SIZE { cx: ww, cy: hh });
        let bf = BLENDFUNCTION { BlendOp: 0, BlendFlags: 0, SourceConstantAlpha: st.alpha, AlphaFormat: 1 };
        let _ = UpdateLayeredWindow(st.prev, None, Some(&dst), Some(&sz), mem, Some(&src), COLORREF(0), Some(&bf), ULW_ALPHA);
        SelectObject(mem, old);
        let _ = DeleteObject(bmp);
        let _ = DeleteDC(mem);
    }
}
fn hide() {
    let st = s();
    st.kind = 0;
    st.alpha = 0;
    if !st.prev.0.is_null() {
        unsafe {
            let _ = ShowWindow(st.prev, SW_HIDE);
        }
    }
}
fn show(kind: i32, t: RECT) {
    let st = s();
    if kind == st.kind && t == st.target {
        return;
    }
    if st.kind == 0 {
        st.alpha = 60;
        st.fade_at = anim::now();
        ui::frame_clock(st.prev, WM_EN_FRAME, true);
    }
    st.kind = kind;
    st.target = t;
    draw(t, st.drag);
    unsafe {
        // logo atrás da janela arrastada (acima das outras)
        let _ = SetWindowPos(st.prev, st.drag, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
    }
}
fn place(h: HWND, want: RECT) {
    unsafe {
        if IsZoomed(h).as_bool() {
            let _ = ShowWindow(h, SW_RESTORE);
        }
        let mut wr = RECT::default();
        let vis = visible(h, &mut wr);
        let r = RECT { left: want.left - (vis.left - wr.left), top: want.top - (vis.top - wr.top), right: want.right + (wr.right - vis.right), bottom: want.bottom + (wr.bottom - vis.bottom) };
        let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
        // tamanho mínimo maior que o quarto: a janela crescia para baixo/direita a partir do canto pedido e, nos cantos
        // de baixo e à direita, saía da tela (#205; issue #2: "offset no terceiro canto"). O que passou do alvo volta,
        // mas nunca além do próprio alvo. Antes isto comparava com o rcWork do Windows, que é maior que a área útil do
        // Shell (barra de menus e Dock), então nos cantos de baixo o ajuste praticamente nunca acontecia.
        let mut now = RECT::default();
        let _ = GetWindowRect(h, &mut now);
        let (e_r, e_b) = (r.right - want.right, r.bottom - want.bottom); // bordas invisíveis
        let (vis_r, vis_b) = (now.right - e_r, now.bottom - e_b);
        let dx = if vis_r > want.right { (now.left - want.left).min(vis_r - want.right).max(0) } else { 0 };
        let dy = if vis_b > want.bottom { (now.top - want.top).min(vis_b - want.bottom).max(0) } else { 0 };
        if dx != 0 || dy != 0 {
            let _ = SetWindowPos(h, None, now.left - dx, now.top - dy, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
        }
    }
}
fn lohi(lo: i32, hi: i32) -> usize {
    ((hi as u16 as u32) << 16 | lo as u16 as u32) as usize
}
/// manda a janela para o alvo (kind 1: retângulo visível t; 2: preencher)
fn apply(h: HWND, kind: i32, t: RECT, start: RECT) {
    let st = s();
    unsafe {
        if !GetPropW(h, w!("MacJanela")).is_invalid() {
            // a DLL encaixa (bordas invisíveis, tamanho de antes, "ampliar" animado)
            let m = RegisterWindowMessageW(w!("MacJanelaEncaixar"));
            if kind == 2 {
                let _ = PostMessageW(h, m, WPARAM(0), LPARAM(0));
            } else {
                let _ = PostMessageW(h, m, WPARAM(lohi(t.right, t.bottom)), LPARAM(lohi(t.left, t.top) as isize));
            }
            return;
        }
        st.before.entry(h.0 as isize).or_insert(start);
        place(h, t);
        let mut now = RECT::default();
        let _ = GetWindowRect(h, &mut now);
        st.tiled.insert(h.0 as isize, now);
    }
}
unsafe extern "system" fn timer_proc(_: HWND, _: u32, _: usize, _: u32) {
    let st = s();
    if st.drag.0.is_null() || !IsWindow(st.drag).as_bool() {
        hide();
        return;
    }
    let mut t = RECT::default();
    let k = target(st.drag, &mut t);
    if k != 0 {
        show(k, t);
    } else if st.kind != 0 {
        hide();
    }
}
fn candidate(h: HWND) -> bool {
    unsafe {
        if h.0.is_null() || GetAncestor(h, GA_ROOT) != h || shell::nossa(h) || apps::is_shell_window(h) {
            return false;
        }
        if crate::janelas::fora_de_tudo(h) {
            return false; // pedido de 02/12/2026: o WacOS não toca nesses programas
        }
        let st = GetWindowLongW(h, GWL_STYLE) as u32;
        let ex = GetWindowLongW(h, GWL_EXSTYLE) as u32;
        st & WS_THICKFRAME.0 != 0 && st & WS_CHILD.0 == 0 && ex & WS_EX_NOACTIVATE.0 == 0
    }
}
unsafe extern "system" fn on_event(_: HWINEVENTHOOK, ev: u32, h: HWND, obj: i32, _: i32, _: u32, _: u32) {
    if obj != OBJID_WINDOW.0 {
        return;
    }
    let st = s();
    if ev == EVENT_SYSTEM_MOVESIZESTART {
        if !candidate(h) || !enabled() {
            return;
        }
        silence_windows(); // (o Ajustes pode ter religado)
        // arrastar ou redimensionar? o ponto em que o botão desceu diz (borda = redimensionar)
        let mut c = POINT::default();
        let _ = GetCursorPos(&mut c);
        let mut hit = HTCAPTION as usize;
        let _ = SendMessageTimeoutW(h, WM_NCHITTEST, WPARAM(0), LPARAM(lohi(c.x, c.y) as isize), SMTO_ABORTIFHUNG, 60, Some(&mut hit));
        if (HTLEFT as usize..=HTBOTTOMRIGHT as usize).contains(&hit) {
            return;
        }
        st.drag = h;
        let _ = GetWindowRect(h, &mut st.start);
        hide();
        st.timer = SetTimer(None, 0, 15, Some(timer_proc));
    } else if ev == EVENT_SYSTEM_MOVESIZEEND {
        if h != st.drag {
            return;
        }
        if st.timer != 0 {
            let _ = KillTimer(None, st.timer);
            st.timer = 0;
        }
        let d = std::mem::take(&mut st.drag);
        hide();
        if !IsWindow(d).as_bool() {
            return;
        }
        let mut t = RECT::default();
        let k = target(d, &mut t);
        let mut now = RECT::default();
        let _ = GetWindowRect(d, &mut now);
        let has_dll = !GetPropW(d, w!("MacJanela")).is_invalid();
        let (sw, sh) = (st.start.right - st.start.left, st.start.bottom - st.start.top);
        if !has_dll && (now.right - now.left != sw || now.bottom - now.top != sh) {
            return; // redimensionou
        }
        if k != 0 {
            if k == 2 && !has_dll {
                let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
                let _ = GetMonitorInfoW(MonitorFromRect(&t, MONITOR_DEFAULTTONEAREST), &mut mi);
                t = mi.rcWork;
            }
            log!("encaixe: {} ({},{} {}x{})", if k == 2 { "preencher" } else { "borda" }, t.left, t.top, t.right - t.left, t.bottom - t.top);
            apply(d, k, t, st.start);
            return;
        }
        // sem a DLL: arrastou uma janela encaixada por nós para longe da borda: volta ao tamanho de antes, no ponteiro
        let key = d.0 as isize;
        if let (false, Some(b), Some(tl)) = (has_dll, st.before.get(&key).copied(), st.tiled.get(&key).copied()) {
            if sw == tl.right - tl.left && sh == tl.bottom - tl.top {
                let mut c = POINT::default();
                let _ = GetCursorPos(&mut c);
                let (bw, bh) = (b.right - b.left, b.bottom - b.top);
                let fx = (c.x - now.left) as f32 / (now.right - now.left).max(1) as f32;
                let left = c.x - (fx * bw as f32) as i32;
                let _ = SetWindowPos(d, None, left, now.top, bw, bh, SWP_NOZORDER | SWP_NOACTIVATE);
                st.before.remove(&key);
                st.tiled.remove(&key);
            }
        }
    }
}
pub fn start() {
    if shell::foto() {
        return;
    }
    let st = s();
    unsafe {
        if st.prev.0.is_null() {
            RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(prev_proc), hInstance: shell::inst(), lpszClassName: w!("ShellEncaixePrevia"), ..Default::default() });
            st.prev = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("ShellEncaixePrevia"), w!(""), WS_POPUP, 0, 0, 1, 1, None, None, shell::inst(), None).unwrap_or_default();
            if !st.prev.0.is_null() {
                apps::ours().push(st.prev);
            }
        }
        if enabled() {
            silence_windows();
        } else if use_windows_snap() && windows_snap_on() {
            // devolve o do Windows (pode ter ficado desligado de uma sessão fechada à força)
            if !get_arranging() {
                set_arranging(true);
            }
            log!("encaixe: o do Windows (encaixe_windows=1)");
        }
        if st.ev.is_invalid() {
            st.ev = SetWinEventHook(EVENT_SYSTEM_MOVESIZESTART, EVENT_SYSTEM_MOVESIZEEND, None, Some(on_event), 0, 0, WINEVENT_OUTOFCONTEXT | shell::sem_proprio());
        }
    }
    log!("encaixe: ligado (encaixe do Windows {} nesta sessão)", if st.turned_off { "desligado" } else { "já estava desligado" });
}
pub fn stop() {
    let st = s();
    unsafe {
        if !st.ev.is_invalid() {
            let _ = UnhookWinEvent(st.ev);
            st.ev = HWINEVENTHOOK::default();
        }
        if st.timer != 0 {
            let _ = KillTimer(None, st.timer);
            st.timer = 0;
        }
    }
    hide();
    // o encaixe do Windows volta como estava (sem gravar: o registro nunca mudou)
    if st.turned_off {
        set_arranging(st.win_before);
        st.turned_off = false;
    }
}
/// Win+← / Win+→: metade esquerda/direita da tela do monitor da janela
pub fn half(h: HWND, right: bool) {
    unsafe {
        if h.0.is_null() || !IsWindow(h).as_bool() {
            return;
        }
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST), &mut mi);
        let a = mi.rcWork;
        let mut sr = RECT::default();
        let _ = GetWindowRect(h, &mut sr);
        let cx = (a.left + a.right) / 2;
        let t = if right { RECT { left: cx, top: a.top, right: a.right, bottom: a.bottom } } else { RECT { left: a.left, top: a.top, right: cx, bottom: a.bottom } };
        apply(h, 1, t, sr);
    }
}