Skip to content

A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.

chore(spikes): add Windows UI diagnostic probes

CristianOlivera17b68794f1972
diff --git a/Cargo.lock b/Cargo.lock
index 120e4e1..fa2bc42 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3933,8 +3933,10 @@ dependencies = [
name = "spikes"
version = "0.0.0"
dependencies = [
+ "anyhow",
"muelle-shell",
"windows",
+ "windows-core",
"windows-numerics",
]
diff --git a/spikes/Cargo.toml b/spikes/Cargo.toml
index de80a8e..a504a5f 100644
--- a/spikes/Cargo.toml
+++ b/spikes/Cargo.toml
@@ -12,30 +12,47 @@ workspace = true
windows = { workspace = true, features = [
"Foundation",
"Foundation_Numerics",
+ "Graphics",
+ "Graphics_Capture",
+ "Graphics_DirectX",
+ "Graphics_DirectX_Direct3D11",
"System",
"UI",
"UI_Composition",
"UI_Composition_Desktop",
"Win32_Foundation",
"Win32_Graphics_Direct2D",
+ "Win32_Graphics_Direct2D_Common",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D11",
"Win32_Graphics_DirectWrite",
"Win32_Graphics_Dwm",
"Win32_Graphics_Dxgi",
+ "Win32_Graphics_Dxgi_Common",
"Win32_Graphics_Gdi",
- "Win32_System_LibraryLoader",
+ "Win32_Security",
+ "Win32_Security_Credentials",
+ "Win32_Security_Cryptography",
"Win32_System_Com",
+ "Win32_System_Console",
+ "Win32_System_Diagnostics_ToolHelp",
+ "Win32_System_LibraryLoader",
+ "Win32_System_Ole",
"Win32_System_ProcessStatus",
+ "Win32_System_SystemInformation",
+ "Win32_System_SystemServices",
"Win32_System_Threading",
"Win32_System_WinRT",
"Win32_System_WinRT_Composition",
+ "Win32_System_WinRT_Direct3D11",
+ "Win32_System_WinRT_Graphics_Capture",
"Win32_UI_Accessibility",
"Win32_UI_HiDpi",
"Win32_UI_Input_KeyboardAndMouse",
- "Win32_System_SystemInformation",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
windows-numerics.workspace = true
+anyhow.workspace = true
+windows-core.workspace = true
muelle-shell.workspace = true
diff --git a/spikes/src/bin/spike_caption.rs b/spikes/src/bin/spike_caption.rs
new file mode 100644
index 0000000..c6cacfa
--- /dev/null
+++ b/spikes/src/bin/spike_caption.rs
@@ -0,0 +1,183 @@
+//! Checks how the menu bar tells a window's minimize/maximize/close buttons
+//! apart: DWM's caption button bounds and the window's own WM_NCHITTEST.
+//! Only queries; nothing is clicked.
+
+use std::{thread::sleep, time::Duration};
+
+use windows::{
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
+ Graphics::Dwm::{DWMWA_CAPTION_BUTTON_BOUNDS, DwmGetWindowAttribute},
+ System::LibraryLoader::GetModuleHandleW,
+ UI::{
+ HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},
+ WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, EnumWindows,
+ GetClassNameW, GetWindowRect, GetWindowTextW, IsWindowVisible, MSG, PM_REMOVE,
+ PeekMessageW, RegisterClassW, SMTO_ABORTIFHUNG, SW_MAXIMIZE, SendMessageTimeoutW,
+ ShowWindow, WM_NCHITTEST, WNDCLASSW, WS_OVERLAPPEDWINDOW,
+ },
+ },
+ },
+ core::{BOOL, w},
+};
+
+unsafe extern "system" fn proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ unsafe { DefWindowProcW(hwnd, msg, w, l) }
+}
+
+fn report(name: &str, window: HWND, point: POINT) {
+ unsafe {
+ use windows::Win32::UI::WindowsAndMessaging::{GA_ROOT, GetAncestor, WindowFromPoint};
+ let under = GetAncestor(WindowFromPoint(point), GA_ROOT);
+ let mut class = [0u16; 64];
+ let n = GetClassNameW(under, &mut class) as usize;
+ let mut r = RECT::default();
+ let _ = GetWindowRect(under, &mut r);
+ println!(
+ " under {point:?}: {} {r:?} same={}",
+ String::from_utf16_lossy(&class[..n]),
+ under == window
+ );
+ let mut frame = RECT::default();
+ let _ = GetWindowRect(window, &mut frame);
+ let mut buttons = RECT::default();
+ let dwm = DwmGetWindowAttribute(
+ window,
+ DWMWA_CAPTION_BUTTON_BOUNDS,
+ (&raw mut buttons).cast(),
+ size_of::<RECT>() as u32,
+ );
+ let position = ((point.y as u32 & 0xFFFF) << 16 | (point.x as u32 & 0xFFFF)) as isize;
+ let mut hit = 0usize;
+ let answered = SendMessageTimeoutW(
+ window,
+ WM_NCHITTEST,
+ WPARAM(0),
+ LPARAM(position),
+ SMTO_ABORTIFHUNG,
+ 50,
+ Some(&mut hit),
+ );
+ let screen = RECT {
+ left: 0,
+ top: frame.top + 9,
+ right: 1920,
+ bottom: 1080,
+ };
+ println!(
+ "{name}: caption_button_at={} frame={frame:?} point={point:?} dwm buttons={:?} nchittest={} (8 min, 9 max, 20 close)",
+ muelle_shell::tracker::caption_button_at(point, screen),
+ dwm.map(|()| buttons),
+ if answered.0 != 0 {
+ hit.to_string()
+ } else {
+ "no answer".into()
+ }
+ );
+ }
+}
+
+unsafe extern "system" fn find_brave(hwnd: HWND, out: LPARAM) -> BOOL {
+ unsafe {
+ let mut class = [0u16; 64];
+ let n = GetClassNameW(hwnd, &mut class) as usize;
+ let mut title = [0u16; 256];
+ let t = GetWindowTextW(hwnd, &mut title) as usize;
+ if IsWindowVisible(hwnd).as_bool()
+ && String::from_utf16_lossy(&class[..n]) == "Chrome_WidgetWin_1"
+ && String::from_utf16_lossy(&title[..t]).contains("Brave")
+ {
+ *(out.0 as *mut HWND) = hwnd;
+ return false.into();
+ }
+ true.into()
+ }
+}
+
+fn main() {
+ unsafe {
+ let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ let Ok(instance) = GetModuleHandleW(None) else {
+ return;
+ };
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(proc),
+ hInstance: instance.into(),
+ lpszClassName: w!("MuelleSpikeCaption"),
+ ..Default::default()
+ });
+ let Ok(hwnd) = CreateWindowExW(
+ Default::default(),
+ w!("MuelleSpikeCaption"),
+ w!("caption"),
+ WS_OVERLAPPEDWINDOW,
+ 300,
+ 200,
+ 700,
+ 450,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ ) else {
+ return;
+ };
+ let _ = ShowWindow(hwnd, SW_MAXIMIZE);
+ let mut msg = MSG::default();
+ for _ in 0..60 {
+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
+ DispatchMessageW(&msg);
+ }
+ sleep(Duration::from_millis(10));
+ }
+ let mut frame = RECT::default();
+ let _ = GetWindowRect(hwnd, &mut frame);
+ // The top-right pixel of the screen area the maximized window shows.
+ let corner = POINT {
+ x: frame.right - 10,
+ y: frame.top + 9,
+ };
+ report("test window, top-right corner", hwnd, corner);
+ report(
+ "test window, left of the buttons",
+ hwnd,
+ POINT {
+ x: corner.x - 200,
+ y: corner.y,
+ },
+ );
+ report(
+ "test window, middle of title",
+ hwnd,
+ POINT {
+ x: (frame.left + frame.right) / 2,
+ y: frame.top + 9,
+ },
+ );
+ let _ = DestroyWindow(hwnd);
+
+ let mut brave = HWND::default();
+ let _ = EnumWindows(Some(find_brave), LPARAM(&raw mut brave as isize));
+ if !brave.is_invalid() {
+ let mut frame = RECT::default();
+ let _ = GetWindowRect(brave, &mut frame);
+ report(
+ "brave, close button",
+ brave,
+ POINT {
+ x: frame.right - 30,
+ y: frame.top + 15,
+ },
+ );
+ report(
+ "brave, a tab",
+ brave,
+ POINT {
+ x: frame.left + 200,
+ y: frame.top + 15,
+ },
+ );
+ }
+ }
+}
diff --git a/spikes/src/bin/spike_focuslog.rs b/spikes/src/bin/spike_focuslog.rs
new file mode 100644
index 0000000..4fccd65
--- /dev/null
+++ b/spikes/src/bin/spike_focuslog.rs
@@ -0,0 +1,90 @@
+//! Logs which window is in front and the stacking order of the top app
+//! windows (with their program) whenever either changes, plus minimize
+//! start/end. Only listens. Usage: `spike_focuslog [seconds]` (default 90).
+
+use std::time::{Duration, Instant};
+
+use windows::{
+ Win32::{
+ Foundation::{CloseHandle, HWND, LPARAM},
+ System::Threading::{OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW},
+ UI::{
+ Accessibility::{HWINEVENTHOOK, SetWinEventHook, UnhookWinEvent},
+ WindowsAndMessaging::{
+ DispatchMessageW, EnumWindows, GWL_EXSTYLE, GetForegroundWindow, GetWindowLongW,
+ GetWindowThreadProcessId, IsIconic, IsWindowVisible, MSG, PM_REMOVE, PeekMessageW,
+ WINEVENT_OUTOFCONTEXT, WS_EX_TOOLWINDOW,
+ },
+ },
+ },
+ core::{BOOL, PWSTR},
+};
+
+fn exe(hwnd: HWND) -> String {
+ unsafe {
+ let mut pid = 0;
+ GetWindowThreadProcessId(hwnd, Some(&mut pid));
+ let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return format!("pid{pid}") };
+ let mut buffer = [0u16; 512];
+ let mut len = buffer.len() as u32;
+ let ok = QueryFullProcessImageNameW(process, PROCESS_NAME_WIN32, PWSTR(buffer.as_mut_ptr()), &mut len).is_ok();
+ let _ = CloseHandle(process);
+ if !ok { return format!("pid{pid}") }
+ let path = String::from_utf16_lossy(&buffer[..len as usize]);
+ path.rsplit(char::from(92)).next().unwrap_or_default().to_owned()
+ }
+}
+
+fn label(hwnd: HWND) -> String {
+ format!("{}#{:x}{}", exe(hwnd), hwnd.0 as usize & 0xFFFF, if unsafe { IsIconic(hwnd).as_bool() } { "(min)" } else { "" })
+}
+
+unsafe extern "system" fn collect(hwnd: HWND, list: LPARAM) -> BOOL {
+ unsafe {
+ let ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;
+ if IsWindowVisible(hwnd).as_bool() && ex & WS_EX_TOOLWINDOW.0 == 0 {
+ let v = &mut *(list.0 as *mut Vec<HWND>);
+ v.push(hwnd);
+ }
+ }
+ true.into()
+}
+
+fn order() -> String {
+ let mut all: Vec<HWND> = Vec::new();
+ unsafe { let _ = EnumWindows(Some(collect), LPARAM(&raw mut all as isize)); }
+ all.into_iter()
+ .map(label)
+ .filter(|l| !l.starts_with("pid") && !l.contains("TextInputHost") && !l.contains("ApplicationFrameHost"))
+ .take(5)
+ .collect::<Vec<_>>()
+ .join(" > ")
+}
+
+static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
+
+fn stamp() -> u128 { START.get().map_or(0, |s| s.elapsed().as_millis()) }
+
+unsafe extern "system" fn on_event(_: HWINEVENTHOOK, event: u32, hwnd: HWND, object: i32, _: i32, _: u32, _: u32) {
+ if object != 0 { return; }
+ let name = match event { 3 => "FOREGROUND", 0x16 => "MINIMIZESTART", 0x17 => "MINIMIZEEND", _ => return };
+ println!("{:>7} {name:<14} {} | z: {}", stamp(), label(hwnd), order());
+}
+
+fn main() {
+ let seconds: u64 = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(90);
+ let _ = START.set(Instant::now());
+ unsafe {
+ let hook = SetWinEventHook(3, 0x17, None, Some(on_event), 0, 0, WINEVENT_OUTOFCONTEXT);
+ let end = Instant::now() + Duration::from_secs(seconds);
+ let mut last = String::new();
+ let mut msg = MSG::default();
+ while Instant::now() < end {
+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() { DispatchMessageW(&msg); }
+ let now = format!("front {} | z: {}", label(GetForegroundWindow()), order());
+ if now != last { println!("{:>7} poll {now}", stamp()); last = now; }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ let _ = UnhookWinEvent(hook);
+ }
+}
diff --git a/spikes/src/bin/spike_menu.rs b/spikes/src/bin/spike_menu.rs
new file mode 100644
index 0000000..97396f2
--- /dev/null
+++ b/spikes/src/bin/spike_menu.rs
@@ -0,0 +1,135 @@
+//! Renders the dock's context menu (the real `menu.rs` and `gfx.rs`) for a
+//! moment, saves a screenshot of it and closes it: a visual check that needs
+//! no clicks. Usage: `spike_menu <dark|light> <out.bgra>`; the file holds
+//! width and height as two little-endian u32, then BGRA pixels.
+
+#![allow(dead_code)]
+
+#[path = "../../../apps/dock/src/gfx.rs"]
+mod gfx;
+#[path = "../../../apps/dock/src/menu.rs"]
+mod menu;
+
+use std::{io::Write, time::Duration};
+
+use muelle_shell::screen;
+use windows::{
+ Win32::{
+ Foundation::{HWND, LPARAM, POINT, RECT, WPARAM},
+ System::{
+ Com::{COINIT_APARTMENTTHREADED, CoInitializeEx},
+ LibraryLoader::GetModuleHandleW,
+ },
+ UI::{
+ HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},
+ WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, FindWindowW, GetWindowRect, PostMessageW,
+ RegisterClassW, WM_CANCELMODE, WNDCLASSW, WS_POPUP,
+ },
+ },
+ },
+ core::w,
+};
+
+unsafe extern "system" fn proc(
+ hwnd: HWND,
+ msg: u32,
+ w: WPARAM,
+ l: LPARAM,
+) -> windows::Win32::Foundation::LRESULT {
+ unsafe { DefWindowProcW(hwnd, msg, w, l) }
+}
+
+fn main() -> anyhow::Result<()> {
+ let mut args = std::env::args().skip(1);
+ let dark = args.next().as_deref() != Some("light");
+ let out = args.next().unwrap_or_else(|| "menu.bgra".into());
+ unsafe {
+ let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+ // The compositor needs a dispatcher queue on this thread, as in the dock.
+ let _queue = windows::Win32::System::WinRT::CreateDispatcherQueueController(
+ windows::Win32::System::WinRT::DispatcherQueueOptions {
+ dwSize: size_of::<windows::Win32::System::WinRT::DispatcherQueueOptions>() as u32,
+ threadType: windows::Win32::System::WinRT::DQTYPE_THREAD_CURRENT,
+ apartmentType: windows::Win32::System::WinRT::DQTAT_COM_STA,
+ },
+ )?;
+ let instance = GetModuleHandleW(None)?;
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(proc),
+ hInstance: instance.into(),
+ lpszClassName: w!("SpikeMenuOwner"),
+ ..Default::default()
+ });
+ let owner = CreateWindowExW(
+ Default::default(),
+ w!("SpikeMenuOwner"),
+ w!(""),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?;
+ let gfx = gfx::Gfx::new()?;
+ let items = vec![
+ menu::MenuItem::action(1, "Desactivar &ocultación automática"),
+ menu::MenuItem::action(2, "Mostrar &escritorio"),
+ menu::MenuItem::Action {
+ command: 3,
+ label: "&Mantener en el Dock".into(),
+ checked: true,
+ enabled: true,
+ },
+ menu::MenuItem::Action {
+ command: 4,
+ label: "Abrir al iniciar sesión".into(),
+ checked: false,
+ enabled: false,
+ },
+ menu::MenuItem::Separator,
+ menu::MenuItem::action(5, "&Salir de Muelle"),
+ ];
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(120));
+ let Ok(menu) = FindWindowW(w!("MuelleMenu"), None) else {
+ return;
+ };
+ // Two "down" keys: the selection lands on the second item.
+ for _ in 0..2 {
+ let _ = PostMessageW(
+ Some(menu),
+ windows::Win32::UI::WindowsAndMessaging::WM_KEYDOWN,
+ WPARAM(0x28),
+ LPARAM(0),
+ );
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ let mut rect = RECT::default();
+ let _ = GetWindowRect(menu, &mut rect);
+ let pad = 24;
+ let area = RECT {
+ left: rect.left - pad,
+ top: rect.top - pad,
+ right: rect.right + pad,
+ bottom: rect.bottom + pad,
+ };
+ if let Some(shot) = screen::capture(area)
+ && let Ok(mut file) = std::fs::File::create(&out)
+ {
+ let _ = file.write_all(&((area.right - area.left) as u32).to_le_bytes());
+ let _ = file.write_all(&((area.bottom - area.top) as u32).to_le_bytes());
+ let _ = file.write_all(&shot.bgra);
+ }
+ let _ = PostMessageW(Some(menu), WM_CANCELMODE, WPARAM(0), LPARAM(0));
+ });
+ let chosen = menu::show(&gfx, owner, &items, POINT { x: 960, y: 980 }, dark);
+ println!("chosen: {chosen:?}");
+ }
+ Ok(())
+}
diff --git a/spikes/src/bin/spike_wgc.rs b/spikes/src/bin/spike_wgc.rs
new file mode 100644
index 0000000..b2d3dd4
--- /dev/null
+++ b/spikes/src/bin/spike_wgc.rs
@@ -0,0 +1,157 @@
+//! Is Muelle visible to Windows.Graphics.Capture, the API that the Snipping
+//! Tool and most screen recorders use? Captures one frame of the primary
+//! monitor and compares a row of pixels with what GDI sees there.
+//! Usage: `spike_wgc [y]` (default: row 10, inside the menu bar).
+
+use std::time::{Duration, Instant};
+
+use muelle_shell::screen;
+use windows::{
+ Foundation::TypedEventHandler,
+ Graphics::{
+ Capture::{Direct3D11CaptureFramePool, GraphicsCaptureItem},
+ DirectX::DirectXPixelFormat,
+ },
+ Win32::{
+ Foundation::{HMODULE, POINT, RECT},
+ Graphics::{
+ Direct3D::D3D_DRIVER_TYPE_HARDWARE,
+ Direct3D11::{
+ D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
+ D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC,
+ D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,
+ ID3D11Texture2D,
+ },
+ Dxgi::IDXGIDevice,
+ Gdi::{MONITOR_DEFAULTTOPRIMARY, MonitorFromPoint},
+ },
+ System::WinRT::{
+ Direct3D11::{CreateDirect3D11DeviceFromDXGIDevice, IDirect3DDxgiInterfaceAccess},
+ Graphics::Capture::IGraphicsCaptureItemInterop,
+ RO_INIT_MULTITHREADED, RoInitialize,
+ },
+ UI::HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},
+ },
+ core::{Interface, Result, factory},
+};
+
+fn main() -> Result<()> {
+ let y: i32 = std::env::args()
+ .nth(1)
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(10);
+ unsafe {
+ let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ RoInitialize(RO_INIT_MULTITHREADED)?;
+ let mut d3d: Option<ID3D11Device> = None;
+ let mut context: Option<ID3D11DeviceContext> = None;
+ D3D11CreateDevice(
+ None,
+ D3D_DRIVER_TYPE_HARDWARE,
+ HMODULE::default(),
+ D3D11_CREATE_DEVICE_BGRA_SUPPORT,
+ None,
+ D3D11_SDK_VERSION,
+ Some(&mut d3d),
+ None,
+ Some(&mut context),
+ )?;
+ let (Some(d3d), Some(context)) = (d3d, context) else {
+ return Ok(());
+ };
+ let device: windows::Graphics::DirectX::Direct3D11::IDirect3DDevice =
+ CreateDirect3D11DeviceFromDXGIDevice(&d3d.cast::<IDXGIDevice>()?)?.cast()?;
+
+ let monitor = MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY);
+ let interop = factory::<GraphicsCaptureItem, IGraphicsCaptureItemInterop>()?;
+ let item: GraphicsCaptureItem = interop.CreateForMonitor(monitor)?;
+ let size = item.Size()?;
+ let pool = Direct3D11CaptureFramePool::CreateFreeThreaded(
+ &device,
+ DirectXPixelFormat::B8G8R8A8UIntNormalized,
+ 1,
+ size,
+ )?;
+ let (sender, receiver) = std::sync::mpsc::channel();
+ pool.FrameArrived(&TypedEventHandler::new(
+ move |pool: windows::core::Ref<Direct3D11CaptureFramePool>, _| {
+ if let Some(pool) = pool.as_ref()
+ && let Ok(frame) = pool.TryGetNextFrame()
+ {
+ let _ = sender.send(frame);
+ }
+ Ok(())
+ },
+ ))?;
+ let session = pool.CreateCaptureSession(&item)?;
+ session.StartCapture()?;
+ // Skip the first frames, which can predate the capture border.
+ let deadline = Instant::now() + Duration::from_secs(3);
+ let mut frame = None;
+ let mut count = 0;
+ while Instant::now() < deadline && count < 4 {
+ if let Ok(f) = receiver.recv_timeout(Duration::from_millis(500)) {
+ frame = Some(f);
+ count += 1;
+ }
+ }
+ session.Close()?;
+ let Some(frame) = frame else {
+ println!("no frame");
+ return Ok(());
+ };
+ let texture: ID3D11Texture2D = frame
+ .Surface()?
+ .cast::<IDirect3DDxgiInterfaceAccess>()?
+ .GetInterface()?;
+ let mut desc = D3D11_TEXTURE2D_DESC::default();
+ texture.GetDesc(&mut desc);
+ desc.Usage = D3D11_USAGE_STAGING;
+ desc.BindFlags = 0;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;
+ desc.MiscFlags = 0;
+ let mut staging: Option<ID3D11Texture2D> = None;
+ d3d.CreateTexture2D(&desc, None, Some(&mut staging))?;
+ let Some(staging) = staging else {
+ return Ok(());
+ };
+ context.CopyResource(&staging, &texture);
+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
+ context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;
+ let row = std::slice::from_raw_parts(
+ (mapped.pData as *const u8).add(mapped.RowPitch as usize * y as usize),
+ desc.Width as usize * 4,
+ )
+ .to_vec();
+ context.Unmap(&staging, 0);
+
+ let Some(gdi) = screen::capture(RECT {
+ left: 0,
+ top: y,
+ right: desc.Width as i32,
+ bottom: y + 1,
+ }) else {
+ return Ok(());
+ };
+ let mut differ = 0;
+ let samples = [100usize, 400, 960, 1500, 1700, 1850];
+ for x in samples {
+ let w = &row[x * 4..x * 4 + 3];
+ let g = &gdi.bgra[x * 4..x * 4 + 3];
+ println!("x={x:4} capture api bgr={w:?} gdi bgr={g:?}");
+ }
+ for x in 0..desc.Width as usize {
+ let d: i32 = (0..3)
+ .map(|c| (row[x * 4 + c] as i32 - gdi.bgra[x * 4 + c] as i32).abs())
+ .sum();
+ if d > 40 {
+ differ += 1;
+ }
+ }
+ println!(
+ "row {y}: {differ} of {} pixels differ between the two captures",
+ desc.Width
+ );
+ }
+ Ok(())
+}