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
40.0 KB
Raw Blame
//! Porte de src\finder\gfx.cpp, tahoe.cpp e shadow.cpp: o que o Finder, o Notas, o Monitor de Atividade e o Ajustes
//! usam para a janela do Tahoe.
//!
//! - `Gfx`: Direct2D sobre DirectComposition (swap chain com alfa pré-multiplicado ligada à janela, que é criada com
//!   WS_EX_NOREDIRECTIONBITMAP). O conteúdo tem alfa real; o vidro aparece onde se desenha transparente.
//! - `frame`/`size`/`set_panel`: o vidro da Composição por baixo da swap chain (HostBackdropBrush desfocado e
//!   saturado), recortado no painel da barra lateral; o DWM fica sem o acrílico, sem borda e sem cantos.
//! - `push_window_clip`/`window_rim`/`panel`/`capsule`: o canto contínuo da janela e as peças de vidro em D2D.
//! - `scene_begin`/`scene_end`/`scene_draw`: a borda de rolagem (o que passa sob as barras fica desfocado e some).
//! - `Shadow`: a sombra grande e difusa do Mac numa janela em camadas logo abaixo da janela.
use std::cell::RefCell;
use std::collections::HashMap;

use windows::core::*;
use windows::Foundation::Numerics::Vector2;
use windows::Foundation::{IPropertyValue, PropertyValue};
use windows::Graphics::Effects::*;
use windows::System::DispatcherQueueController;
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::Graphics::Direct3D::*;
use windows::Win32::Graphics::Direct3D11::*;
use windows::Win32::Graphics::DirectComposition::*;
use windows::Win32::Graphics::Dwm::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::Registry::*;
use windows::Win32::System::WinRT::Composition::*;
use windows::Win32::System::WinRT::Graphics::Direct2D::*;
use windows::Win32::System::WinRT::*;
use windows::Win32::UI::HiDpi::GetDpiForWindow;
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::UI::Color;
use windows::UI::Composition::Desktop::DesktopWindowTarget;
use windows::UI::Composition::*;

use crate::{col, mat, pt, rf, rr, squircle, Cor, Global, RectF};

// =====================================================================================================================
// gfx.cpp
/// a fábrica do app (app2d): geometrias e o contexto de desenho têm de vir da mesma fábrica
/// (D2DERR_WRONG_FACTORY, 0x88990012), por isso o dispositivo nasce dela e não de uma fábrica própria
fn fabrica() -> Option<ID2D1Factory1> {
    if crate::app2d::s().d2d.is_none() {
        unsafe { D2D1CreateFactory::<ID2D1Factory1>(D2D1_FACTORY_TYPE_SINGLE_THREADED, None).ok() }
    } else {
        crate::app2d::d2d().cast().ok()
    }
}
pub struct Gfx {
    d3d: ID3D11Device,
    pub d2d: ID2D1Factory1,
    pub dc: ID2D1DeviceContext,
    swap: IDXGISwapChain1,
    #[allow(dead_code)]
    dcomp: IDCompositionDevice,
    #[allow(dead_code)]
    target: IDCompositionTarget,
    #[allow(dead_code)]
    visual: IDCompositionVisual,
    backbuffer: Option<ID2D1Bitmap1>,
}
impl Gfx {
    /// D3D11 (com suporte a vídeo: o Quick Look toca vídeo neste dispositivo) na placa que liga a tela, D2D e a swap
    /// chain da Composição na janela. None: sem GPU utilizável nem WARP (quem chama cai no HwndRenderTarget).
    pub fn init(hwnd: HWND) -> Option<Gfx> {
        unsafe {
            let flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT;
            let mut d3d: Option<ID3D11Device> = None;
            if let Some(ad) = crate::gpu::adaptador_da_tela() {
                let _ = D3D11CreateDevice(&ad, D3D_DRIVER_TYPE_UNKNOWN, HMODULE::default(), flags, None, D3D11_SDK_VERSION, Some(&mut d3d), None, None);
            }
            if d3d.is_none() {
                let _ = D3D11CreateDevice(None, D3D_DRIVER_TYPE_HARDWARE, HMODULE::default(), D3D11_CREATE_DEVICE_BGRA_SUPPORT, None, D3D11_SDK_VERSION, Some(&mut d3d), None, None);
            }
            if d3d.is_none() {
                // sem GPU utilizável (VM, área remota): renderizador por software
                let _ = D3D11CreateDevice(None, D3D_DRIVER_TYPE_WARP, HMODULE::default(), D3D11_CREATE_DEVICE_BGRA_SUPPORT, None, D3D11_SDK_VERSION, Some(&mut d3d), None, None);
            }
            let d3d = d3d?;
            let dxgi: IDXGIDevice = d3d.cast().ok()?;
            let d2d: ID2D1Factory1 = fabrica()?;
            let dev = d2d.CreateDevice(&dxgi).ok()?;
            let dc = dev.CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE).ok()?;
            dc.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE); // ClearType não combina com fundo transparente
            let mut rc = RECT::default();
            let _ = GetClientRect(hwnd, &mut rc);
            let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
            let desc = DXGI_SWAP_CHAIN_DESC1 {
                Width: rc.right.max(1) as u32,
                Height: rc.bottom.max(1) as u32,
                Format: DXGI_FORMAT_B8G8R8A8_UNORM,
                SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
                BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
                BufferCount: 2,
                Scaling: DXGI_SCALING_STRETCH,
                SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,
                AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED,
                ..Default::default()
            };
            let swap = factory.CreateSwapChainForComposition(&d3d, &desc, None).ok()?;
            let dcomp: IDCompositionDevice = DCompositionCreateDevice(&dxgi).ok()?;
            let target = dcomp.CreateTargetForHwnd(hwnd, true).ok()?;
            let visual = dcomp.CreateVisual().ok()?;
            visual.SetContent(&swap).ok()?;
            target.SetRoot(&visual).ok()?;
            dcomp.Commit().ok()?;
            let mut g = Gfx { d3d, d2d, dc, swap, dcomp, target, visual, backbuffer: None };
            g.bind();
            Some(g)
        }
    }
    fn bind(&mut self) {
        unsafe {
            let Ok(surface) = self.swap.GetBuffer::<IDXGISurface>(0) else { return };
            let props = D2D1_BITMAP_PROPERTIES1 {
                pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
                dpiX: 96.0,
                dpiY: 96.0,
                bitmapOptions: D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
                colorContext: std::mem::ManuallyDrop::new(None),
            };
            self.backbuffer = self.dc.CreateBitmapFromDxgiSurface(&surface, Some(&props)).ok();
            if let Some(b) = &self.backbuffer {
                self.dc.SetTarget(b);
            }
        }
    }
    pub fn resize(&mut self, w: u32, h: u32) {
        if w == 0 || h == 0 {
            return;
        }
        unsafe {
            self.dc.SetTarget(None);
            self.backbuffer = None;
            let _ = self.swap.ResizeBuffers(2, w, h, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG(0));
        }
        self.bind();
    }
    /// já com BeginDraw; desenhe em DIPs
    pub fn begin(&self, dpi: f32) -> Option<ID2D1DeviceContext> {
        self.backbuffer.as_ref()?;
        unsafe {
            self.dc.SetDpi(dpi, dpi);
            self.dc.BeginDraw();
        }
        Some(self.dc.clone())
    }
    /// EndDraw + Present
    pub fn end(&self) -> Result<()> {
        unsafe {
            let r = self.dc.EndDraw(None, None);
            let _ = self.swap.Present(1, DXGI_PRESENT(0));
            r
        }
    }
    /// pré-multiplicado
    pub fn create_bitmap_bgra(&self, w: u32, h: u32, px: &[u8], stride: u32) -> Option<ID2D1Bitmap> {
        let props = D2D1_BITMAP_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0 };
        let rt: ID2D1RenderTarget = self.dc.cast().ok()?;
        unsafe { rt.CreateBitmap(D2D_SIZE_U { width: w, height: h }, Some(px.as_ptr() as *const _), stride, &props).ok() }
    }
    pub fn device(&self) -> &ID3D11Device {
        &self.d3d
    }
    /// ID3D11Texture2D BGRA -> bitmap (sem cópia)
    pub fn bitmap_from_texture(&self, tex: &IUnknown) -> Option<ID2D1Bitmap> {
        unsafe {
            let surface: IDXGISurface = tex.cast().ok()?;
            let props = D2D1_BITMAP_PROPERTIES1 {
                pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_IGNORE },
                dpiX: 96.0,
                dpiY: 96.0,
                bitmapOptions: D2D1_BITMAP_OPTIONS_NONE,
                colorContext: std::mem::ManuallyDrop::new(None),
            };
            self.dc.CreateBitmapFromDxgiSurface(&surface, Some(&props)).ok().and_then(|b| b.cast().ok())
        }
    }
}

