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
23.4 KB
Raw Blame
//! espacos.cpp: Spaces do Mac OS X Leopard (tema Leopard; Win+F8, como o F8 do Mac): a tela recua e mostra todas as
//! áreas de trabalho lado a lado numa grade, sobre o cinza-escuro do 10.5. A área atual aparece como está (foto da tela
//! tirada antes de abrir); as outras com o papel de parede e as janelas de cada uma (moldura de metal com o ícone e o
//! nome). Clicar numa área vai para ela (a grade amplia até a escolhida); a casa "+" cria outra área. Esc ou Win+F8
//! fecha. As áreas são as do Windows (mesas.rs: as mesmas do Mission Control).
#![allow(dead_code)]

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::System::Threading::{AttachThreadInput, GetCurrentThreadId};
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::{IVirtualDesktopManager, VirtualDesktopManager};
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

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

const WM_SP_FRAME: u32 = WM_APP + 182;

struct WinBox {
    r: RECT,
    title: String,
    icon: Option<ui::Img>,
    bmp: Option<ID2D1Bitmap>,
}
struct Space {
    id: GUID,
    wins: Vec<WinBox>,
}
#[derive(Default)]
struct S {
    wnd: HWND,
    s: ui::GpuSurface,
    open: bool,
    closing: bool,
    at: f64,
    cur: usize,
    pick: Option<usize>,
    hover: Option<usize>,
    sp: Vec<Space>,
    mon: RECT,
    w: f32,
    h: f32,
    shot: Option<ui::Img>,
    shot_bmp: Option<ID2D1Bitmap>,
    wall: Option<ui::Img>,
    wall_bmp: Option<ID2D1Bitmap>,
    ft: Option<(IDWriteTextFormat, IDWriteTextFormat)>,
    foto: bool,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
    SS.get().get_or_insert_with(S::default)
}
fn sc() -> f32 {
    if s().foto {
        ui::foto_scale()
    } else {
        ui::scale(s().wnd)
    }
}
fn release() {
    let st = s();
    st.shot = None;
    st.shot_bmp = None;
    st.sp.clear();
}
fn reg_bin(name: PCWSTR, buf: &mut [u8]) -> usize {
    let mut cb = buf.len() as u32;
    let ok = unsafe { RegGetValueW(HKEY_CURRENT_USER, w!("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops"), name, RRF_RT_REG_BINARY, None, Some(buf.as_mut_ptr() as *mut _), Some(&mut cb)).is_ok() };
    if ok {
        cb as usize
    } else {
        0
    }
}
fn guid_of(b: &[u8]) -> GUID {
    GUID::from_values(u32::from_le_bytes([b[0], b[1], b[2], b[3]]), u16::from_le_bytes([b[4], b[5]]), u16::from_le_bytes([b[6], b[7]]), [b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]])
}
/// as áreas do Windows (registro do Explorador) e a atual
fn load_spaces() {
    let st = s();
    let mut ids = [0u8; 16 * 32];
    let mut cur = [0u8; 16];
    let has_cur = reg_bin(w!("CurrentVirtualDesktop"), &mut cur) == 16;
    st.cur = 0;
    let n = reg_bin(w!("VirtualDesktopIDs"), &mut ids);
    for c in ids[..n].chunks_exact(16) {
        if has_cur && c == cur {
            st.cur = st.sp.len();
        }
        st.sp.push(Space { id: guid_of(c), wins: Vec::new() });
    }
    if st.sp.is_empty() {
        st.sp.push(Space { id: GUID::zeroed(), wins: Vec::new() });
    }
}
fn icon_px(h: HWND) -> Option<ui::Img> {
    unsafe {
        let mut res = 0usize;
        let mut ic = HICON::default();
        if SendMessageTimeoutW(h, WM_GETICON, WPARAM(ICON_BIG as usize), LPARAM(0), SMTO_ABORTIFHUNG, 50, Some(&mut res)).0 != 0 && res != 0 {
            ic = HICON(res as *mut _);
        }
        if ic.is_invalid() {
            ic = HICON(GetClassLongPtrW(h, GCLP_HICON) as *mut _);
        }
        if ic.is_invalid() {
            return None;
        }
        const N: i32 = 48;
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: N, biHeight: -N, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
        let dc = CreateCompatibleDC(None);
        let mut bits = std::ptr::null_mut();
        let Ok(bm) = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &mut bits, None, 0) else {
            let _ = DeleteDC(dc);
            return None;
        };
        let old = SelectObject(dc, bm);
        let _ = DrawIconEx(dc, 0, 0, ic, N, N, 0, None, DI_NORMAL);
        SelectObject(dc, old);
        let mut px = std::slice::from_raw_parts(bits as *const u8, (N * N * 4) as usize).to_vec();
        let _ = DeleteObject(bm);
        let _ = DeleteDC(dc);
        if !px.chunks_exact(4).any(|p| p[3] != 0) {
            px.chunks_exact_mut(4).for_each(|p| p[3] = 255);
        }
        for p in px.chunks_exact_mut(4) {
            let a = p[3] as u32;
            for c in &mut p[..3] {
                *c = (*c as u32 * a / 255) as u8;
            }
        }
        Some(ui::Img { w: N as u32, h: N as u32, px })
    }
}
/// as janelas de cada área (as das outras áreas ficam "escondidas" pelo Windows, mas a posição continua valendo)
fn load_windows() {
    let st = s();
    unsafe {
        let Ok(vdm) = CoCreateInstance::<_, IVirtualDesktopManager>(&VirtualDesktopManager, None, CLSCTX_ALL) else { return };
        let mut hs = Vec::new();
        let mut h = GetTopWindow(None).unwrap_or_default();
        while !h.0.is_null() {
            let next = GetWindow(h, GW_HWNDNEXT).unwrap_or_default();
            let ex = WINDOW_EX_STYLE(GetWindowLongW(h, GWL_EXSTYLE) as u32);
            let ok = IsWindowVisible(h).as_bool()
                && !IsIconic(h).as_bool()
                && !apps::is_shell_window(h)
                && !(ex.contains(WS_EX_TOOLWINDOW) && !ex.contains(WS_EX_APPWINDOW))
                && !(!GetWindow(h, GW_OWNER).unwrap_or_default().0.is_null() && !ex.contains(WS_EX_APPWINDOW))
                && GetWindowTextLengthW(h) > 0;
            if ok {
                let mut cloaked = 0u32;
                let _ = DwmGetWindowAttribute(h, DWMWA_CLOAKED, &mut cloaked as *mut _ as *mut _, 4);
                let mut cls = [0u16; 64];
                let n = GetClassNameW(h, &mut cls);
                let cls = String::from_utf16_lossy(&cls[..n.max(0) as usize]);
                // cloaked & 1: escondida pelo próprio app (não é de outra área)
                if cloaked & 1 == 0 && !mesa::is_desk_class(&cls) && cls != "Shell_TrayWnd" {
                    hs.push(h);
                }
            }
            h = next;
        }
        for &h in hs.iter().rev() {
            // de baixo para cima: a de cima é desenhada por último
            let Ok(d) = vdm.GetWindowDesktopId(h) else { continue };
            let Some(sp) = st.sp.iter_mut().find(|s| s.id == d) else { continue };
            let mut r = RECT::default();
            if DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, &mut r as *mut _ as *mut _, std::mem::size_of::<RECT>() as u32).is_err() {
                let _ = GetWindowRect(h, &mut r);
            }
            if r.right - r.left < 60 || r.bottom - r.top < 40 {
                continue;
            }
            let mut t = [0u16; 256];
            let n = GetWindowTextW(h, &mut t);
            sp.wins.push(WinBox { r, title: String::from_utf16_lossy(&t[..n.max(0) as usize]), icon: icon_px(h), bmp: None });
        }
    }
}
/// a área atual como está agora
fn shot() {
    let st = s();
    let (w_, h) = (st.mon.right - st.mon.left, st.mon.bottom - st.mon.top);
    unsafe {
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w_, biHeight: -h, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
        let sdc = GetDC(None);
        let mdc = CreateCompatibleDC(sdc);
        let mut bits = std::ptr::null_mut();
        if let Ok(bm) = CreateDIBSection(sdc, &bi, DIB_RGB_COLORS, &mut bits, None, 0) {
            let old = SelectObject(mdc, bm);
            let _ = BitBlt(mdc, 0, 0, w_, h, sdc, st.mon.left, st.mon.top, SRCCOPY | CAPTUREBLT);
            SelectObject(mdc, old);
            let mut px = std::slice::from_raw_parts(bits as *const u8, (w_ * h * 4) as usize).to_vec();
            px.chunks_exact_mut(4).for_each(|p| p[3] = 255);
            let mut img = ui::Img { w: w_ as u32, h: h as u32, px };
            ui::downscale(&mut img, 1600);
            st.shot = Some(img);
            let _ = DeleteObject(bm);
        }
        let _ = DeleteDC(mdc);
        ReleaseDC(None, sdc);
    }
}
fn wallpaper() {
    let st = s();
    if st.wall.is_some() {
        return;
    }
    let mut p = [0u16; 260];
    unsafe {
        let _ = SystemParametersInfoW(SPI_GETDESKWALLPAPER, p.len() as u32, Some(p.as_mut_ptr() as *mut _), SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0));
    }
    let path = from_w(&p);
    if !path.is_empty() {
        st.wall = ui::load_photo(&path, 800);
    }
}
/// a grade: colunas e linhas para n casas (mais a casa "+")
fn tile(i: usize, n: usize) -> RectF {
    let st = s();
    let cols = (n as f64).sqrt().ceil() as usize;
    let rows = n.div_ceil(cols);
    let (gap, ar) = (26.0, st.w / st.h);
    let (aw, ah) = (st.w * 0.86, st.h * 0.80);
    let mut tw = (aw - (cols - 1) as f32 * gap) / cols as f32;
    let mut th = tw / ar;
    if th * rows as f32 + (rows - 1) as f32 * gap > ah {
        th = (ah - (rows - 1) as f32 * gap) / rows as f32;
        tw = th * ar;
    }
    let x0 = (st.w - (cols as f32 * tw + (cols - 1) as f32 * gap)) / 2.0;
    let y0 = (st.h - (rows as f32 * th + (rows - 1) as f32 * gap)) / 2.0;
    let (c, r) = ((i % cols) as f32, (i / cols) as f32);
    rf(x0 + c * (tw + gap), y0 + r * (th + gap), x0 + c * (tw + gap) + tw, y0 + r * (th + gap) + th)
}
/// a última casa é o "+"
fn count() -> usize {
    let n = s().sp.len();
    n + if n < 16 { 1 } else { 0 }
}
fn prog() -> f32 {
    let st = s();
    if st.foto {
        return 1.0;
    }
    let k = anim::ease(((anim::now() - st.at) / 320.0).clamp(0.0, 1.0) as f32);
    if st.closing {
        1.0 - k
    } else {
        k
    }
}
fn lerp(a: RectF, b: RectF, t: f32) -> RectF {
    rf(a.left + (b.left - a.left) * t, a.top + (b.top - a.top) * t, a.right + (b.right - a.right) * t, a.bottom + (b.bottom - a.bottom) * t)
}
unsafe fn draw_cover(dc: &ID2D1DeviceContext, b: &ID2D1Bitmap, r: RectF) {
    let sz = b.GetSize();
    let k = ((r.right - r.left) / sz.width).max((r.bottom - r.top) / sz.height);
    let (cx, cy) = ((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0);
    dc.PushAxisAlignedClip(&r, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
    dc.DrawBitmap(b, Some(&rf(cx - sz.width * k / 2.0, cy - sz.height * k / 2.0, cx + sz.width * k / 2.0, cy + sz.height * k / 2.0)), 1.0, D2D1_INTERPOLATION_MODE_LINEAR, None, None);
    dc.PopAxisAlignedClip();
}
fn bmp(rt: &ID2D1RenderTarget, slot: &mut Option<ID2D1Bitmap>, img: &Option<ui::Img>) -> Option<ID2D1Bitmap> {
    if slot.is_none() {
        if let Some(i) = img {
            *slot = ui::bitmap(rt, i.w, i.h, &i.px);
        }
    }
    slot.clone()
}
unsafe fn draw_space(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, i: usize, r: RectF) {
    let st = s();
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    if i == st.cur {
        if let Some(b) = bmp(&rt, &mut st.shot_bmp, &st.shot) {
            dc.DrawBitmap(&b, Some(&r), 1.0, D2D1_INTERPOLATION_MODE_LINEAR, None, None);
            return;
        }
    }
    if let Some(b) = bmp(&rt, &mut st.wall_bmp, &st.wall) {
        draw_cover(dc, &b, r);
    } else {
        br.SetColor(&col(0.20, 0.28, 0.45, 1.0));
        dc.FillRectangle(&r, br);
    }
    let (kx, ky) = ((r.right - r.left) / (st.mon.right - st.mon.left) as f32, (r.bottom - r.top) / (st.mon.bottom - st.mon.top) as f32);
    let ft = &st.ft.as_ref().unwrap().0;
    let mon = st.mon;
    dc.PushAxisAlignedClip(&r, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
    for w_ in st.sp[i].wins.iter_mut() {
        // a janela em miniatura: corpo claro, a barra de metal com o nome e o ícone no meio
        let q = rf(r.left + (w_.r.left - mon.left) as f32 * kx, r.top + (w_.r.top - mon.top) as f32 * ky, r.left + (w_.r.right - mon.left) as f32 * kx, r.top + (w_.r.bottom - mon.top) as f32 * ky);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.30));
        dc.FillRoundedRectangle(&rr(rf(q.left + 1.0, q.top + 2.0, q.right + 1.0, q.bottom + 3.0), 3.0, 3.0), br);
        br.SetColor(&col(0.93, 0.93, 0.93, 0.97));
        dc.FillRoundedRectangle(&rr(q, 3.0, 3.0), br);
        let bh = 14.0f32.min((q.bottom - q.top) * 0.2);
        comum::leopard::metal(&rt, rf(q.left, q.top, q.right, q.top + bh), true, false, true, 3.0);
        if q.right - q.left > 40.0 {
            br.SetColor(&col(0.0, 0.0, 0.0, 0.8));
            dc.DrawText(&w(&w_.title), ft, &rf(q.left + 4.0, q.top, q.right - 4.0, q.top + bh), br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
        }
        if let Some(b) = bmp(&rt, &mut w_.bmp, &w_.icon) {
            let sz = 40.0f32.min((q.right - q.left).min(q.bottom - q.top - bh) * 0.5);
            let (cx, cy) = ((q.left + q.right) / 2.0, (q.top + bh + q.bottom) / 2.0);
            dc.DrawBitmap(&b, Some(&rf(cx - sz / 2.0, cy - sz / 2.0, cx + sz / 2.0, cy + sz / 2.0)), 1.0, D2D1_INTERPOLATION_MODE_LINEAR, None, None);
        }
        br.SetColor(&col(0.0, 0.0, 0.0, 0.35));
        dc.DrawRoundedRectangle(&rr(q, 3.0, 3.0), br, 0.8, None);
    }
    dc.PopAxisAlignedClip();
}
unsafe fn paint_on(dc: &ID2D1DeviceContext) {
    let st = s();
    let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
    if st.ft.is_none() {
        let a = ui::format_face("Lucida Sans Unicode", 9.0, DWRITE_FONT_WEIGHT_NORMAL);
        let _ = a.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
        let _ = a.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        let _ = a.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
        let b = ui::format_face("Lucida Sans Unicode", 13.0, DWRITE_FONT_WEIGHT_BOLD);
        let _ = b.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
        let _ = b.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        st.ft = Some((a, b));
    }
    let k = prog();
    let full = rf(0.0, 0.0, st.w, st.h);
    br.SetColor(&col(0.24, 0.24, 0.25, (k * 1.5).min(1.0))); // o cinza do Spaces do 10.5
    dc.FillRectangle(&full, &br);
    let n = count();
    let focus = st.pick.unwrap_or(st.cur); // a casa que cresce para a tela inteira (abrindo: a atual; escolhendo: a escolhida)
    let fnum = st.ft.as_ref().unwrap().1.clone();
    let fac = ui::d2d();
    let dash = fac.CreateStrokeStyle(&D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_FLAT, endCap: D2D1_CAP_STYLE_FLAT, dashCap: D2D1_CAP_STYLE_FLAT, lineJoin: D2D1_LINE_JOIN_MITER, miterLimit: 10.0, dashStyle: D2D1_DASH_STYLE_DASH, dashOffset: 0.0 }, None).ok();
    for pass in 0..2 {
        // a casa em foco por último (por cima das outras enquanto cresce)
        for i in 0..n {
            let f = i == focus;
            if (pass == 0) == f {
                continue;
            }
            let t = tile(i, n);
            let r = if f { lerp(full, t, k) } else { t };
            let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(None), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: if f { 1.0 } else { k }, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
            dc.PushLayer(&lp, None);
            if i >= st.sp.len() {
                // a casa "+": criar outra área
                br.SetColor(&col(1.0, 1.0, 1.0, if st.hover == Some(i) { 0.16 } else { 0.08 }));
                dc.FillRoundedRectangle(&rr(r, 6.0, 6.0), &br);
                br.SetColor(&col(1.0, 1.0, 1.0, 0.35));
                dc.DrawRoundedRectangle(&rr(r, 6.0, 6.0), &br, 2.0, dash.as_ref());
                let (cx, cy) = ((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0);
                let s_ = (r.right - r.left).min(r.bottom - r.top) * 0.12;
                br.SetColor(&col(1.0, 1.0, 1.0, 0.7));
                dc.DrawLine(pt(cx - s_, cy), pt(cx + s_, cy), &br, 4.0, None);
                dc.DrawLine(pt(cx, cy - s_), pt(cx, cy + s_), &br, 4.0, None);
            } else {
                br.SetColor(&col(0.0, 0.0, 0.0, 0.45 * k));
                dc.FillRectangle(&rf(r.left + 2.0, r.top + 4.0, r.right + 2.0, r.bottom + 6.0), &br);
                draw_space(dc, &br, i, r);
                if k > 0.05 {
                    // contorno: claro na área sob o mouse, mais forte na atual (como o destaque do 10.5)
                    let lit = i == st.cur || st.hover == Some(i);
                    br.SetColor(&col(1.0, 1.0, 1.0, (if i == st.cur { 0.85 } else if st.hover == Some(i) { 0.6 } else { 0.18 }) * k));
                    dc.DrawRectangle(&rf(r.left - 1.5, r.top - 1.5, r.right + 1.5, r.bottom + 1.5), &br, if lit { 3.0 } else { 1.0 }, None);
                    // o número da área num selinho embaixo
                    let nb = rf((r.left + r.right) / 2.0 - 13.0, r.bottom - 30.0, (r.left + r.right) / 2.0 + 13.0, r.bottom - 8.0);
                    br.SetColor(&col(0.0, 0.0, 0.0, 0.55 * k));
                    dc.FillRoundedRectangle(&rr(nb, 11.0, 11.0), &br);
                    br.SetColor(&col(1.0, 1.0, 1.0, 0.95 * k));
                    dc.DrawText(&w(&(i + 1).to_string()), &fnum, &nb, &br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
                }
            }
            dc.PopLayer();
        }
    }
}
fn paint() {
    let st = s();
    if !st.open {
        return;
    }
    let k = sc();
    let (wpx, hpx) = ((st.w * k).round() as i32, (st.h * k).round() as i32);
    let Some(dc) = ui::gpu_begin(&mut st.s, wpx, hpx, k) else { return };
    unsafe { paint_on(&dc) };
    ui::gpu_end(&mut st.s);
}
fn hide_now() {
    let st = s();
    ui::frame_clock(st.wnd, WM_SP_FRAME, false);
    unsafe {
        let _ = ShowWindow(st.wnd, SW_HIDE);
    }
    let to = st.pick.filter(|&p| p != st.cur && p < st.sp.len());
    st.open = false;
    st.closing = false;
    release();
    if let Some(to) = to {
        mesas::switch(to);
    }
}
fn close(pick: usize) {
    let st = s();
    if !st.open || st.closing {
        return;
    }
    st.pick = Some(pick);
    st.closing = true;
    st.at = anim::now();
    ui::frame_clock(st.wnd, WM_SP_FRAME, true);
}
fn hit(l: LPARAM) -> Option<usize> {
    let k = sc();
    let (x, y) = (get_x_lparam(l) as f32 / k, get_y_lparam(l) as f32 / k);
    let n = count();
    (0..n).find(|&i| in_rect(&tile(i, n), x, y))
}
fn reload() {
    let st = s();
    release();
    load_spaces();
    shot();
    load_windows();
    st.shot_bmp = None;
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let st = s();
    match m {
        WM_SP_FRAME => {
            ui::frame_ack(h, WM_SP_FRAME);
            paint();
            if anim::now() - st.at > 340.0 {
                if st.closing {
                    hide_now();
                } else {
                    ui::frame_clock(h, WM_SP_FRAME, false);
                }
            }
            LRESULT(0)
        }
        WM_MOUSEMOVE => {
            let i = hit(l);
            if i != st.hover && !st.closing {
                st.hover = i;
                paint();
            }
            LRESULT(0)
        }
        WM_LBUTTONUP => {
            match hit(l) {
                None => close(st.cur),
                Some(i) if i >= st.sp.len() => {
                    // "+": cria a área e mostra a grade de novo
                    if mesas::create() {
                        reload();
                        paint();
                    }
                }
                Some(i) => close(i),
            }
            LRESULT(0)
        }
        WM_KEYDOWN => {
            let vk = w_.0 as u16;
            if vk == VK_ESCAPE.0 || vk == VK_F8.0 {
                close(st.cur);
            } else if (b'1' as u16..=b'9' as u16).contains(&vk) && ((vk - b'1' as u16) as usize) < st.sp.len() {
                close((vk - b'1' as u16) as usize);
            }
            LRESULT(0)
        }
        WM_ACTIVATE => {
            if loword(w_.0) == WA_INACTIVE && st.open && !st.closing {
                close(st.cur);
            }
            LRESULT(0)
        }
        WM_CLOSE => {
            close(st.cur);
            LRESULT(0)
        }
        _ => DefWindowProcW(h, m, w_, l),
    }
}
pub fn create(hi: HINSTANCE) -> bool {
    let st = s();
    unsafe {
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellSpaces"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
        st.wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, w!("ShellSpaces"), w!("Spaces"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
    }
    if st.wnd.0.is_null() {
        return false;
    }
    apps::ours().push(st.wnd);
    st.s.hwnd = st.wnd;
    ui::gpu_soltar_escondida(&mut st.s); // escondido há 2 min: solta os buffers da tela cheia
    true
}
pub fn is_open() -> bool {
    s().open && !s().closing
}
pub fn toggle() {
    let st = s();
    if st.wnd.0.is_null() && !create(shell::inst()) {
        return;
    }
    if st.open {
        if !st.closing {
            close(st.cur);
        }
        return;
    }
    let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
    unsafe {
        let _ = GetMonitorInfoW(MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), &mut mi);
    }
    st.mon = mi.rcMonitor;
    reload();
    wallpaper();
    unsafe {
        let _ = SetWindowPos(st.wnd, HWND_TOPMOST, st.mon.left, st.mon.top, st.mon.right - st.mon.left, st.mon.bottom - st.mon.top, SWP_NOACTIVATE);
    }
    let k = sc();
    st.w = (st.mon.right - st.mon.left) as f32 / k;
    st.h = (st.mon.bottom - st.mon.top) as f32 / k;
    st.open = true;
    st.closing = false;
    st.pick = None;
    st.hover = None;
    st.at = anim::now();
    paint();
    unsafe {
        let _ = ShowWindow(st.wnd, SW_SHOW);
        let fg = GetForegroundWindow();
        let ft = if fg.0.is_null() { 0 } else { GetWindowThreadProcessId(fg, None) };
        let me = GetCurrentThreadId();
        let att = ft != 0 && ft != me && AttachThreadInput(me, ft, true).as_bool();
        let _ = SetForegroundWindow(st.wnd);
        let _ = SetFocus(st.wnd);
        if att {
            let _ = AttachThreadInput(me, ft, false);
        }
    }
    ui::frame_clock(st.wnd, WM_SP_FRAME, true);
    log!("spaces: {} áreas, atual {}", st.sp.len(), st.cur + 1);
}
/// modo foto: a grade aberta; sem foto da tela (todas as áreas com o papel de parede e as janelas de cada uma)
pub fn foto(tela_w: f32, tela_h: f32) {
    let st = s();
    st.foto = true;
    let k = ui::foto_scale();
    st.mon = RECT { left: 0, top: 0, right: (tela_w * k) as i32, bottom: (tela_h * k) as i32 };
    load_spaces();
    load_windows();
    wallpaper();
    // as janelas estão em px da tela de verdade: a foto pode ter outro tamanho, então a conta usa o monitor real
    let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
    unsafe {
        let _ = GetMonitorInfoW(MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), &mut mi);
    }
    st.mon = mi.rcMonitor;
    st.w = tela_w;
    st.h = tela_h;
    st.open = true;
    st.s.foto_pos = (0.0, 0.0);
    paint();
}