use std::fmt; #[cfg(windows)] use std::mem::size_of; use super::foreground_window::{ForegroundWindowError, WindowSelection}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct CaptureLimits { pub maximum_width: u32, pub maximum_height: u32, pub maximum_pixels: u64, } impl Default for CaptureLimits { fn default() -> Self { Self { maximum_width: 8192, maximum_height: 8192, maximum_pixels: 16_000_000, } } } impl CaptureLimits { pub fn validate(self) -> Result { if self.maximum_width == 0 || self.maximum_width > 8192 || self.maximum_height == 0 || self.maximum_height > 8192 || self.maximum_pixels == 0 || self.maximum_pixels > 16_000_000 { return Err(WindowCaptureError::InvalidLimits); } Ok(self) } #[cfg(any(windows, test))] fn validate_dimensions(self, width: u32, height: u32) -> Result<(), WindowCaptureError> { let pixels = u64::from(width) .checked_mul(u64::from(height)) .ok_or(WindowCaptureError::WindowTooLarge { width, height })?; if width == 0 || height == 0 || width > self.maximum_width || height > self.maximum_height || pixels > self.maximum_pixels { return Err(WindowCaptureError::WindowTooLarge { width, height }); } Ok(()) } } pub struct WindowCapture { pub width: u32, pub height: u32, pub png_bytes: Vec, } impl fmt::Debug for WindowCapture { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("WindowCapture") .field("width", &self.width) .field("height", &self.height) .field("png_bytes", &format_args!("{} bytes", self.png_bytes.len())) .finish() } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum WindowCaptureError { InvalidLimits, WindowTooLarge { width: u32, height: u32 }, Selection(ForegroundWindowError), CaptureFailed, EncodingFailed, UnsupportedPlatform, Platform(u32), } impl fmt::Display for WindowCaptureError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::InvalidLimits => formatter.write_str("the window-capture limits are invalid"), Self::WindowTooLarge { width, height } => { write!( formatter, "the selected window is too large to capture ({width}x{height})" ) } Self::Selection(error) => write!(formatter, "the selected window is invalid: {error}"), Self::CaptureFailed => { formatter.write_str("PrintWindow could not capture the selected window") } Self::EncodingFailed => formatter.write_str("the captured bitmap could not be encoded"), Self::UnsupportedPlatform => { formatter.write_str("window capture is unavailable on this platform") } Self::Platform(code) => { write!(formatter, "window capture failed with Win32 error {code}") } } } } impl std::error::Error for WindowCaptureError {} /// Captures the exact window authorized by a short-lived WindowSelection. /// /// No arbitrary HWND is accepted, no image is written to disk, and dimensions /// are checked before allocating the BGRA and PNG buffers. pub fn capture_selected_window( selection: &WindowSelection, limits: CaptureLimits, ) -> Result { let limits = limits.validate()?; selection .validate() .map_err(WindowCaptureError::Selection)?; capture_selected_window_native(selection, limits) } #[cfg(windows)] fn capture_selected_window_native( selection: &WindowSelection, limits: CaptureLimits, ) -> Result { use windows::Win32::{ Foundation::{HWND, RECT}, Graphics::Gdi::{ BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleBitmap, CreateCompatibleDC, DIB_RGB_COLORS, GetDC, GetDIBits, HGDIOBJ, SelectObject, }, Storage::Xps::{PRINT_WINDOW_FLAGS, PrintWindow}, UI::WindowsAndMessaging::GetWindowRect, }; let window = HWND(selection.raw_handle() as *mut core::ffi::c_void); let mut rectangle = RECT::default(); unsafe { GetWindowRect(window, &mut rectangle) }.map_err(map_windows_error)?; let width_i32 = rectangle .right .checked_sub(rectangle.left) .ok_or(WindowCaptureError::CaptureFailed)?; let height_i32 = rectangle .bottom .checked_sub(rectangle.top) .ok_or(WindowCaptureError::CaptureFailed)?; let width = u32::try_from(width_i32).map_err(|_| WindowCaptureError::CaptureFailed)?; let height = u32::try_from(height_i32).map_err(|_| WindowCaptureError::CaptureFailed)?; limits.validate_dimensions(width, height)?; let screen_dc = unsafe { GetDC(None) }; if screen_dc.0.is_null() { return Err(last_windows_error()); } let screen_dc = ScreenDc(screen_dc); let memory_dc = unsafe { CreateCompatibleDC(Some(screen_dc.0)) }; if memory_dc.0.is_null() { return Err(last_windows_error()); } let memory_dc = MemoryDc(memory_dc); let bitmap = unsafe { CreateCompatibleBitmap(screen_dc.0, width_i32, height_i32) }; if bitmap.0.is_null() { return Err(last_windows_error()); } let bitmap = Bitmap(bitmap); { let previous = unsafe { SelectObject(memory_dc.0, HGDIOBJ(bitmap.0.0)) }; if previous.0.is_null() { return Err(last_windows_error()); } let _selection_guard = SelectedGdiObject { dc: memory_dc.0, previous, }; const PW_RENDERFULLCONTENT: PRINT_WINDOW_FLAGS = PRINT_WINDOW_FLAGS(2); let captured = unsafe { PrintWindow(window, memory_dc.0, PW_RENDERFULLCONTENT) }.as_bool() || unsafe { PrintWindow(window, memory_dc.0, PRINT_WINDOW_FLAGS(0)) }.as_bool(); if !captured { return Err(WindowCaptureError::CaptureFailed); } } let byte_len = usize::try_from(u64::from(width) * u64::from(height) * 4) .map_err(|_| WindowCaptureError::WindowTooLarge { width, height })?; let mut bgra = vec![0_u8; byte_len]; let mut bitmap_info = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: size_of::() as u32, biWidth: width_i32, // Negative height asks GetDIBits for top-down rows. biHeight: -height_i32, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, biSizeImage: byte_len as u32, ..BITMAPINFOHEADER::default() }, ..BITMAPINFO::default() }; let copied_rows = unsafe { GetDIBits( screen_dc.0, bitmap.0, 0, height, Some(bgra.as_mut_ptr().cast()), &mut bitmap_info, DIB_RGB_COLORS, ) }; if copied_rows != height_i32 { return Err(last_windows_error()); } for pixel in bgra.chunks_exact_mut(4) { pixel.swap(0, 2); // BI_RGB device-dependent bitmaps commonly leave alpha at zero. pixel[3] = 255; } let png_bytes = encode_rgba_png(width, height, &bgra)?; Ok(WindowCapture { width, height, png_bytes, }) } #[cfg(not(windows))] fn capture_selected_window_native( _selection: &WindowSelection, _limits: CaptureLimits, ) -> Result { Err(WindowCaptureError::UnsupportedPlatform) } #[cfg(any(windows, test))] fn encode_rgba_png(width: u32, height: u32, pixels: &[u8]) -> Result, WindowCaptureError> { let expected = usize::try_from(u64::from(width) * u64::from(height) * 4) .map_err(|_| WindowCaptureError::EncodingFailed)?; if pixels.len() != expected { return Err(WindowCaptureError::EncodingFailed); } let mut encoded = Vec::new(); { let mut encoder = png::Encoder::new(&mut encoded, width, height); encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); let mut writer = encoder .write_header() .map_err(|_| WindowCaptureError::EncodingFailed)?; writer .write_image_data(pixels) .map_err(|_| WindowCaptureError::EncodingFailed)?; } Ok(encoded) } #[cfg(windows)] struct ScreenDc(windows::Win32::Graphics::Gdi::HDC); #[cfg(windows)] impl Drop for ScreenDc { fn drop(&mut self) { unsafe { windows::Win32::Graphics::Gdi::ReleaseDC(None, self.0); } } } #[cfg(windows)] struct MemoryDc(windows::Win32::Graphics::Gdi::HDC); #[cfg(windows)] impl Drop for MemoryDc { fn drop(&mut self) { unsafe { let _ = windows::Win32::Graphics::Gdi::DeleteDC(self.0); } } } #[cfg(windows)] struct Bitmap(windows::Win32::Graphics::Gdi::HBITMAP); #[cfg(windows)] impl Drop for Bitmap { fn drop(&mut self) { use windows::Win32::Graphics::Gdi::{DeleteObject, HGDIOBJ}; unsafe { let _ = DeleteObject(HGDIOBJ(self.0.0)); } } } #[cfg(windows)] struct SelectedGdiObject { dc: windows::Win32::Graphics::Gdi::HDC, previous: windows::Win32::Graphics::Gdi::HGDIOBJ, } #[cfg(windows)] impl Drop for SelectedGdiObject { fn drop(&mut self) { unsafe { windows::Win32::Graphics::Gdi::SelectObject(self.dc, self.previous); } } } #[cfg(windows)] fn map_windows_error(error: windows::core::Error) -> WindowCaptureError { WindowCaptureError::Platform(error.code().0 as u32) } #[cfg(windows)] fn last_windows_error() -> WindowCaptureError { let code = unsafe { windows::Win32::Foundation::GetLastError() }.0; if code == 0 { WindowCaptureError::CaptureFailed } else { WindowCaptureError::Platform(code) } } #[cfg(test)] mod tests { use super::*; #[test] fn caps_capture_dimensions_and_pixel_count() { assert!(CaptureLimits::default().validate().is_ok()); assert_eq!( CaptureLimits { maximum_pixels: u64::MAX, ..CaptureLimits::default() } .validate(), Err(WindowCaptureError::InvalidLimits) ); assert_eq!( CaptureLimits::default().validate_dimensions(8192, 8192), Err(WindowCaptureError::WindowTooLarge { width: 8192, height: 8192, }) ); } #[test] fn encodes_an_opaque_rgba_pixel_without_disk_io() { let bytes = encode_rgba_png(1, 1, &[1, 2, 3, 255]).expect("encode pixel"); assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n"); } }