// =====================================================================================================================
// tahoe.cpp: o vidro da Composição por baixo da swap chain
#[windows::core::implement(IGraphicsEffect, IGraphicsEffectSource, IGraphicsEffectD2D1Interop)]
struct Fx {
    name: RefCell<HSTRING>,
    id: GUID,
    src: IGraphicsEffectSource,
    props: Vec<(u32, IInspectable)>,
}
impl IGraphicsEffect_Impl for Fx_Impl {
    fn Name(&self) -> Result<HSTRING> {
        Ok(self.name.borrow().clone())
    }
    fn SetName(&self, n: &HSTRING) -> Result<()> {
        *self.name.borrow_mut() = n.clone();
        Ok(())
    }
}
impl IGraphicsEffectSource_Impl for Fx_Impl {}
impl IGraphicsEffectD2D1Interop_Impl for Fx_Impl {
    fn GetEffectId(&self) -> Result<GUID> {
        Ok(self.id)
    }
    fn GetNamedPropertyMapping(&self, _n: &PCWSTR, _i: *mut u32, _m: *mut GRAPHICS_EFFECT_PROPERTY_MAPPING) -> Result<()> {
        Err(E_INVALIDARG.into())
    }
    fn GetPropertyCount(&self) -> Result<u32> {
        Ok(self.props.len() as u32)
    }
    fn GetProperty(&self, index: u32) -> Result<IPropertyValue> {
        self.props.iter().find(|(i, _)| *i == index).map(|(_, v)| v.cast()).unwrap_or(Err(E_INVALIDARG.into()))
    }
    fn GetSource(&self, index: u32) -> Result<IGraphicsEffectSource> {
        if index != 0 {
            return Err(E_INVALIDARG.into());
        }
        Ok(self.src.clone())
    }
    fn GetSourceCount(&self) -> Result<u32> {
        Ok(1)
    }
}

struct Win {
    #[allow(dead_code)]
    target: DesktopWindowTarget,
    root: ContainerVisual,
    geo: CompositionRoundedRectangleGeometry,
    tint: CompositionColorBrush,
}
#[derive(Default)]
struct Est {
    dq: Option<DispatcherQueueController>,
    comp: Option<Compositor>,
    wins: HashMap<isize, Win>,
    dark: bool,
    log: Option<fn(&str)>,
}
static EST: Global<Option<Est>> = Global::new(None);
fn est() -> &'static mut Est {
    EST.get().get_or_insert_with(Est::default)
}
/// para onde vão as mensagens de erro (o log do app)
pub fn set_log(f: fn(&str)) {
    est().log = Some(f);
}
fn log(s: &str) {
    if let Some(f) = est().log {
        f(s);
    }
}

