Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: windows支持hidpi #177

Merged
merged 4 commits into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "xcap"
version = "0.1.0"
version = "0.1.1"
edition = "2021"
description = "XCap is a cross-platform screen capture library written in Rust. It supports Linux (X11, Wayland), MacOS, and Windows. XCap supports screenshot and video recording (WIP)."
license = "Apache-2.0"
Expand All @@ -12,9 +12,9 @@ keywords = ["screen", "monitor", "window", "capture", "image"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["default-image"]
vendored = ["dbus/vendored"]
default-image = ["image/default"]
image = ["image/default"]

[dependencies]
image = { version = "0.25", default-features = false, features = ["png"] }
log = "0.4"
Expand All @@ -29,6 +29,7 @@ windows = { version = "0.58", features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_Graphics_Dwm",
"Win32_System_LibraryLoader",
"Win32_UI_WindowsAndMessaging",
"Win32_Storage_Xps",
"Win32_System_Threading",
Expand Down
44 changes: 42 additions & 2 deletions src/windows/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ use std::{ops::Deref, ptr};
use windows::{
core::PCWSTR,
Win32::{
Foundation::{CloseHandle, GetLastError, HANDLE, HWND},
Foundation::{CloseHandle, FreeLibrary, GetLastError, HANDLE, HMODULE, HWND},
Graphics::Gdi::{CreateDCW, DeleteDC, DeleteObject, GetWindowDC, ReleaseDC, HBITMAP, HDC},
System::Threading::{OpenProcess, PROCESS_ACCESS_RIGHTS},
System::{
LibraryLoader::LoadLibraryW,
Threading::{OpenProcess, PROCESS_ACCESS_RIGHTS},
},
},
};

Expand Down Expand Up @@ -137,3 +140,40 @@ impl BoxProcessHandle {
}
}
}

#[derive(Debug)]
pub(super) struct BoxHModule(HMODULE);

impl Deref for BoxHModule {
type Target = HMODULE;
fn deref(&self) -> &Self::Target {
&self.0
}
}

impl Drop for BoxHModule {
fn drop(&mut self) {
unsafe {
if let Err(err) = FreeLibrary(self.0) {
log::error!("FreeLibrary {:?} failed {:?}", self, err);
}
};
}
}

impl BoxHModule {
pub fn new(lib_filename: PCWSTR) -> XCapResult<Self> {
unsafe {
let hmodule = LoadLibraryW(lib_filename)?;

if hmodule.is_invalid() {
return Err(XCapError::new(format!(
"LoadLibraryW error {:?}",
GetLastError()
)));
}

Ok(Self(hmodule))
}
}
}
84 changes: 73 additions & 11 deletions src/windows/impl_monitor.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
use image::RgbaImage;
use std::mem;

use image::RgbaImage;
use windows::{
core::PCWSTR,
core::{s, w, HRESULT, PCWSTR},
Win32::{
Foundation::{BOOL, LPARAM, POINT, RECT, TRUE},
Foundation::{BOOL, HANDLE, LPARAM, POINT, RECT, TRUE},
Graphics::Gdi::{
EnumDisplayMonitors, EnumDisplaySettingsW, GetDeviceCaps, GetMonitorInfoW,
MonitorFromPoint, DESKTOPHORZRES, DEVMODEW, DMDO_180, DMDO_270, DMDO_90, DMDO_DEFAULT,
ENUM_CURRENT_SETTINGS, HDC, HMONITOR, HORZRES, MONITORINFO, MONITORINFOEXW,
MONITOR_DEFAULTTONULL,
},
System::LibraryLoader::GetProcAddress,
UI::WindowsAndMessaging::MONITORINFOF_PRIMARY,
},
};

use crate::error::{XCapError, XCapResult};

use super::{
boxed::BoxHDC, capture::capture_monitor, impl_video_recorder::ImplVideoRecorder,
boxed::{BoxHDC, BoxHModule},
capture::capture_monitor,
impl_video_recorder::ImplVideoRecorder,
utils::wide_string_to_string,
};

