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
14.8 KB
Raw Blame
//! foto.cpp + fotogpu.cpp (namespace foto do C++; aqui fotojanela, porque foto.rs é o modo foto do Shell).
//! Foto de uma janela de outro programa: a miniatura do DWM numa janela nossa escondida (cloak) e
//! PrintWindow(PW_RENDERFULLCONTENT) dela. Vale para janelas minimizadas (o DWM guarda a última imagem) e para apps
//! Chromium/DirectX, sem tocar no programa. Uns poucos ms por janela.
//! Pela GPU: várias janelas de uma vez pela captura do Windows (Windows.Graphics.Capture), copiadas direto para
//! superfícies do compositor, sem a borda amarela e sem o cursor. Start abre todas em paralelo e as deixa abertas
//! guardando o último quadro; Grab tira as fotos na hora; Stop fecha. A que falhar volta vazia (quem chamou usa a CPU).
#![allow(dead_code)]

use std::sync::{Arc, Mutex, Weak};

use comum::windows::core::*;
use comum::windows::Foundation::TypedEventHandler;
use comum::windows::Graphics::Capture::*;
use comum::windows::Graphics::DirectX::Direct3D11::IDirect3DDevice;
use comum::windows::Graphics::DirectX::DirectXPixelFormat;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct3D11::*;
use comum::windows::Win32::Graphics::DirectComposition::IDCompositionSurface;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Dxgi::Common::*;
use comum::windows::Win32::Graphics::Dxgi::IDXGIDevice;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::Storage::Xps::{PrintWindow, PRINT_WINDOW_FLAGS};
use comum::windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED};
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::System::WinRT::Direct3D11::*;
use comum::windows::Win32::System::WinRT::Graphics::Capture::IGraphicsCaptureItemInterop;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

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

const PW_RENDERFULLCONTENT: u32 = 2;