fn dwm(h: HWND, tahoe: bool) {
    unsafe {
        let corner: i32 = if tahoe { 1 } else { 0 }; // DWMWCP_DONOTROUND / DEFAULT
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
        if tahoe {
            let none: u32 = 0xFFFF_FFFE; // DWMWA_COLOR_NONE: sem a borda retangular do DWM
            let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(34), &none as *const _ as *const _, 4);
            let bd: i32 = 1; // DWMSBT_NONE: o desfoque vem da Composição, recortado no raio certo
            let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(38), &bd as *const _ as *const _, 4);
            let on: i32 = 1;
            let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(17), &on as *const _ as *const _, 4); // DWMWA_USE_HOSTBACKDROPBRUSH
        }
        // sem sombra retangular do DWM no Tahoe (a sombra redonda é a de Shadow)
        let pol = if tahoe { DWMNCRP_DISABLED } else { DWMNCRP_USEWINDOWSTYLE };
        let _ = DwmSetWindowAttribute(h, DWMWA_NCRENDERING_POLICY, &pol as *const _ as *const _, 4);
    }
}
/// fundo da janela desfocado (16) e com a cor reforçada (1,65), como no Shell; sem o efeito, o fundo puro
fn frost(comp: &Compositor) -> Result<CompositionBrush> {
    let r = (|| -> Result<CompositionBrush> {
        let src: IGraphicsEffectSource = CompositionEffectSourceParameter::Create(&HSTRING::from("fundo"))?.cast()?;
        let blur: IGraphicsEffect = Fx {
            name: RefCell::new(HSTRING::from("fosco")),
            id: CLSID_D2D1GaussianBlur,
            src,
            props: vec![
                (D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION.0 as u32, PropertyValue::CreateSingle(16.0)?),
                (D2D1_GAUSSIANBLUR_PROP_OPTIMIZATION.0 as u32, PropertyValue::CreateUInt32(D2D1_GAUSSIANBLUR_OPTIMIZATION_BALANCED.0 as u32)?),
                (D2D1_GAUSSIANBLUR_PROP_BORDER_MODE.0 as u32, PropertyValue::CreateUInt32(D2D1_BORDER_MODE_HARD.0 as u32)?),
            ],
        }
        .into();
        let sat: IGraphicsEffect = Fx { name: RefCell::new(HSTRING::from("vibra")), id: CLSID_D2D1Saturation, src: blur.cast()?, props: vec![(D2D1_SATURATION_PROP_SATURATION.0 as u32, PropertyValue::CreateSingle(1.65)?)] }.into();
        let b = comp.CreateEffectFactory(&sat)?.CreateBrush()?;
        b.SetSourceParameter(&HSTRING::from("fundo"), &comp.CreateHostBackdropBrush()?)?;
        b.cast()
    })();
    match r {
        Ok(b) => Ok(b),
        Err(e) => {
            log(&format!("tahoe: fosco indisponível ({:08X} {})", e.code().0 as u32, e.message()));
            comp.CreateHostBackdropBrush()?.cast()
        }
    }
}
fn ucol(c: Cor) -> Color {
    let c8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
    Color { A: c8(c.a), R: c8(c.r), G: c8(c.g), B: c8(c.b) }
}
fn comp() -> Result<Compositor> {
    let e = est();
    if let Some(c) = &e.comp {
        return Ok(c.clone());
    }
    // o menu de contexto pode já ter criado a fila desta thread: uma segunda é recusada pelo Windows
    if windows::System::DispatcherQueue::GetForCurrentThread().is_err() {
        let o = DispatcherQueueOptions { dwSize: std::mem::size_of::<DispatcherQueueOptions>() as u32, threadType: DQTYPE_THREAD_CURRENT, apartmentType: DQTAT_COM_NONE };
        e.dq = Some(unsafe { CreateDispatcherQueueController(o)? });
    }
    let c = Compositor::new()?;
    e.comp = Some(c.clone());
    Ok(c)
}
/// janela de cantos grandes com o vidro da Composição (ou de volta ao DWM)
pub fn frame(h: HWND, on: bool) {
    let k = h.0 as isize;
    if !on {
        if let Some(w) = est().wins.get(&k) {
            let _ = w.root.SetIsVisible(false);
        }
        dwm(h, false);
        return;
    }
    dwm(h, true);
    if let Some(w) = est().wins.get(&k) {
        let _ = w.root.SetIsVisible(true);
        return;
    }
    let r = (|| -> Result<Win> {
        let comp = comp()?;
        let interop: ICompositorDesktopInterop = comp.cast()?;
        // por baixo (isTopmost false): a swap chain do D2D fica por cima, no alvo do DirectComposition
        let target = unsafe { interop.CreateDesktopWindowTarget(h, false)? };
        let root = comp.CreateContainerVisual()?;
        root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
        let blur = comp.CreateSpriteVisual()?;
        blur.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
        blur.SetBrush(&frost(&comp)?)?;
        let tint_v = comp.CreateSpriteVisual()?;
        tint_v.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
        let tint = comp.CreateColorBrush()?;
        tint_v.SetBrush(&tint)?;
        root.Children()?.InsertAtTop(&blur)?;
        root.Children()?.InsertAtTop(&tint_v)?;
        let geo = comp.CreateRoundedRectangleGeometry()?;
        root.SetClip(&comp.CreateGeometricClipWithGeometry(&geo)?)?;
        target.SetRoot(&root)?;
        Ok(Win { target, root, geo, tint })
    })();
    match r {
        Ok(w) => {
            est().wins.insert(k, w);
            let dark = est().dark;
            size(h, dark, false);
        }
        Err(e) => log(&format!("tahoe: vidro indisponível ({:08X})", e.code().0 as u32)),
    }
}
pub fn is_dark_theme() -> bool {
    est().dark
}
/// acompanha o tema (o vidro fica só no painel da barra lateral, recortado por set_panel)
pub fn size(h: HWND, dark: bool, reduce: bool) {
    est().dark = dark;
    let Some(w) = est().wins.get(&(h.0 as isize)) else { return };
    // a "face" do vidro da barra lateral (guia macOS26-Theme-Reference, seção 29): escuro 74 % de um cinza 0,176; claro
    // 71 % de 0,95. Reduzir transparência: quase opaco.
    let a = if reduce {
        0.97
    } else if dark {
        0.74
    } else {
        0.71
    };
    let _ = w.tint.SetColor(ucol(if dark { col(0.176, 0.176, 0.185, a) } else { col(0.95, 0.95, 0.955, a) }));
}
/// Recorte do vidro = o painel flutuante da barra lateral (DIPs). Fora dele a janela é só o desenho D2D.
pub fn set_panel(h: HWND, r: RectF, radius: f32) {
    let Some(w) = est().wins.get(&(h.0 as isize)) else { return };
    let k = unsafe { GetDpiForWindow(h) } as f32 / 96.0;
    let g = &w.geo;
    if r.right <= r.left || r.bottom <= r.top {
        let _ = g.SetSize(Vector2 { X: 0.0, Y: 0.0 }); // sem painel de vidro (Golden Gate)
        return;
    }
    // 1 px para FORA: o conteúdo opaco do D2D cobre a sobra; para dentro, os pixels de borda mostravam um tracejado
    let _ = g.SetOffset(Vector2 { X: r.left * k - 1.0, Y: r.top * k - 1.0 });
    let _ = g.SetSize(Vector2 { X: (r.right - r.left) * k + 2.0, Y: (r.bottom - r.top) * k + 2.0 });
    let rr_ = radius * k * 0.5; // menor que o canto contínuo (D2D): o vidro sempre cobre a curva toda
    let _ = g.SetCornerRadius(Vector2 { X: rr_, Y: rr_ });
}
/// cantos das janelas: 26 pt no Tahoe, 16 pt no Golden Gate
pub fn window_r(golden: bool) -> f32 {
    if golden {
        16.0
    } else {
        26.0
    }
}
/// raio atual da janela em DIPs (0 maximizada)
pub fn radius(h: HWND, golden: bool) -> f32 {
    if unsafe { IsZoomed(h).as_bool() } {
        0.0
    } else {
        window_r(golden)
    }
}