Expand Down Expand Up @@ -70,6 +74,70 @@ fn get_dev_mode_w(monitor_info_exw: &MONITORINFOEXW) -> XCapResult<DEVMODEW> {
Ok(dev_mode_w)
}

// 定义 GetProcessDpiAwareness 函数的类型
type GetProcessDpiAwareness =
unsafe extern "system" fn(hprocess: HANDLE, value: *mut u32) -> HRESULT;

// 定义 GetDpiForMonitor 函数的类型
type GetDpiForMonitor = unsafe extern "system" fn(
hmonitor: HMONITOR,
dpi_type: u32,
dpi_x: *mut u32,
dpi_y: *mut u32,
) -> HRESULT;

fn get_hi_dpi_scale_factor(hmonitor: HMONITOR) -> XCapResult<f32> {
unsafe {
let box_hmodule = BoxHModule::new(w!("Shcore.dll"))?;

let get_get_process_dpi_awareness_proc_address =
GetProcAddress(*box_hmodule, s!("GetProcessDpiAwareness")).ok_or(XCapError::new(
"GetProcAddress GetProcessDpiAwareness failed",
))?;

let get_get_process_dpi_awareness: GetProcessDpiAwareness =
mem::transmute(get_get_process_dpi_awareness_proc_address);

let mut process_dpi_awareness = 0;
// https://learn.microsoft.com/zh-cn/windows/win32/api/shellscalingapi/nf-shellscalingapi-getprocessdpiawareness
get_get_process_dpi_awareness(HANDLE::default(), &mut process_dpi_awareness).ok()?;

// 当前进程不感知 DPI,则回退到 GetDeviceCaps 获取 DPI
if process_dpi_awareness == 0 {
return Err(XCapError::new("Process not DPI aware"));
}

let get_dpi_for_monitor_proc_address = GetProcAddress(*box_hmodule, s!("GetDpiForMonitor"))
.ok_or(XCapError::new("GetProcAddress GetDpiForMonitor failed"))?;

let get_dpi_for_monitor: GetDpiForMonitor =
mem::transmute(get_dpi_for_monitor_proc_address);

let mut dpi_x = 0;
let mut dpi_y = 0;

// https://learn.microsoft.com/zh-cn/windows/win32/api/shellscalingapi/ne-shellscalingapi-monitor_dpi_type
get_dpi_for_monitor(hmonitor, 0, &mut dpi_x, &mut dpi_y).ok()?;

Ok(dpi_x as f32 / 96.0)
}
}

fn get_scale_factor(hmonitor: HMONITOR, box_hdc_monitor: BoxHDC) -> XCapResult<f32> {
let scale_factor = get_hi_dpi_scale_factor(hmonitor).unwrap_or_else(|err| {
log::info!("{}", err);
// https://learn.microsoft.com/zh-cn/windows/win32/api/wingdi/nf-wingdi-getdevicecaps
unsafe {
let physical_width = GetDeviceCaps(*box_hdc_monitor, DESKTOPHORZRES);
let logical_width = GetDeviceCaps(*box_hdc_monitor, HORZRES);

physical_width as f32 / logical_width as f32
}
});

Ok(scale_factor)
}

impl ImplMonitor {
pub fn new(hmonitor: HMONITOR) -> XCapResult<ImplMonitor> {
let mut monitor_info_ex_w = MONITORINFOEXW::default();
Expand Down Expand Up @@ -97,13 +165,7 @@ impl ImplMonitor {
};

let box_hdc_monitor = BoxHDC::from(&monitor_info_ex_w.szDevice);

let scale_factor = unsafe {
let physical_width = GetDeviceCaps(*box_hdc_monitor, DESKTOPHORZRES);
let logical_width = GetDeviceCaps(*box_hdc_monitor, HORZRES);

physical_width as f32 / logical_width as f32
};
let scale_factor = get_scale_factor(hmonitor, box_hdc_monitor)?;

Ok(ImplMonitor {
hmonitor,
Expand Down
Loading