static CAP: Global<isize> = Global::new(0);
fn ensure() -> Option<HWND> {
    let g = CAP.get();
    if *g != 0 {
        return Some(HWND(*g as *mut _));
    }
    unsafe {
        let hi = GetModuleHandleW(None).ok()?;
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(def_proc), hInstance: hi.into(), lpszClassName: w!("ShellFoto"), ..Default::default() });
        let h = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP | WS_EX_TRANSPARENT, w!("ShellFoto"), w!(""), WS_POPUP, 0, 0, 1, 1, None, None, hi, None).ok()?;
        apps::ours().push(h);
        let cloak: i32 = 1;
        let _ = DwmSetWindowAttribute(h, DWMWA_CLOAK, &cloak as *const _ as *const _, 4);
        *g = h.0 as isize;
        Some(h)
    }
}
unsafe extern "system" fn def_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    DefWindowProcW(h, m, w_, l)
}
/// cantos arredondados (o Windows 11 arredonda as janelas normais): alfa por pixel, pré-multiplicado
fn corners(px: &mut [u8], w: u32, h: u32, r: f32) {
    let rr = r.ceil() as i32;
    for y in 0..rr.min(h as i32) {
        for x in 0..rr.min(w as i32) {
            let (dx, dy) = (r - (x as f32 + 0.5), r - (y as f32 + 0.5));
            let a = (r + 0.5 - (dx * dx + dy * dy).sqrt()).clamp(0.0, 1.0);
            if a >= 1.0 {
                continue;
            }
            let (x, y) = (x as u32, y as u32);
            for (cx, cy) in [(x, y), (w - 1 - x, y), (x, h - 1 - y), (w - 1 - x, h - 1 - y)] {
                let i = ((cy as usize) * w as usize + cx as usize) * 4;
                for k in 0..4 {
                    px[i + k] = (px[i + k] as f32 * a).round() as u8;
                }
            }
        }
    }
}
/// foto pela CPU: BGRA pré-multiplicado, (px, w, h)
pub fn window(h: HWND, src: RECT, corner: f32) -> Option<(Vec<u8>, u32, u32)> {
    let cap = ensure()?;
    unsafe {
        if !IsWindow(h).as_bool() {
            return None;
        }
        let (w, hh) = ((src.right - src.left).max(0) as u32, (src.bottom - src.top).max(0) as u32);
        if !(4..=16384).contains(&w) || !(4..=16384).contains(&hh) {
            return None;
        }
        let th = DwmRegisterThumbnail(cap, h).ok()?;
        let _ = SetWindowPos(cap, None, 0, 0, w as i32, hh as i32, SWP_NOACTIVATE | SWP_NOZORDER | SWP_SHOWWINDOW);
        let tp = DWM_THUMBNAIL_PROPERTIES {
            dwFlags: DWM_TNP_RECTDESTINATION | DWM_TNP_RECTSOURCE | DWM_TNP_VISIBLE | DWM_TNP_OPACITY | DWM_TNP_SOURCECLIENTAREAONLY,
            rcSource: src,
            rcDestination: RECT { left: 0, top: 0, right: w as i32, bottom: hh as i32 },
            fVisible: true.into(),
            opacity: 255,
            fSourceClientAreaOnly: false.into(),
        };
        let _ = DwmUpdateThumbnailProperties(th, &tp);
        let sdc = GetDC(None);
        let mdc = CreateCompatibleDC(sdc);
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w as i32, biHeight: -(hh as i32), biPlanes: 1, biBitCount: 32, ..Default::default() }, ..Default::default() };
        let mut bits: *mut core::ffi::c_void = std::ptr::null_mut();
        let mut out = None;
        if let Ok(bm) = CreateDIBSection(sdc, &bi, DIB_RGB_COLORS, &mut bits, None, 0) {
            let old = SelectObject(mdc, bm);
            let mut got = false;
            for tries in 0..2 {
                if got {
                    break;
                }
                if tries > 0 {
                    let _ = DwmFlush();
                }
                if !PrintWindow(cap, mdc, PRINT_WINDOW_FLAGS(PW_RENDERFULLCONTENT)).as_bool() {
                    continue;
                }
                let _ = GdiFlush();
                let p = std::slice::from_raw_parts(bits as *const u32, (w * hh) as usize);
                'y: for y in (0..hh).step_by(7) {
                    for x in (0..w).step_by(7) {
                        if p[(y * w + x) as usize] & 0xFFFFFF != 0 {
                            got = true;
                            break 'y;
                        }
                    }
                }
            }
            if got {
                let mut px = std::slice::from_raw_parts(bits as *const u8, (w * hh * 4) as usize).to_vec();
                for i in (3..px.len()).step_by(4) {
                    px[i] = 255; // opaca
                }
                if corner > 0.0 {
                    corners(&mut px, w, hh, corner);
                }
                out = Some((px, w, hh));
            }
            SelectObject(mdc, old);
            let _ = DeleteObject(bm);
        }
        let _ = DeleteDC(mdc);
        ReleaseDC(None, sdc);
        let _ = DwmUnregisterThumbnail(th);
        let _ = ShowWindow(cap, SW_HIDE);
        out
    }
}
// ---- pela GPU
struct Cap {
    h: isize,
    src: RECT,
    item: Mutex<Option<GraphicsCaptureItem>>,
    pool: Mutex<Option<Direct3D11CaptureFramePool>>,
    session: Mutex<Option<GraphicsCaptureSession>>,
    /// o último quadro que chegou
    frame: Mutex<Option<Direct3D11CaptureFrame>>,
    /// sinal: chegou o primeiro
    ev: isize,
    failed: Mutex<bool>,
}
unsafe impl Send for Cap {}
unsafe impl Sync for Cap {}
pub struct Live {
    caps: Vec<Arc<Cap>>,
}
pub struct Gpu {
    pub surf: Option<IDCompositionSurface>,
    pub w: u32,
    pub h: u32,
}
static DEV: Global<Option<IDirect3DDevice>> = Global::new(None);
fn dev() -> Option<IDirect3DDevice> {
    let g = DEV.get();
    if g.is_none() {
        let d3d = ui::d3d()?;
        let dx: IDXGIDevice = d3d.cast().ok()?;
        *g = unsafe { CreateDirect3D11DeviceFromDXGIDevice(&dx) }.ok().and_then(|i| i.cast().ok());
    }
    g.clone()
}
pub fn start(hs: &[HWND], srcs: &[RECT]) -> Option<Live> {
    if ui::d3d().is_none() || ui::comp().is_none() || hs.is_empty() {
        return None;
    }
    if !GraphicsCaptureSession::IsSupported().unwrap_or(false) {
        return None;
    }
    let dv = dev()?;
    let n = hs.len().min(60);
    let mut live = Live { caps: Vec::with_capacity(n) };
    let mut ths = Vec::new(); // todas ao mesmo tempo, uma thread por janela
    for i in 0..n {
        let ev = unsafe { CreateEventW(None, true, false, None) }.map(|e| e.0 as isize).unwrap_or(0);
        let c = Arc::new(Cap { h: hs[i].0 as isize, src: srcs[i], item: Mutex::new(None), pool: Mutex::new(None), session: Mutex::new(None), frame: Mutex::new(None), ev, failed: Mutex::new(false) });
        live.caps.push(c.clone());
        let dv = dv.clone();
        struct SendDev(IDirect3DDevice);
        unsafe impl Send for SendDev {}
        let sd = SendDev(dv);
        ths.push(std::thread::spawn(move || {
            let sd = sd;
            unsafe {
                let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
            }
            let r = (|| -> Result<()> {
                let interop = factory::<GraphicsCaptureItem, IGraphicsCaptureItemInterop>()?;
                let item: GraphicsCaptureItem = unsafe { interop.CreateForWindow(HWND(c.h as *mut _)) }?;
                let pool = Direct3D11CaptureFramePool::CreateFreeThreaded(&sd.0, DirectXPixelFormat::B8G8R8A8UIntNormalized, 2, item.Size()?)?;
                let ses = pool.CreateCaptureSession(&item)?;
                let _ = ses.SetIsCursorCaptureEnabled(false);
                let _ = ses.SetIsBorderRequired(false);
                let wk: Weak<Cap> = Arc::downgrade(&c); // um quadro atrasado depois do Stop não encontra nada
                pool.FrameArrived(&TypedEventHandler::<Direct3D11CaptureFramePool, IInspectable>::new(move |p, _| {
                    let Some(c) = wk.upgrade() else { return Ok(()) };
                    let Some(p) = p.as_ref() else { return Ok(()) };
                    let Ok(f) = p.TryGetNextFrame() else { return Ok(()) };
                    let old = c.frame.lock().unwrap().replace(f);
                    if let Some(o) = old {
                        let _ = o.Close(); // devolve o buffer: o próximo quadro pode chegar
                    }
                    unsafe {
                        let _ = SetEvent(HANDLE(c.ev as *mut _));
                    }
                    Ok(())
                }))?;
                ses.StartCapture()?;
                *c.item.lock().unwrap() = Some(item);
                *c.pool.lock().unwrap() = Some(pool);
                *c.session.lock().unwrap() = Some(ses);
                Ok(())
            })();
            if r.is_err() {
                *c.failed.lock().unwrap() = true;
                unsafe {
                    let _ = SetEvent(HANDLE(c.ev as *mut _));
                }
            }
            unsafe { CoUninitialize() };
        }));
    }
    for t in ths {
        let _ = t.join();
    }
    Some(live)
}
pub fn grab(live: Option<&Live>, timeout_ms: u32) -> Vec<Gpu> {
    let Some(live) = live else { return Vec::new() };
    let mut out: Vec<Gpu> = live.caps.iter().map(|_| Gpu { surf: None, w: 0, h: 0 }).collect();
    let (Some(d3d), Some(cd)) = (ui::d3d(), ui::comp()) else { return out };
    unsafe {
        let evs: Vec<HANDLE> = live.caps.iter().filter(|c| c.ev != 0).map(|c| HANDLE(c.ev as *mut _)).collect();
        if !evs.is_empty() {
            let _ = WaitForMultipleObjects(&evs, true, timeout_ms);
        }
        let Ok(ctx) = d3d.GetImmediateContext() else { return out };
        for (i, c) in live.caps.iter().enumerate() {
            if *c.failed.lock().unwrap() {
                continue;
            }
            let fr = c.frame.lock().unwrap(); // o quadro não é trocado enquanto copia
            let Some(f) = fr.as_ref() else { continue };
            let r = (|| -> Result<Option<Gpu>> {
                let access: IDirect3DDxgiInterfaceAccess = f.Surface()?.cast()?;
                let tex: ID3D11Texture2D = access.GetInterface()?;
                let mut d = D3D11_TEXTURE2D_DESC::default();
                tex.GetDesc(&mut d);
                let cs = f.ContentSize()?;
                // o quadro é a janela inteira (com a borda invisível), como a miniatura do DWM: o mesmo recorte
                let h = HWND(c.h as *mut _);
                let mut wr = RECT::default();
                let _ = GetWindowRect(h, &mut wr);
                let mut s = c.src;
                let (fw, fh) = (cs.Width.min(d.Width as i32), cs.Height.min(d.Height as i32));
                if fw != wr.right - wr.left || fh != wr.bottom - wr.top {
                    // quadro só da parte visível
                    let mut efb = wr;
                    let _ = DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, &mut efb as *mut _ as *mut _, std::mem::size_of::<RECT>() as u32);
                    let (dx, dy) = (efb.left - wr.left, efb.top - wr.top);
                    s = RECT { left: s.left - dx, top: s.top - dy, right: s.right - dx, bottom: s.bottom - dy };
                }
                s = RECT { left: s.left.clamp(0, fw), right: s.right.clamp(0, fw), top: s.top.clamp(0, fh), bottom: s.bottom.clamp(0, fh) };
                let (w, hh) = ((s.right - s.left) as u32, (s.bottom - s.top) as u32);
                if w < 4 || hh < 4 {
                    return Ok(None);
                }
                let surf = cd.CreateSurface(w, hh, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ALPHA_MODE_PREMULTIPLIED)?;
                let mut off = POINT::default();
                let dst: ID3D11Texture2D = surf.BeginDraw(None, &mut off)?;
                let bx = D3D11_BOX { left: s.left as u32, top: s.top as u32, front: 0, right: s.right as u32, bottom: s.bottom as u32, back: 1 };
                ctx.CopySubresourceRegion(&dst, 0, off.x as u32, off.y as u32, 0, &tex, 0, Some(&bx));
                drop(dst);
                surf.EndDraw()?;
                Ok(Some(Gpu { surf: Some(surf), w, h: hh }))
            })();
            if let Ok(Some(g)) = r {
                out[i] = g;
            }
        }
    }
    out
}
pub fn stop(live: Live) {
    for c in &live.caps {
        if let Some(s) = c.session.lock().unwrap().take() {
            let _ = s.Close();
        }
        if let Some(p) = c.pool.lock().unwrap().take() {
            let _ = p.Close(); // fora da trava do quadro: um quadro chegando termina antes
        }
        if let Some(f) = c.frame.lock().unwrap().take() {
            let _ = f.Close();
        }
        c.item.lock().unwrap().take();
        if c.ev != 0 {
            unsafe {
                let _ = CloseHandle(HANDLE(c.ev as *mut _));
            }
        }
    }
}
/// tudo de uma vez: abre, fotografa e fecha
pub fn windows(hs: &[HWND], srcs: &[RECT], timeout_ms: u32) -> Vec<Gpu> {
    let t0 = anim::now();
    let Some(live) = start(hs, srcs) else { return hs.iter().map(|_| Gpu { surf: None, w: 0, h: 0 }).collect() };
    let t1 = anim::now();
    let mut out = grab(Some(&live), timeout_ms);
    let t2 = anim::now();
    stop(live);
    out.resize_with(hs.len(), || Gpu { surf: None, w: 0, h: 0 });
    log!("foto (GPU): {} janelas, abrir capturas {:.1} ms, fotos {:.1} ms", hs.len(), t1 - t0, t2 - t1);
    out
}