unsafe fn factory(dc: &ID2D1RenderTarget) -> ID2D1Factory {
    dc.GetFactory().unwrap()
}
fn grow(r: RectF, d: f32) -> RectF {
    rf(r.left - d, r.top - d, r.right + d, r.bottom + d)
}
unsafe fn gradient(dc: &ID2D1RenderTarget, stops: &[(f32, Cor)], a: (f32, f32), b: (f32, f32)) -> Option<ID2D1LinearGradientBrush> {
    crate::linear(dc, stops, pt(a.0, a.1), pt(b.0, b.1))
}
/// Cápsula de vidro (botões da barra de ferramentas, campos, painéis): corpo claro translúcido, sombra curta e
/// difusa, contorno especular claro em cima e uma linha escura fina embaixo. radius < 0: meia altura.
pub unsafe fn capsule(dc: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, r: RectF, mut radius: f32, dark: bool, lift: f32) {
    if radius < 0.0 {
        radius = (r.bottom - r.top) / 2.0;
    }
    for i in (1..=3).rev() {
        let k = i as f32 * 1.2 * lift;
        br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.06 } else { 0.035 } * lift));
        dc.FillRoundedRectangle(&rr(rf(r.left - k * 0.5, r.top + k * 0.4, r.right + k * 0.5, r.bottom + k), radius + k * 0.5, radius + k * 0.5), br);
    }
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.075) } else { col(1.0, 1.0, 1.0, 0.94) });
    dc.FillRoundedRectangle(&rr(r, radius, radius), br);
    let st = if dark {
        [(0.0, col(1.0, 1.0, 1.0, 0.20)), (0.5, col(1.0, 1.0, 1.0, 0.05)), (1.0, col(1.0, 1.0, 1.0, 0.10))]
    } else {
        [(0.0, col(0.0, 0.0, 0.0, 0.05)), (0.5, col(0.0, 0.0, 0.0, 0.07)), (1.0, col(0.0, 0.0, 0.0, 0.12))]
    };
    if let Some(lg) = gradient(dc, &st, (0.0, r.top), (0.0, r.bottom)) {
        dc.DrawRoundedRectangle(&rr(rf(r.left + 0.25, r.top + 0.25, r.right - 0.25, r.bottom - 0.25), radius, radius), &lg, 0.6, None);
    }
    if !dark {
        br.SetColor(&col(1.0, 1.0, 1.0, 0.9));
        dc.DrawRoundedRectangle(&rr(rf(r.left + 1.0, r.top + 1.0, r.right - 1.0, r.bottom - 1.0), radius - 1.0, radius - 1.0), br, 0.6, None);
    }
}
/// Painel de vidro flutuante (barra lateral): transparente por dentro, contorno especular e borda fina por fora
pub unsafe fn panel(dc: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, r: RectF, radius: f32, dark: bool) {
    let f = factory(dc);
    let body = squircle::squircle(&f, r, radius);
    let inner = squircle::squircle(&f, grow(r, -0.5), radius - 0.5);
    let outer = squircle::squircle(&f, grow(r, 0.5), radius + 0.5);
    let a = |d: f32, l: f32| if dark { d } else { l };
    br.SetColor(&col(1.0, 1.0, 1.0, a(0.03, 0.10))); // reflexo suave
    if let Some(b) = &body {
        dc.FillGeometry(b, br, None);
    }
    if let Some(i) = &inner {
        let st = [(0.0, col(1.0, 1.0, 1.0, a(0.34, 0.95))), (0.25, col(1.0, 1.0, 1.0, a(0.08, 0.45))), (0.75, col(1.0, 1.0, 1.0, a(0.05, 0.35))), (1.0, col(1.0, 1.0, 1.0, a(0.22, 0.80)))];
        if let Some(lg) = gradient(dc, &st, (r.left, r.top), (r.right, r.bottom)) {
            dc.DrawGeometry(i, &lg, 1.0, None);
        }
    }
    br.SetColor(&col(0.0, 0.0, 0.0, a(0.40, 0.08))); // borda escura fina por fora: 1 px inteiro
    if let Some(o) = &outer {
        dc.DrawGeometry(o, br, 1.0, None);
    }
}
/// Contorno da janela inteira (o DWM não desenha borda no Tahoe): linha fina no mesmo canto contínuo
pub unsafe fn window_rim(dc: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, w: f32, h: f32, radius: f32, dark: bool) {
    let f = factory(dc);
    let Some(g) = squircle::squircle(&f, rf(0.5, 0.5, w - 0.5, h - 0.5), radius - 0.5) else { return };
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.16) });
    dc.DrawGeometry(&g, br, 1.0, None);
}
/// Tudo o que vem depois fica recortado no contorno da janela (canto contínuo). PopLayer depois, se true.
pub unsafe fn push_window_clip(dc: &ID2D1DeviceContext, w: f32, h: f32, radius: f32) -> bool {
    if radius <= 0.0 {
        return false;
    }
    let f = factory(&dc.cast().unwrap());
    let Some(g) = squircle::squircle(&f, rf(0.0, 0.0, w, h), radius) else { return false };
    let lp = D2D1_LAYER_PARAMETERS1 {
        contentBounds: rf(-1e9, -1e9, 1e9, 1e9),
        geometricMask: std::mem::ManuallyDrop::new(Some(g.cast().unwrap())),
        maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
        maskTransform: mat::ident(),
        opacity: 1.0,
        opacityBrush: std::mem::ManuallyDrop::new(None),
        layerOptions: D2D1_LAYER_OPTIONS1_NONE,
    };
    dc.PushLayer(&lp, None);
    std::mem::ManuallyDrop::into_inner(lp.geometricMask);
    true
}

// ---- Borda de rolagem do Tahoe: o que passa sob as barras flutuantes fica desfocado e some aos poucos. A cena é
// desenhada fora da tela por um segundo contexto do mesmo dispositivo e depois composta no principal.
#[derive(Default)]
struct Scene {
    dev: Option<ID2D1Device>,
    dc: Option<ID2D1DeviceContext>,
    bmp: Option<ID2D1Bitmap1>,
    blur: Option<ID2D1Effect>,
    w: u32,
    h: u32,
    dpi: f32,
}
static SCENES: Global<[Option<Scene>; 4]> = Global::new([None, None, None, None]);
static SCENE_ERR: Global<String> = Global::new(String::new());
/// por que scene_begin devolveu None
pub fn scene_error() -> String {
    SCENE_ERR.get().clone()
}
/// None: desenhe direto
pub unsafe fn scene_begin(main: &ID2D1DeviceContext, slot: usize, w_dip: f32, h_dip: f32, dpi: f32) -> Option<ID2D1DeviceContext> {
    if slot >= 4 {
        return None;
    }
    let s = SCENES.get()[slot].get_or_insert_with(Scene::default);
    let Ok(dev) = main.GetDevice() else {
        *SCENE_ERR.get() = "sem dispositivo".into();
        return None;
    };
    if s.dev.as_ref() != Some(&dev) {
        // dispositivo novo (ou perdido e recriado)
        *s = Scene { dev: Some(dev.clone()), ..Default::default() };
        match dev.CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE) {
            Ok(dc) => {
                s.blur = dc.CreateEffect(&CLSID_D2D1GaussianBlur).ok();
                s.dc = Some(dc);
            }
            Err(e) => {
                *SCENE_ERR.get() = format!("contexto {:08X}", e.code().0 as u32);
                *s = Scene::default();
                return None;
            }
        }
    }
    let (w, h) = ((w_dip * dpi / 96.0).ceil() as u32, (h_dip * dpi / 96.0).ceil() as u32);
    if w < 1 || h < 1 {
        *SCENE_ERR.get() = "tamanho zero".into();
        return None;
    }
    let dc = s.dc.clone()?;
    if s.bmp.is_none() || w != s.w || h != s.h || dpi != s.dpi {
        s.bmp = None;
        let bp = D2D1_BITMAP_PROPERTIES1 {
            pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
            dpiX: dpi,
            dpiY: dpi,
            bitmapOptions: D2D1_BITMAP_OPTIONS_TARGET,
            colorContext: std::mem::ManuallyDrop::new(None),
        };
        match dc.CreateBitmap(D2D_SIZE_U { width: w, height: h }, None, 0, &bp) {
            Ok(b) => s.bmp = Some(b),
            Err(e) => {
                *SCENE_ERR.get() = format!("bitmap {:08X}", e.code().0 as u32);
                return None;
            }
        }
        (s.w, s.h, s.dpi) = (w, h, dpi);
    }
    if let Some(b) = &s.bmp {
        dc.SetTarget(b);
    }
    dc.SetDpi(dpi, dpi);
    dc.BeginDraw();
    dc.SetTransform(&mat::ident());
    dc.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
    Some(dc)
}
pub unsafe fn scene_end(slot: usize) {
    if let Some(Some(s)) = SCENES.get().get(slot) {
        if let Some(dc) = &s.dc {
            let _ = dc.EndDraw(None, None);
            dc.SetTarget(None);
        }
    }
}
unsafe fn layer_mask(dc: &ID2D1DeviceContext, area: RectF, m: &ID2D1LinearGradientBrush) {
    let lp = D2D1_LAYER_PARAMETERS1 {
        contentBounds: area,
        geometricMask: std::mem::ManuallyDrop::new(None),
        maskAntialiasMode: D2D1_ANTIALIAS_MODE_ALIASED,
        maskTransform: mat::ident(),
        opacity: 1.0,
        opacityBrush: std::mem::ManuallyDrop::new(Some(m.cast().unwrap())),
        layerOptions: D2D1_LAYER_OPTIONS1_NONE,
    };
    dc.PushLayer(&lp, None);
    std::mem::ManuallyDrop::into_inner(lp.opacityBrush);
}
/// nítida em `area` e, na faixa de cima (`band` DIPs), desfocada e sumindo; fade: cor do fundo para onde a faixa vai
pub unsafe fn scene_draw(dc: &ID2D1DeviceContext, slot: usize, area: RectF, band: f32, fade: Cor) {
    let Some(Some(s)) = SCENES.get().get(slot) else { return };
    let Some(bmp) = &s.bmp else { return };
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    let edge = area.top + band;
    let img: ID2D1Image = bmp.cast().unwrap();
    // nítida: some na metade de baixo da faixa
    if let Some(m) = gradient(&rt, &[(0.0, col(0.0, 0.0, 0.0, 0.0)), (1.0, col(0.0, 0.0, 0.0, 1.0))], (0.0, edge - band * 0.45), (0.0, edge)) {
        layer_mask(dc, area, &m);
        dc.DrawImage(&img, None, None, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
        dc.PopLayer();
    } else {
        dc.DrawImage(&img, None, None, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
    }
    // desfocada na faixa, mais fraca bem no alto (onde ficam o título e os botões)
    let Some(blur) = &s.blur else { return };
    if band <= 0.0 {
        return;
    }
    blur.SetInput(0, &img, true);
    let _ = blur.SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION.0 as u32, D2D1_PROPERTY_TYPE_FLOAT, &12.0f32.to_le_bytes());
    let _ = blur.SetValue(D2D1_GAUSSIANBLUR_PROP_BORDER_MODE.0 as u32, D2D1_PROPERTY_TYPE_ENUM, &(D2D1_BORDER_MODE_HARD.0 as u32).to_le_bytes());
    if let Some(m) = gradient(&rt, &[(0.0, col(0.0, 0.0, 0.0, 0.30)), (0.6, col(0.0, 0.0, 0.0, 0.85)), (1.0, col(0.0, 0.0, 0.0, 0.0))], (0.0, area.top), (0.0, edge)) {
        layer_mask(dc, rf(area.left, area.top, area.right, edge), &m);
        if let Ok(out) = blur.GetOutput() {
            dc.DrawImage(&out, None, None, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
        }
        dc.PopLayer();
    }
    // e a faixa vai para a cor do fundo (o conteúdo some sob os botões, sem uma linha)
    if fade.a > 0.0 {
        let (f0, mut fm, mut f1) = (fade, fade, fade);
        fm.a = fade.a * 0.85;
        f1.a = 0.0;
        if let Some(g) = gradient(&rt, &[(0.0, f0), (0.5, fm), (1.0, f1)], (0.0, area.top), (0.0, edge)) {
            dc.FillRectangle(&rf(area.left, area.top, area.right, edge), &g);
        }
    }
}

// =====================================================================================================================
// shadow.cpp: sombra grande e difusa (estilo Mac) atrás da janela principal
fn erf(x: f32) -> f32 {
    // Abramowitz e Stegun 7.1.26 (erro < 1,5e-7): a std do Rust não tem
    let s = x.signum();
    let x = x.abs();
    let t = 1.0 / (1.0 + 0.327_591_1 * x);
    let y = 1.0 - (((((1.061_405_4 * t - 1.453_152_1) * t) + 1.421_413_7) * t - 0.284_496_74) * t + 0.254_829_6) * t * (-x * x).exp();
    s * y
}
fn erfc(x: f32) -> f32 {
    1.0 - erf(x)
}
unsafe extern "system" fn sombra_proc(h: HWND, m: u32, w: WPARAM, l: LPARAM) -> LRESULT {
    if m == WM_NCHITTEST {
        return LRESULT(HTTRANSPARENT as isize);
    }
    DefWindowProcW(h, m, w, l)
}
pub struct Shadow {
    owner: HWND,
    wnd: HWND,
    active: bool,
    last_size: SIZE,
    last_active: bool,
    radius_dip: f32,
    last_radius: f32,
    mem: HDC,
    dib: HBITMAP,
    bits: *mut u32,
}
impl Shadow {
    pub fn create(main: HWND) -> Shadow {
        unsafe {
            let inst = GetModuleHandleW(None).unwrap_or_default();
            let wc = WNDCLASSEXW { cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32, lpfnWndProc: Some(sombra_proc), hInstance: inst.into(), lpszClassName: w!("ArquivosSombra"), ..Default::default() };
            RegisterClassExW(&wc);
            let wnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("ArquivosSombra"), w!(""), WS_POPUP, 0, 0, 1, 1, None, None, inst, None).unwrap_or_default();
            if wnd.0.is_null() {
                log(&format!("erro: janela de sombra ({})", GetLastError().0));
            }
            Shadow { owner: main, wnd, active: true, last_size: SIZE::default(), last_active: true, radius_dip: 0.0, last_radius: 0.0, mem: HDC::default(), dib: HBITMAP::default(), bits: std::ptr::null_mut() }
        }
    }
    pub fn set_active(&mut self, a: bool) {
        self.active = a;
    }
    /// cantos da janela (0 = retângulo, como no Sequoia; 26 no Tahoe)
    pub fn set_radius(&mut self, dip: f32) {
        self.radius_dip = dip;
    }
    unsafe fn rebuild(&mut self, w: i32, h: i32, win: RECT, scale: f32) {
        if !self.dib.is_invalid() {
            let _ = DeleteObject(self.dib);
            self.dib = HBITMAP::default();
        }
        if self.mem.is_invalid() {
            self.mem = CreateCompatibleDC(None);
        }
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w, biHeight: -h, biPlanes: 1, biBitCount: 32, ..Default::default() }, ..Default::default() };
        let mut bits: *mut core::ffi::c_void = std::ptr::null_mut();
        let Ok(dib) = CreateDIBSection(None, &bi, DIB_RGB_COLORS, &mut bits, None, 0) else { return };
        self.dib = dib;
        self.bits = bits as *mut u32;
        SelectObject(self.mem, dib);
        let active = self.active;
        // janela ativa: sombra mais escura e maior, como no Mac; inativa: mais suave
        let (mut sigma, mut amount, mut dy) = (if active { 20.0 } else { 16.0 } * scale, if active { 0.55 } else { 0.44 }, if active { 16.0 } else { 12.0 } * scale);
        if self.radius_dip > 0.0 {
            // Tahoe: medido no macOS 26 (guia, seções 51 e 61; blur CSS = 2σ); tema escuro dos apps lido do registro
            let (mut light, mut cb) = (1u32, 4u32);
            let _ = RegGetValueW(HKEY_CURRENT_USER, w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), w!("AppsUseLightTheme"), RRF_RT_REG_DWORD, None, Some(&mut light as *mut _ as *mut _), Some(&mut cb));
            let dk = light == 0;
            if active {
                (sigma, amount, dy) = (if dk { 19.5 } else { 20.0 } * scale, if dk { 0.69 } else { 0.43 }, if dk { 18.0 } else { 17.0 } * scale);
            } else {
                (sigma, amount, dy) = (if dk { 16.0 } else { 15.0 } * scale, if dk { 0.62 } else { 0.42 }, if dk { 12.0 } else { 10.0 } * scale);
            }
        }
        let (l, r, t, b) = (win.left as f32, win.right as f32, win.top as f32 + dy, win.bottom as f32 + dy);
        let k = 1.0 / (sigma * std::f32::consts::SQRT_2);
        let px = std::slice::from_raw_parts_mut(self.bits, (w * h) as usize);
        if self.radius_dip > 0.0 {
            // Tahoe: sombra de retângulo arredondado (distância até a forma, perfil erfc)
            let rad = self.radius_dip * scale;
            let (cxl, cxr, cyt, cyb) = (l + rad, r - rad, t + rad, b - rad);
            let (wr, wl, wt, wb, ir) = (win.right as f32, win.left as f32, win.top as f32, win.bottom as f32, rad);
            for y in 0..h {
                for x in 0..w {
                    let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
                    // dentro da janela (arredondada) não escurece
                    let ix = (wl + ir - fx).max(fx - (wr - ir)).max(0.0);
                    let iy = (wt + ir - fy).max(fy - (wb - ir)).max(0.0);
                    let i = (y * w + x) as usize;
                    if fx >= wl && fx < wr && fy >= wt && fy < wb && ix * ix + iy * iy <= ir * ir {
                        px[i] = 0;
                        continue;
                    }
                    let dx = (cxl - fx).max(fx - cxr).max(0.0);
                    let dy2 = (cyt - fy).max(fy - cyb).max(0.0);
                    let inside = (cxl - fx).max(fx - cxr).max((cyt - fy).max(fy - cyb)).min(0.0);
                    let d = (dx * dx + dy2 * dy2).sqrt() + inside - rad;
                    let a = amount * 0.5 * erfc(d * k);
                    px[i] = ((a.min(1.0) * 255.0).round() as u32) << 24;
                }
            }
            return;
        }
        // embaixo da janela não escurece, menos nos cantos (buraco com cantos redondos de 24 pt, folgado)
        let ax: Vec<f32> = (0..w).map(|x| 0.5 * (erf((x as f32 + 0.5 - l) * k) - erf((x as f32 + 0.5 - r) * k))).collect();
        let ay: Vec<f32> = (0..h).map(|y| 0.5 * (erf((y as f32 + 0.5 - t) * k) - erf((y as f32 + 0.5 - b) * k))).collect();
        let rc = 24.0 * scale;
        for y in 0..h {
            let row_inside = y >= win.top && y < win.bottom;
            let fy = y as f32 + 0.5;
            let cy = (win.top as f32 + rc - fy).max(fy - (win.bottom as f32 - rc)).max(0.0);
            for x in 0..w {
                let fx = x as f32 + 0.5;
                let cx = (win.left as f32 + rc - fx).max(fx - (win.right as f32 - rc)).max(0.0);
                let i = (y * w + x) as usize;
                if row_inside && x >= win.left && x < win.right && cx * cx + cy * cy <= rc * rc {
                    px[i] = 0;
                    continue;
                }
                let a = amount * ax[x as usize] * ay[y as usize];
                px[i] = ((a.min(1.0) * 255.0).round() as u32) << 24; // preto pré-multiplicado
            }
        }
    }
    /// chamar quando a janela mudar de posição, tamanho, ordem ou estado
    pub fn update(&mut self) {
        if self.wnd.0.is_null() {
            return;
        }
        unsafe {
            let o = self.owner;
            let mut cloaked = 0i32;
            let cl = DwmGetWindowAttribute(o, DWMWA_CLOAKED, &mut cloaked as *mut _ as *mut _, 4).is_ok() && cloaked != 0;
            if !IsWindowVisible(o).as_bool() || IsIconic(o).as_bool() || IsZoomed(o).as_bool() || cl {
                let _ = ShowWindow(self.wnd, SW_HIDE);
                return;
            }
            let mut vis = RECT::default(); // retângulo visível (sem a borda invisível de redimensionar)
            if DwmGetWindowAttribute(o, DWMWA_EXTENDED_FRAME_BOUNDS, &mut vis as *mut _ as *mut _, std::mem::size_of::<RECT>() as u32).is_err() {
                let _ = GetWindowRect(o, &mut vis);
            }
            let scale = GetDpiForWindow(o) as f32 / 96.0;
            let (m, mb) = ((64.0 * scale) as i32, (90.0 * scale) as i32); // margem maior embaixo: a sombra cai para baixo
            let r = RECT { left: vis.left - m, top: vis.top - m, right: vis.right + m, bottom: vis.bottom + mb };
            let size = SIZE { cx: r.right - r.left, cy: r.bottom - r.top };
            if size.cx != self.last_size.cx || size.cy != self.last_size.cy || self.active != self.last_active || self.radius_dip != self.last_radius {
                let win = RECT { left: m, top: m, right: m + (vis.right - vis.left), bottom: m + (vis.bottom - vis.top) };
                self.rebuild(size.cx, size.cy, win, scale);
                (self.last_size, self.last_active, self.last_radius) = (size, self.active, self.radius_dip);
            }
            let (pos, zero) = (POINT { x: r.left, y: r.top }, POINT::default());
            let bf = BLENDFUNCTION { BlendOp: 0, BlendFlags: 0, SourceConstantAlpha: 255, AlphaFormat: 1 };
            if UpdateLayeredWindow(self.wnd, None, Some(&pos), Some(&size), self.mem, Some(&zero), COLORREF(0), Some(&bf), ULW_ALPHA).is_err() {
                log(&format!("erro: UpdateLayeredWindow ({}) {}x{}", GetLastError().0, size.cx, size.cy));
            }
            // logo abaixo da janela principal na ordem das janelas
            let _ = SetWindowPos(self.wnd, o, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
        }
    }
    pub fn destroy(&mut self) {
        unsafe {
            if !self.wnd.0.is_null() {
                let _ = DestroyWindow(self.wnd);
            }
            if !self.dib.is_invalid() {
                let _ = DeleteObject(self.dib);
            }
            if !self.mem.is_invalid() {
                let _ = DeleteDC(self.mem);
            }
        }
        self.wnd = HWND::default();
        self.dib = HBITMAP::default();
        self.mem = HDC::default();
    }
}

// =====================================================================================================================
/// Modo foto do caminho da Composição: o mesmo tipo de contexto (ID2D1DeviceContext de um dispositivo D3D11 WARP,
/// sem janela) desenhando num bitmap; `ler` devolve os pixels BGRA pré-multiplicados. Onde o vidro apareceria, a foto
/// fica transparente.
pub struct Offscreen {
    pub dc: ID2D1DeviceContext,
    alvo: ID2D1Bitmap1,
    copia: ID2D1Bitmap1,
    pub w: u32,
    pub h: u32,
}
impl Offscreen {
    pub fn new(w: u32, h: u32, dpi: f32) -> Option<Offscreen> {
        unsafe {
            let mut d3d: Option<ID3D11Device> = None;
            D3D11CreateDevice(None, D3D_DRIVER_TYPE_WARP, HMODULE::default(), D3D11_CREATE_DEVICE_BGRA_SUPPORT, None, D3D11_SDK_VERSION, Some(&mut d3d), None, None).ok()?;
            let dxgi: IDXGIDevice = d3d?.cast().ok()?;
            let d2d: ID2D1Factory1 = fabrica()?;
            let dc = d2d.CreateDevice(&dxgi).ok()?.CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE).ok()?;
            let props = |opts| D2D1_BITMAP_PROPERTIES1 {
                pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
                dpiX: dpi,
                dpiY: dpi,
                bitmapOptions: opts,
                colorContext: std::mem::ManuallyDrop::new(None),
            };
            let sz = D2D_SIZE_U { width: w, height: h };
            let alvo = dc.CreateBitmap(sz, None, 0, &props(D2D1_BITMAP_OPTIONS_TARGET)).ok()?;
            let copia = dc.CreateBitmap(sz, None, 0, &props(D2D1_BITMAP_OPTIONS_CPU_READ | D2D1_BITMAP_OPTIONS_CANNOT_DRAW)).ok()?;
            dc.SetTarget(&alvo);
            dc.SetDpi(dpi, dpi);
            dc.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
            Some(Offscreen { dc, alvo, copia, w, h })
        }
    }
    /// os pixels do último quadro (BGRA pré-multiplicado, de cima para baixo, w*4 por linha)
    pub fn ler(&self) -> Option<Vec<u8>> {
        unsafe {
            self.copia.CopyFromBitmap(None, &self.alvo, None).ok()?;
            let m = self.copia.Map(D2D1_MAP_OPTIONS_READ).ok()?;
            let mut out = vec![0u8; (self.w * self.h * 4) as usize];
            for y in 0..self.h as usize {
                let src = std::slice::from_raw_parts(m.bits.add(y * m.pitch as usize), self.w as usize * 4);
                out[y * self.w as usize * 4..(y + 1) * self.w as usize * 4].copy_from_slice(src);
            }
            let _ = self.copia.Unmap();
            Some(out)
        }
    }
}