DPI for everyone (#548)

This commit is contained in:
Francesca Frangipane 2018-06-14 19:42:18 -04:00 committed by GitHub
parent f083dae328
commit 1b74822cfc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
41 changed files with 3096 additions and 1663 deletions

196
src/platform/windows/dpi.rs Normal file
View file

@ -0,0 +1,196 @@
#![allow(non_snake_case, unused_unsafe)]
use std::mem;
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use winapi::shared::minwindef::{BOOL, UINT, FALSE};
use winapi::shared::windef::{
DPI_AWARENESS_CONTEXT,
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE,
HDC,
HMONITOR,
HWND,
};
use winapi::shared::winerror::S_OK;
use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryA};
use winapi::um::shellscalingapi::{
MDT_EFFECTIVE_DPI,
MONITOR_DPI_TYPE,
PROCESS_DPI_AWARENESS,
PROCESS_PER_MONITOR_DPI_AWARE,
};
use winapi::um::wingdi::{GetDeviceCaps, LOGPIXELSX};
use winapi::um::winnt::{HRESULT, LPCSTR};
use winapi::um::winuser::{self, MONITOR_DEFAULTTONEAREST};
const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT = -4isize as _;
type SetProcessDPIAware = unsafe extern "system" fn () -> BOOL;
type SetProcessDpiAwareness = unsafe extern "system" fn (
value: PROCESS_DPI_AWARENESS,
) -> HRESULT;
type SetProcessDpiAwarenessContext = unsafe extern "system" fn (
value: DPI_AWARENESS_CONTEXT,
) -> BOOL;
type GetDpiForWindow = unsafe extern "system" fn (hwnd: HWND) -> UINT;
type GetDpiForMonitor = unsafe extern "system" fn (
hmonitor: HMONITOR,
dpi_type: MONITOR_DPI_TYPE,
dpi_x: *mut UINT,
dpi_y: *mut UINT,
) -> HRESULT;
type EnableNonClientDpiScaling = unsafe extern "system" fn (hwnd: HWND) -> BOOL;
// Helper function to dynamically load function pointer.
// `library` and `function` must be zero-terminated.
fn get_function_impl(library: &str, function: &str) -> Option<*const c_void> {
assert_eq!(library.chars().last(), Some('\0'));
assert_eq!(function.chars().last(), Some('\0'));
// Library names we will use are ASCII so we can use the A version to avoid string conversion.
let module = unsafe { LoadLibraryA(library.as_ptr() as LPCSTR) };
if module.is_null() {
return None;
}
let function_ptr = unsafe { GetProcAddress(module, function.as_ptr() as LPCSTR) };
if function_ptr.is_null() {
return None;
}
Some(function_ptr as _)
}
macro_rules! get_function {
($lib:expr, $func:ident) => {
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0'))
.map(|f| unsafe { mem::transmute::<*const _, $func>(f) })
}
}
lazy_static! {
static ref GET_DPI_FOR_WINDOW: Option<GetDpiForWindow> = get_function!(
"user32.dll",
GetDpiForWindow
);
static ref GET_DPI_FOR_MONITOR: Option<GetDpiForMonitor> = get_function!(
"shcore.dll",
GetDpiForMonitor
);
static ref ENABLE_NON_CLIENT_DPI_SCALING: Option<EnableNonClientDpiScaling> = get_function!(
"user32.dll",
EnableNonClientDpiScaling
);
}
pub fn become_dpi_aware(enable: bool) {
if !enable { return; }
static ENABLE_DPI_AWARENESS: Once = ONCE_INIT;
ENABLE_DPI_AWARENESS.call_once(|| { unsafe {
if let Some(SetProcessDpiAwarenessContext) = get_function!(
"user32.dll",
SetProcessDpiAwarenessContext
) {
// We are on Windows 10 Anniversary Update (1607) or later.
if SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
== FALSE {
// V2 only works with Windows 10 Creators Update (1703). Try using the older
// V1 if we can't set V2.
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
}
} else if let Some(SetProcessDpiAwareness) = get_function!(
"shcore.dll",
SetProcessDpiAwareness
) {
// We are on Windows 8.1 or later.
SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
} else if let Some(SetProcessDPIAware) = get_function!(
"user32.dll",
SetProcessDPIAware
) {
// We are on Vista or later.
SetProcessDPIAware();
}
} });
}
pub fn enable_non_client_dpi_scaling(hwnd: HWND) {
unsafe {
if let Some(EnableNonClientDpiScaling) = *ENABLE_NON_CLIENT_DPI_SCALING {
EnableNonClientDpiScaling(hwnd);
}
}
}
pub fn get_monitor_dpi(hmonitor: HMONITOR) -> Option<u32> {
unsafe {
if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR {
// We are on Windows 8.1 or later.
let mut dpi_x = 0;
let mut dpi_y = 0;
if GetDpiForMonitor(hmonitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK {
// MSDN says that "the values of *dpiX and *dpiY are identical. You only need to
// record one of the values to determine the DPI and respond appropriately".
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510(v=vs.85).aspx
return Some(dpi_x as u32)
}
}
}
None
}
pub const BASE_DPI: u32 = 96;
pub fn dpi_to_scale_factor(dpi: u32) -> f64 {
dpi as f64 / BASE_DPI as f64
}
pub unsafe fn get_window_dpi(hwnd: HWND, hdc: HDC) -> u32 {
if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW {
// We are on Windows 10 Anniversary Update (1607) or later.
match GetDpiForWindow(hwnd) {
0 => BASE_DPI, // 0 is returned if hwnd is invalid
dpi => dpi as u32,
}
} else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR {
// We are on Windows 8.1 or later.
let monitor = winuser::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if monitor.is_null() {
return BASE_DPI;
}
let mut dpi_x = 0;
let mut dpi_y = 0;
if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK {
dpi_x as u32
} else {
BASE_DPI
}
} else {
// We are on Vista or later.
if winuser::IsProcessDPIAware() != FALSE {
// If the process is DPI aware, then scaling must be handled by the application using
// this DPI value.
GetDeviceCaps(hdc, LOGPIXELSX) as u32
} else {
// If the process is DPI unaware, then scaling is performed by the OS; we thus return
// 96 (scale factor 1.0) to prevent the window from being re-scaled by both the
// application and the WM.
BASE_DPI
}
}
}
// Use this when you have both the HWND and HDC on hand (i.e. window methods)
pub fn get_window_scale_factor(hwnd: HWND, hdc: HDC) -> f64 {
dpi_to_scale_factor(unsafe { get_window_dpi(hwnd, hdc) })
}
// Use this when you only have the HWND (i.e. event handling)
pub fn get_hwnd_scale_factor(hwnd: HWND) -> f64 {
let hdc = unsafe { winuser::GetDC(hwnd) };
if hdc.is_null() {
panic!("[winit] `GetDC` returned null!");
}
unsafe { get_window_scale_factor(hwnd, hdc) }
}

View file

@ -12,42 +12,56 @@
//! The closure passed to the `execute_in_thread` method takes an `Inserter` that you can use to
//! add a `WindowState` entry to a list of window to be used by the callback.
use std::{mem, ptr, thread};
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::OsString;
use std::mem;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::AsRawHandle;
use std::ptr;
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Barrier;
use std::sync::Mutex;
use std::sync::Condvar;
use std::thread;
use std::sync::{Arc, Barrier, Condvar, mpsc, Mutex};
use winapi::shared::minwindef::{LOWORD, HIWORD, DWORD, WPARAM, LPARAM, INT, UINT, LRESULT, MAX_PATH};
use winapi::ctypes::c_int;
use winapi::shared::minwindef::{
BOOL,
DWORD,
HIWORD,
INT,
LOWORD,
LPARAM,
LRESULT,
MAX_PATH,
UINT,
WPARAM,
};
use winapi::shared::windef::{HWND, POINT, RECT};
use winapi::shared::windowsx;
use winapi::um::{winuser, shellapi, processthreadsapi};
use winapi::um::winnt::{LONG, SHORT};
use winapi::um::winnt::{LONG, LPCSTR, SHORT};
use events::DeviceEvent;
use {
ControlFlow,
CursorState,
Event,
EventsLoopClosed,
KeyboardInput,
LogicalPosition,
LogicalSize,
PhysicalSize,
WindowEvent,
WindowId as SuperWindowId,
};
use events::{DeviceEvent, Touch, TouchPhase};
use platform::platform::{event, Cursor, WindowId, DEVICE_ID, wrap_device_id, util};
use platform::platform::dpi::{
become_dpi_aware,
dpi_to_scale_factor,
enable_non_client_dpi_scaling,
get_hwnd_scale_factor,
};
use platform::platform::event::{handle_extended_keys, process_key_params, vkey_to_winit_vkey};
use platform::platform::raw_input::*;
use platform::platform::raw_input::{get_raw_input_data, get_raw_mouse_button_state};
use platform::platform::window::adjust_size;
use ControlFlow;
use CursorState;
use Event;
use EventsLoopClosed;
use KeyboardInput;
use WindowAttributes;
use WindowEvent;
use WindowId as SuperWindowId;
use events::{Touch, TouchPhase};
/// Contains saved window info for switching between fullscreen
#[derive(Clone)]
pub struct SavedWindowInfo {
@ -57,6 +71,11 @@ pub struct SavedWindowInfo {
pub ex_style: LONG,
/// Window position and size
pub rect: RECT,
// Since a window can be fullscreened to a different monitor, a DPI change can be triggered. This could result in
// the window being automitcally resized to smaller/larger than it was supposed to be restored to, so we thus must
// check if the post-fullscreen DPI matches the pre-fullscreen DPI.
pub is_fullscreen: bool,
pub dpi_factor: Option<f64>,
}
/// Contains information about states and the window that the callback is going to use.
@ -67,11 +86,28 @@ pub struct WindowState {
/// Cursor state to set at the next `WM_SETCURSOR` event received.
pub cursor_state: CursorState,
/// Used by `WM_GETMINMAXINFO`.
pub attributes: WindowAttributes,
pub max_size: Option<PhysicalSize>,
pub min_size: Option<PhysicalSize>,
/// Will contain `true` if the mouse is hovering the window.
pub mouse_in_window: bool,
/// Saved window info for fullscreen restored
pub saved_window_info: Option<SavedWindowInfo>,
// This is different from the value in `SavedWindowInfo`! That one represents the DPI saved upon entering
// fullscreen. This will always be the most recent DPI for the window.
pub dpi_factor: f64,
}
impl WindowState {
pub fn update_min_max(&mut self, old_dpi_factor: f64, new_dpi_factor: f64) {
let scale_factor = new_dpi_factor / old_dpi_factor;
let dpi_adjuster = |mut physical_size: PhysicalSize| -> PhysicalSize {
physical_size.width *= scale_factor;
physical_size.height *= scale_factor;
physical_size
};
self.max_size = self.max_size.map(&dpi_adjuster);
self.min_size = self.min_size.map(&dpi_adjuster);
}
}
/// Dummy object that allows inserting a window's state.
@ -98,11 +134,17 @@ pub struct EventsLoop {
// Variable that contains the block state of the win32 event loop thread during a WM_SIZE event.
// The mutex's value is `true` when it's blocked, and should be set to false when it's done
// blocking. That's done by the parent thread when it receives a Resized event.
win32_block_loop: Arc<(Mutex<bool>, Condvar)>
win32_block_loop: Arc<(Mutex<bool>, Condvar)>,
}
impl EventsLoop {
pub fn new() -> EventsLoop {
Self::with_dpi_awareness(true)
}
pub fn with_dpi_awareness(dpi_aware: bool) -> EventsLoop {
become_dpi_aware(dpi_aware);
// The main events transfer channel.
let (tx, rx) = mpsc::channel();
let win32_block_loop = Arc::new((Mutex::new(false), Condvar::new()));
@ -171,7 +213,7 @@ impl EventsLoop {
EventsLoop {
thread_id,
receiver: rx,
win32_block_loop
win32_block_loop,
}
}
@ -289,22 +331,21 @@ impl EventsLoopProxy {
where
F: FnMut(Inserter) + Send + 'static,
{
unsafe {
// We are using double-boxing here because it make casting back much easier
let boxed = Box::new(function) as Box<FnMut(_)>;
let boxed2 = Box::new(boxed);
let raw = Box::into_raw(boxed2);
// We are using double-boxing here because it make casting back much easier
let double_box = Box::new(Box::new(function) as Box<FnMut(_)>);
let raw = Box::into_raw(double_box);
let res = winuser::PostThreadMessageA(
let res = unsafe {
winuser::PostThreadMessageA(
self.thread_id,
*EXEC_MSG_ID,
raw as *mut () as usize as WPARAM,
0,
);
// PostThreadMessage can only fail if the thread ID is invalid (which shouldn't happen
// as the events loop is still alive) or if the queue is full.
assert!(res != 0, "PostThreadMessage failed; is the messages queue full?");
}
)
};
// PostThreadMessage can only fail if the thread ID is invalid (which shouldn't happen as
// the events loop is still alive) or if the queue is full.
assert!(res != 0, "PostThreadMessage failed; is the messages queue full?");
}
}
@ -313,7 +354,7 @@ lazy_static! {
// WPARAM and LPARAM are unused.
static ref WAKEUP_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as *const i8)
winuser::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as LPCSTR)
}
};
// Message sent when we want to execute a closure in the thread.
@ -321,14 +362,21 @@ lazy_static! {
// and LPARAM is unused.
static ref EXEC_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as *const i8)
winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as LPCSTR)
}
};
// Message sent by a `Window` when it wants to be destroyed by the main thread.
// WPARAM and LPARAM are unused.
pub static ref DESTROY_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::DestroyMsg\0".as_ptr() as *const i8)
winuser::RegisterWindowMessageA("Winit::DestroyMsg\0".as_ptr() as LPCSTR)
}
};
// Message sent by a `Window` after creation if it has a DPI != 96.
// WPARAM is the the DPI (u32). LOWORD of LPARAM is width, and HIWORD is height.
pub static ref INITIAL_DPI_MSG_ID: u32 = {
unsafe {
winuser::RegisterWindowMessageA("Winit::InitialDpiMsg\0".as_ptr() as LPCSTR)
}
};
}
@ -385,11 +433,18 @@ unsafe fn release_mouse() {
//
// Returning 0 tells the Win32 API that the message has been processed.
// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary
pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
wparam: WPARAM, lparam: LPARAM)
-> LRESULT
{
pub unsafe extern "system" fn callback(
window: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
match msg {
winuser::WM_NCCREATE => {
enable_non_client_dpi_scaling(window);
winuser::DefWindowProcW(window, msg, wparam, lparam)
},
winuser::WM_CLOSE => {
use events::WindowEvent::CloseRequested;
send_event(Event::WindowEvent {
@ -427,9 +482,14 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
let windowpos = lparam as *const winuser::WINDOWPOS;
if (*windowpos).flags & winuser::SWP_NOMOVE != winuser::SWP_NOMOVE {
let dpi_factor = get_hwnd_scale_factor(window);
let logical_position = LogicalPosition::from_physical(
((*windowpos).x, (*windowpos).y),
dpi_factor,
);
send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: Moved((*windowpos).x, (*windowpos).y),
event: Moved(logical_position),
});
}
@ -448,9 +508,11 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
let mut context_stash = context_stash.borrow_mut();
let cstash = context_stash.as_mut().unwrap();
let dpi_factor = get_hwnd_scale_factor(window);
let logical_size = LogicalSize::from_physical((w, h), dpi_factor);
let event = Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: Resized(w, h),
event: Resized(logical_size),
};
// If this window has been inserted into the window map, the resize event happened
@ -528,10 +590,12 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
let x = windowsx::GET_X_LPARAM(lparam) as f64;
let y = windowsx::GET_Y_LPARAM(lparam) as f64;
let dpi_factor = get_hwnd_scale_factor(window);
let position = LogicalPosition::from_physical((x, y), dpi_factor);
send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: CursorMoved { device_id: DEVICE_ID, position: (x, y), modifiers: event::get_key_mods() },
event: CursorMoved { device_id: DEVICE_ID, position, modifiers: event::get_key_mods() },
});
0
@ -869,10 +933,17 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
let mut inputs = Vec::with_capacity( pcount );
inputs.set_len( pcount );
let htouch = lparam as winuser::HTOUCHINPUT;
if winuser::GetTouchInputInfo( htouch, pcount as UINT,
inputs.as_mut_ptr(),
mem::size_of::<winuser::TOUCHINPUT>() as INT ) > 0 {
if winuser::GetTouchInputInfo(
htouch,
pcount as UINT,
inputs.as_mut_ptr(),
mem::size_of::<winuser::TOUCHINPUT>() as INT,
) > 0 {
let dpi_factor = get_hwnd_scale_factor(window);
for input in &inputs {
let x = (input.x as f64) / 100f64;
let y = (input.y as f64) / 100f64;
let location = LogicalPosition::from_physical((x, y), dpi_factor);
send_event( Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: WindowEvent::Touch(Touch {
@ -886,8 +957,7 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
} else {
continue;
},
location: ((input.x as f64) / 100f64,
(input.y as f64) / 100f64),
location,
id: input.dwID as u64,
device_id: DEVICE_ID,
})
@ -907,11 +977,14 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
let x = windowsx::GET_X_LPARAM(lparam) as f64;
let y = windowsx::GET_Y_LPARAM(lparam) as f64;
let dpi_factor = get_hwnd_scale_factor(window);
let position = LogicalPosition::from_physical((x, y), dpi_factor);
send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: CursorMoved { device_id: DEVICE_ID, position: (x, y), modifiers: event::get_key_mods() },
event: CursorMoved { device_id: DEVICE_ID, position, modifiers: event::get_key_mods() },
});
0
},
@ -985,18 +1058,15 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
if let Some(wstash) = cstash.windows.get(&window) {
let window_state = wstash.lock().unwrap();
if window_state.attributes.min_dimensions.is_some() ||
window_state.attributes.max_dimensions.is_some() {
if window_state.min_size.is_some() || window_state.max_size.is_some() {
let style = winuser::GetWindowLongA(window, winuser::GWL_STYLE) as DWORD;
let ex_style = winuser::GetWindowLongA(window, winuser::GWL_EXSTYLE) as DWORD;
if let Some(min_dimensions) = window_state.attributes.min_dimensions {
let (width, height) = adjust_size(min_dimensions, style, ex_style);
if let Some(min_size) = window_state.min_size {
let (width, height) = adjust_size(min_size, style, ex_style);
(*mmi).ptMinTrackSize = POINT { x: width as i32, y: height as i32 };
}
if let Some(max_dimensions) = window_state.attributes.max_dimensions {
let (width, height) = adjust_size(max_dimensions, style, ex_style);
if let Some(max_size) = window_state.max_size {
let (width, height) = adjust_size(max_size, style, ex_style);
(*mmi).ptMaxTrackSize = POINT { x: width as i32, y: height as i32 };
}
}
@ -1007,10 +1077,115 @@ pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
0
},
// Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change
// DPI, therefore all applications are closed while DPI is changing.
winuser::WM_DPICHANGED => {
use events::WindowEvent::HiDpiFactorChanged;
// This message actually provides two DPI values - x and y. However MSDN says that
// "you only need to use either the X-axis or the Y-axis value when scaling your
// application since they are the same".
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn312083(v=vs.85).aspx
let new_dpi_x = u32::from(LOWORD(wparam as DWORD));
let new_dpi_factor = dpi_to_scale_factor(new_dpi_x);
let suppress_resize = CONTEXT_STASH.with(|context_stash| {
context_stash
.borrow()
.as_ref()
.and_then(|cstash| cstash.windows.get(&window))
.map(|window_state_mutex| {
let mut window_state = window_state_mutex.lock().unwrap();
let suppress_resize = window_state.saved_window_info
.as_mut()
.map(|saved_window_info| {
let dpi_changed = if !saved_window_info.is_fullscreen {
saved_window_info.dpi_factor.take() != Some(new_dpi_factor)
} else {
false
};
!dpi_changed || saved_window_info.is_fullscreen
})
.unwrap_or(false);
// Now we adjust the min/max dimensions for the new DPI.
if !suppress_resize {
let old_dpi_factor = window_state.dpi_factor;
window_state.update_min_max(old_dpi_factor, new_dpi_factor);
}
window_state.dpi_factor = new_dpi_factor;
suppress_resize
})
.unwrap_or(false)
});
// This prevents us from re-applying DPI adjustment to the restored size after exiting
// fullscreen (the restored size is already DPI adjusted).
if !suppress_resize {
// Resize window to the size suggested by Windows.
let rect = &*(lparam as *const RECT);
winuser::SetWindowPos(
window,
ptr::null_mut(),
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
winuser::SWP_NOZORDER | winuser::SWP_NOACTIVATE,
);
}
send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: HiDpiFactorChanged(new_dpi_factor),
});
0
},
_ => {
if msg == *DESTROY_MSG_ID {
winuser::DestroyWindow(window);
0
} else if msg == *INITIAL_DPI_MSG_ID {
use events::WindowEvent::HiDpiFactorChanged;
let scale_factor = dpi_to_scale_factor(wparam as u32);
send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)),
event: HiDpiFactorChanged(scale_factor),
});
// Automatically resize for actual DPI
let width = LOWORD(lparam as DWORD) as u32;
let height = HIWORD(lparam as DWORD) as u32;
let (adjusted_width, adjusted_height): (u32, u32) = PhysicalSize::from_logical(
(width, height),
scale_factor,
).into();
// We're not done yet! `SetWindowPos` needs the window size, not the client area size.
let mut rect = RECT {
top: 0,
left: 0,
bottom: adjusted_height as LONG,
right: adjusted_width as LONG,
};
let dw_style = winuser::GetWindowLongA(window, winuser::GWL_STYLE) as DWORD;
let b_menu = !winuser::GetMenu(window).is_null() as BOOL;
let dw_style_ex = winuser::GetWindowLongA(window, winuser::GWL_EXSTYLE) as DWORD;
winuser::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex);
let outer_x = (rect.right - rect.left).abs() as c_int;
let outer_y = (rect.top - rect.bottom).abs() as c_int;
winuser::SetWindowPos(
window,
ptr::null_mut(),
0,
0,
outer_x,
outer_y,
winuser::SWP_NOMOVE
| winuser::SWP_NOREPOSITION
| winuser::SWP_NOZORDER
| winuser::SWP_NOACTIVATE,
);
0
} else {
winuser::DefWindowProcW(window, msg, wparam, lparam)
}

View file

@ -47,6 +47,7 @@ pub struct WindowId(HWND);
unsafe impl Send for WindowId {}
unsafe impl Sync for WindowId {}
mod dpi;
mod event;
mod events_loop;
mod icon;

View file

@ -1,38 +1,31 @@
use winapi::ctypes::wchar_t;
use winapi::shared::minwindef::{DWORD, LPARAM, BOOL, TRUE};
use winapi::shared::windef::{HMONITOR, HDC, LPRECT, HWND};
use winapi::shared::minwindef::{BOOL, DWORD, LPARAM, TRUE};
use winapi::shared::windef::{HDC, HMONITOR, HWND, LPRECT, POINT};
use winapi::um::winuser;
use std::collections::VecDeque;
use std::{mem, ptr};
use std::collections::VecDeque;
use {PhysicalPosition, PhysicalSize};
use super::{EventsLoop, util};
use platform::platform::dpi::{dpi_to_scale_factor, get_monitor_dpi};
/// Win32 implementation of the main `MonitorId` object.
#[derive(Debug, Clone)]
pub struct MonitorId {
/// The system name of the adapter.
adapter_name: [wchar_t; 32],
/// Monitor handle.
hmonitor: HMonitor,
/// The system name of the monitor.
monitor_name: String,
/// True if this is the primary monitor.
primary: bool,
/// The position of the monitor in pixels on the desktop.
///
/// A window that is positioned at these coordinates will overlap the monitor.
position: (i32, i32),
/// The current resolution in pixels on the monitor.
dimensions: (u32, u32),
/// DPI scaling factor.
hidpi_factor: f32,
/// DPI scale factor.
hidpi_factor: f64,
}
// Send is not implemented for HMONITOR, we have to wrap it and implement it manually.
@ -44,122 +37,109 @@ struct HMonitor(HMONITOR);
unsafe impl Send for HMonitor {}
unsafe extern "system" fn monitor_enum_proc(hmonitor: HMONITOR, _: HDC, place: LPRECT, data: LPARAM) -> BOOL {
unsafe extern "system" fn monitor_enum_proc(
hmonitor: HMONITOR,
_hdc: HDC,
_place: LPRECT,
data: LPARAM,
) -> BOOL {
let monitors = data as *mut VecDeque<MonitorId>;
let place = *place;
let position = (place.left as i32, place.top as i32);
let dimensions = ((place.right - place.left) as u32, (place.bottom - place.top) as u32);
let mut monitor_info: winuser::MONITORINFOEXW = mem::zeroed();
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
if winuser::GetMonitorInfoW(hmonitor, &mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO) == 0 {
// Some error occurred, just skip this monitor and go on.
return TRUE;
}
(*monitors).push_back(MonitorId {
adapter_name: monitor_info.szDevice,
hmonitor: HMonitor(hmonitor),
monitor_name: util::wchar_to_string(&monitor_info.szDevice),
primary: monitor_info.dwFlags & winuser::MONITORINFOF_PRIMARY != 0,
position,
dimensions,
hidpi_factor: 1.0,
});
// TRUE means continue enumeration.
TRUE
(*monitors).push_back(MonitorId::from_hmonitor(hmonitor));
TRUE // continue enumeration
}
impl EventsLoop {
// TODO: Investigate opportunities for caching
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
let mut monitors: VecDeque<MonitorId> = VecDeque::new();
unsafe {
let mut result: VecDeque<MonitorId> = VecDeque::new();
winuser::EnumDisplayMonitors(ptr::null_mut(), ptr::null_mut(), Some(monitor_enum_proc), &mut result as *mut _ as LPARAM);
result
winuser::EnumDisplayMonitors(
ptr::null_mut(),
ptr::null_mut(),
Some(monitor_enum_proc),
&mut monitors as *mut _ as LPARAM,
);
}
monitors
}
pub fn get_current_monitor(handle: HWND) -> MonitorId {
unsafe {
let mut monitor_info: winuser::MONITORINFOEXW = mem::zeroed();
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
let hmonitor = winuser::MonitorFromWindow(handle, winuser::MONITOR_DEFAULTTONEAREST);
winuser::GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO,
);
let place = monitor_info.rcMonitor;
let position = (place.left as i32, place.top as i32);
let dimensions = (
(place.right - place.left) as u32,
(place.bottom - place.top) as u32,
);
MonitorId {
adapter_name: monitor_info.szDevice,
hmonitor: super::monitor::HMonitor(hmonitor),
monitor_name: util::wchar_to_string(&monitor_info.szDevice),
primary: monitor_info.dwFlags & winuser::MONITORINFOF_PRIMARY != 0,
position,
dimensions,
hidpi_factor: 1.0,
}
}
pub fn get_current_monitor(hwnd: HWND) -> MonitorId {
let hmonitor = unsafe {
winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST)
};
MonitorId::from_hmonitor(hmonitor)
}
pub fn get_primary_monitor(&self) -> MonitorId {
// we simply get all available monitors and return the one with the `MONITORINFOF_PRIMARY` flag
// TODO: it is possible to query the win32 API for the primary monitor, this should be done
// instead
for monitor in self.get_available_monitors().into_iter() {
if monitor.primary {
return monitor;
}
}
const ORIGIN: POINT = POINT { x: 0, y: 0 };
let hmonitor = unsafe {
winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY)
};
MonitorId::from_hmonitor(hmonitor)
}
}
panic!("Failed to find the primary monitor")
fn get_monitor_info(hmonitor: HMONITOR) -> Result<winuser::MONITORINFOEXW, util::WinError> {
let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::uninitialized() };
monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
let status = unsafe {
winuser::GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO,
)
};
if status == 0 {
Err(util::WinError::from_last_error())
} else {
Ok(monitor_info)
}
}
impl MonitorId {
/// See the docs if the crate root file.
pub(crate) fn from_hmonitor(hmonitor: HMONITOR) -> Self {
let monitor_info = get_monitor_info(hmonitor).expect("`GetMonitorInfoW` failed");
let place = monitor_info.rcMonitor;
let dimensions = (
(place.right - place.left) as u32,
(place.bottom - place.top) as u32,
);
MonitorId {
hmonitor: HMonitor(hmonitor),
monitor_name: util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr()),
primary: util::has_flag(monitor_info.dwFlags, winuser::MONITORINFOF_PRIMARY),
position: (place.left as i32, place.top as i32),
dimensions,
hidpi_factor: dpi_to_scale_factor(get_monitor_dpi(hmonitor).unwrap_or(96)),
}
}
#[inline]
pub fn get_name(&self) -> Option<String> {
Some(self.monitor_name.clone())
}
/// See the docs of the crate root file.
#[inline]
pub fn get_native_identifier(&self) -> String {
self.monitor_name.clone()
}
/// See the docs of the crate root file.
#[inline]
pub fn get_hmonitor(&self) -> HMONITOR {
self.hmonitor.0
}
/// See the docs of the crate root file.
#[inline]
pub fn get_dimensions(&self) -> (u32, u32) {
// TODO: retrieve the dimensions every time this is called
self.dimensions
}
/// A window that is positioned at these coordinates will overlap the monitor.
#[inline]
pub fn get_position(&self) -> (i32, i32) {
self.position
pub fn get_dimensions(&self) -> PhysicalSize {
self.dimensions.into()
}
#[inline]
pub fn get_hidpi_factor(&self) -> f32 {
pub fn get_position(&self) -> PhysicalPosition {
self.position.into()
}
#[inline]
pub fn get_hidpi_factor(&self) -> f64 {
self.hidpi_factor
}
}

View file

@ -1,9 +1,9 @@
use std::{self, mem, ptr};
use std::{self, mem, ptr, slice};
use std::ops::BitAnd;
use winapi::ctypes::wchar_t;
use winapi::shared::minwindef::DWORD;
use winapi::shared::windef::RECT;
use winapi::shared::windef::{HWND, RECT};
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::winbase::{
FormatMessageW,
@ -19,6 +19,7 @@ use winapi::um::winnt::{
LANG_NEUTRAL,
SUBLANG_DEFAULT,
};
use winapi::um::winuser;
pub fn has_flag<T>(bitset: T, flag: T) -> bool
where T:
@ -28,9 +29,22 @@ where T:
}
pub fn wchar_to_string(wchar: &[wchar_t]) -> String {
String::from_utf16_lossy(wchar)
.trim_right_matches(0 as char)
.to_string()
String::from_utf16_lossy(wchar).to_string()
}
pub fn wchar_ptr_to_string(wchar: *const wchar_t) -> String {
let len = unsafe { lstrlenW(wchar) } as usize;
let wchar_slice = unsafe { slice::from_raw_parts(wchar, len) };
wchar_to_string(wchar_slice)
}
pub fn get_window_rect(hwnd: HWND) -> Option<RECT> {
let mut rect: RECT = unsafe { mem::uninitialized() };
if unsafe { winuser::GetWindowRect(hwnd, &mut rect) } != 0 {
Some(rect)
} else {
None
}
}
// This won't be needed anymore if we just add a derive to winapi.

View file

@ -1,29 +1,34 @@
#![cfg(target_os = "windows")]
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::ffi::OsStr;
use std::{io, mem, ptr};
use std::os::raw;
use std::os::windows::ffi::OsStrExt;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::channel;
use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE, UINT};
use winapi::ctypes::c_int;
use winapi::shared::minwindef::{BOOL, DWORD, FALSE, LPARAM, TRUE, UINT, WORD, WPARAM};
use winapi::shared::windef::{HDC, HWND, LPPOINT, POINT, RECT};
use winapi::um::{combaseapi, dwmapi, libloaderapi, winuser};
use winapi::um::objbase::{COINIT_MULTITHREADED};
use winapi::um::shobjidl_core::{CLSID_TaskbarList, ITaskbarList2};
use winapi::um::winnt::{LONG, LPCWSTR};
use CreationError;
use CursorState;
use Icon;
use MonitorId as RootMonitorId;
use MouseCursor;
use WindowAttributes;
use {
CreationError,
CursorState,
Icon,
LogicalPosition,
LogicalSize,
MonitorId as RootMonitorId,
MouseCursor,
PhysicalSize,
WindowAttributes,
};
use platform::platform::{Cursor, EventsLoop, PlatformSpecificWindowBuilderAttributes, WindowId};
use platform::platform::events_loop::{self, DESTROY_MSG_ID};
use platform::platform::dpi::{BASE_DPI, dpi_to_scale_factor, get_window_dpi, get_window_scale_factor};
use platform::platform::events_loop::{self, DESTROY_MSG_ID, INITIAL_DPI_MSG_ID};
use platform::platform::icon::{self, IconType, WinIcon};
use platform::platform::raw_input::register_all_mice_and_keyboards_for_raw_input;
use platform::platform::util;
@ -33,6 +38,12 @@ pub struct Window {
/// Main handle for the window.
window: WindowWrapper,
decorations: Cell<bool>,
maximized: Cell<bool>,
resizable: Cell<bool>,
fullscreen: RefCell<Option<::MonitorId>>,
always_on_top: Cell<bool>,
/// The current window state.
window_state: Arc<Mutex<events_loop::WindowState>>,
@ -56,19 +67,16 @@ unsafe impl Sync for Window {}
// and it added fifty pixels to the top.
// From this we can perform the reverse calculation: Instead of expanding the rectangle, we shrink it.
unsafe fn unjust_window_rect(prc: &mut RECT, style: DWORD, ex_style: DWORD) -> BOOL {
let mut rc: RECT = mem::zeroed();
let mut rc: RECT = mem::uninitialized();
winuser::SetRectEmpty(&mut rc);
let frc = winuser::AdjustWindowRectEx(&mut rc, style, 0, ex_style);
if frc != 0 {
let status = winuser::AdjustWindowRectEx(&mut rc, style, 0, ex_style);
if status != 0 {
prc.left -= rc.left;
prc.top -= rc.top;
prc.right -= rc.right;
prc.bottom -= rc.bottom;
}
frc
status
}
impl Window {
@ -78,16 +86,13 @@ impl Window {
pl_attr: PlatformSpecificWindowBuilderAttributes,
) -> Result<Window, CreationError> {
let (tx, rx) = channel();
let proxy = events_loop.create_proxy();
events_loop.execute_in_thread(move |inserter| {
// We dispatch an `init` function because of code style.
// First person to remove the need for cloning here gets a cookie!
let win = unsafe { init(w_attr.clone(), pl_attr.clone(), inserter, proxy.clone()) };
let _ = tx.send(win);
});
rx.recv().unwrap()
}
@ -115,168 +120,193 @@ impl Window {
}
}
/// See the docs in the crate root file.
pub fn get_position(&self) -> Option<(i32, i32)> {
let mut rect: RECT = unsafe { mem::uninitialized() };
if unsafe { winuser::GetWindowRect(self.window.0, &mut rect) } != 0 {
Some((rect.left as i32, rect.top as i32))
} else {
None
}
pub(crate) fn get_position_physical(&self) -> Option<(i32, i32)> {
util::get_window_rect(self.window.0)
.map(|rect| (rect.left as i32, rect.top as i32))
}
pub fn get_inner_position(&self) -> Option<(i32, i32)> {
use std::mem;
#[inline]
pub fn get_position(&self) -> Option<LogicalPosition> {
self.get_position_physical()
.map(|physical_position| {
let dpi_factor = self.get_hidpi_factor();
LogicalPosition::from_physical(physical_position, dpi_factor)
})
}
pub(crate) fn get_inner_position_physical(&self) -> Option<(i32, i32)> {
let mut position: POINT = unsafe { mem::zeroed() };
if unsafe { winuser::ClientToScreen(self.window.0, &mut position) } == 0 {
return None;
}
Some((position.x, position.y))
}
/// See the docs in the crate root file.
pub fn set_position(&self, x: i32, y: i32) {
#[inline]
pub fn get_inner_position(&self) -> Option<LogicalPosition> {
self.get_inner_position_physical()
.map(|physical_position| {
let dpi_factor = self.get_hidpi_factor();
LogicalPosition::from_physical(physical_position, dpi_factor)
})
}
pub(crate) fn set_position_physical(&self, x: i32, y: i32) {
unsafe {
winuser::SetWindowPos(self.window.0, ptr::null_mut(), x as raw::c_int, y as raw::c_int,
0, 0, winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOSIZE);
winuser::SetWindowPos(
self.window.0,
ptr::null_mut(),
x as c_int,
y as c_int,
0,
0,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOSIZE,
);
winuser::UpdateWindow(self.window.0);
}
}
/// See the docs in the crate root file.
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let mut rect: RECT = unsafe { mem::uninitialized() };
pub fn set_position(&self, logical_position: LogicalPosition) {
let dpi_factor = self.get_hidpi_factor();
let (x, y) = logical_position.to_physical(dpi_factor).into();
self.set_position_physical(x, y);
}
pub(crate) fn get_inner_size_physical(&self) -> Option<(u32, u32)> {
let mut rect: RECT = unsafe { mem::uninitialized() };
if unsafe { winuser::GetClientRect(self.window.0, &mut rect) } == 0 {
return None
return None;
}
Some((
(rect.right - rect.left) as u32,
(rect.bottom - rect.top) as u32
(rect.bottom - rect.top) as u32,
))
}
/// See the docs in the crate root file.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
let mut rect: RECT = unsafe { mem::uninitialized() };
if unsafe { winuser::GetWindowRect(self.window.0, &mut rect) } == 0 {
return None
}
Some((
(rect.right - rect.left) as u32,
(rect.bottom - rect.top) as u32
))
pub fn get_inner_size(&self) -> Option<LogicalSize> {
self.get_inner_size_physical()
.map(|physical_size| {
let dpi_factor = self.get_hidpi_factor();
LogicalSize::from_physical(physical_size, dpi_factor)
})
}
/// See the docs in the crate root file.
pub fn set_inner_size(&self, x: u32, y: u32) {
pub(crate) fn get_outer_size_physical(&self) -> Option<(u32, u32)> {
util::get_window_rect(self.window.0)
.map(|rect| (
(rect.right - rect.left) as u32,
(rect.bottom - rect.top) as u32,
))
}
#[inline]
pub fn get_outer_size(&self) -> Option<LogicalSize> {
self.get_outer_size_physical()
.map(|physical_size| {
let dpi_factor = self.get_hidpi_factor();
LogicalSize::from_physical(physical_size, dpi_factor)
})
}
pub(crate) fn set_inner_size_physical(&self, x: u32, y: u32) {
unsafe {
// Calculate the outer size based upon the specified inner size
let mut rect = RECT { top: 0, left: 0, bottom: y as LONG, right: x as LONG };
let mut rect = RECT {
top: 0,
left: 0,
bottom: y as LONG,
right: x as LONG,
};
let dw_style = winuser::GetWindowLongA(self.window.0, winuser::GWL_STYLE) as DWORD;
let b_menu = !winuser::GetMenu(self.window.0).is_null() as BOOL;
let dw_style_ex = winuser::GetWindowLongA(self.window.0, winuser::GWL_EXSTYLE) as DWORD;
winuser::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex);
let outer_x = (rect.right - rect.left).abs() as raw::c_int;
let outer_y = (rect.top - rect.bottom).abs() as raw::c_int;
winuser::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, outer_x, outer_y,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOREPOSITION | winuser::SWP_NOMOVE);
let outer_x = (rect.right - rect.left).abs() as c_int;
let outer_y = (rect.top - rect.bottom).abs() as c_int;
winuser::SetWindowPos(
self.window.0,
ptr::null_mut(),
0,
0,
outer_x,
outer_y,
winuser::SWP_ASYNCWINDOWPOS
| winuser::SWP_NOZORDER
| winuser::SWP_NOREPOSITION
| winuser::SWP_NOMOVE,
);
winuser::UpdateWindow(self.window.0);
}
}
/// See the docs in the crate root file.
#[inline]
pub fn set_min_dimensions(&self, dimensions: Option<(u32, u32)>) {
let mut window_state = self.window_state.lock().unwrap();
window_state.attributes.min_dimensions = dimensions;
// Make windows re-check the window size bounds.
if let Some(inner_size) = self.get_inner_size() {
unsafe {
let mut rect = RECT { top: 0, left: 0, bottom: inner_size.1 as LONG, right: inner_size.0 as LONG };
let dw_style = winuser::GetWindowLongA(self.window.0, winuser::GWL_STYLE) as DWORD;
let b_menu = !winuser::GetMenu(self.window.0).is_null() as BOOL;
let dw_style_ex = winuser::GetWindowLongA(self.window.0, winuser::GWL_EXSTYLE) as DWORD;
winuser::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex);
let outer_x = (rect.right - rect.left).abs() as raw::c_int;
let outer_y = (rect.top - rect.bottom).abs() as raw::c_int;
winuser::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, outer_x, outer_y,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOREPOSITION | winuser::SWP_NOMOVE);
}
}
pub fn set_inner_size(&self, logical_size: LogicalSize) {
let dpi_factor = self.get_hidpi_factor();
let (width, height) = logical_size.to_physical(dpi_factor).into();
self.set_inner_size_physical(width, height);
}
/// See the docs in the crate root file.
#[inline]
pub fn set_max_dimensions(&self, dimensions: Option<(u32, u32)>) {
let mut window_state = self.window_state.lock().unwrap();
window_state.attributes.max_dimensions = dimensions;
pub(crate) fn set_min_dimensions_physical(&self, dimensions: Option<(u32, u32)>) {
self.window_state.lock().unwrap().min_size = dimensions.map(Into::into);
// Make windows re-check the window size bounds.
if let Some(inner_size) = self.get_inner_size() {
unsafe {
let mut rect = RECT { top: 0, left: 0, bottom: inner_size.1 as LONG, right: inner_size.0 as LONG };
let dw_style = winuser::GetWindowLongA(self.window.0, winuser::GWL_STYLE) as DWORD;
let b_menu = !winuser::GetMenu(self.window.0).is_null() as BOOL;
let dw_style_ex = winuser::GetWindowLongA(self.window.0, winuser::GWL_EXSTYLE) as DWORD;
winuser::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex);
let outer_x = (rect.right - rect.left).abs() as raw::c_int;
let outer_y = (rect.top - rect.bottom).abs() as raw::c_int;
self.get_inner_size_physical()
.map(|(width, height)| self.set_inner_size_physical(width, height));
}
winuser::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, outer_x, outer_y,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOREPOSITION | winuser::SWP_NOMOVE);
}
}
#[inline]
pub fn set_min_dimensions(&self, logical_size: Option<LogicalSize>) {
let physical_size = logical_size.map(|logical_size| {
let dpi_factor = self.get_hidpi_factor();
logical_size.to_physical(dpi_factor).into()
});
self.set_min_dimensions_physical(physical_size);
}
pub fn set_max_dimensions_physical(&self, dimensions: Option<(u32, u32)>) {
self.window_state.lock().unwrap().max_size = dimensions.map(Into::into);
// Make windows re-check the window size bounds.
self.get_inner_size_physical()
.map(|(width, height)| self.set_inner_size_physical(width, height));
}
#[inline]
pub fn set_max_dimensions(&self, logical_size: Option<LogicalSize>) {
let physical_size = logical_size.map(|logical_size| {
let dpi_factor = self.get_hidpi_factor();
logical_size.to_physical(dpi_factor).into()
});
self.set_max_dimensions_physical(physical_size);
}
#[inline]
pub fn set_resizable(&self, resizable: bool) {
if let Ok(mut window_state) = self.window_state.lock() {
if window_state.attributes.resizable == resizable {
return;
}
if window_state.attributes.fullscreen.is_some() {
window_state.attributes.resizable = resizable;
return;
}
let window = self.window.clone();
let mut style = unsafe {
winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE)
};
if resizable {
style |= winuser::WS_SIZEBOX as LONG;
} else {
style &= !winuser::WS_SIZEBOX as LONG;
}
unsafe {
winuser::SetWindowLongW(
window.0,
winuser::GWL_STYLE,
style as _,
);
};
window_state.attributes.resizable = resizable;
if resizable == self.resizable.get() {
return;
}
if self.fullscreen.borrow().is_some() {
// If we're in fullscreen, update stored configuration but don't apply anything.
self.resizable.replace(resizable);
return;
}
}
// TODO: remove
pub fn platform_display(&self) -> *mut ::libc::c_void {
panic!() // Deprecated function ; we don't care anymore
}
// TODO: remove
pub fn platform_window(&self) -> *mut ::libc::c_void {
self.window.0 as *mut ::libc::c_void
let mut style = unsafe {
winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE)
};
if resizable {
style |= winuser::WS_SIZEBOX as LONG;
} else {
style &= !winuser::WS_SIZEBOX as LONG;
}
unsafe {
winuser::SetWindowLongW(
self.window.0,
winuser::GWL_STYLE,
style as _,
);
};
self.resizable.replace(resizable);
}
/// Returns the `hwnd` of this window.
@ -411,29 +441,30 @@ impl Window {
}
#[inline]
pub fn hidpi_factor(&self) -> f32 {
1.0
pub fn get_hidpi_factor(&self) -> f64 {
get_window_scale_factor(self.window.0, self.window.1)
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
let mut point = POINT {
x: x,
y: y,
};
fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), ()> {
let mut point = POINT { x, y };
unsafe {
if winuser::ClientToScreen(self.window.0, &mut point) == 0 {
return Err(());
}
if winuser::SetCursorPos(point.x, point.y) == 0 {
return Err(());
}
}
Ok(())
}
#[inline]
pub fn set_cursor_position(&self, logical_position: LogicalPosition) -> Result<(), ()> {
let dpi_factor = self.get_hidpi_factor();
let (x, y) = logical_position.to_physical(dpi_factor).into();
self.set_cursor_position_physical(x, y)
}
#[inline]
pub fn id(&self) -> WindowId {
WindowId(self.window.0)
@ -441,18 +472,13 @@ impl Window {
#[inline]
pub fn set_maximized(&self, maximized: bool) {
let mut window_state = self.window_state.lock().unwrap();
window_state.attributes.maximized = maximized;
// we only maximized if we are not in fullscreen
if window_state.attributes.fullscreen.is_some() {
return;
}
self.maximized.replace(maximized);
// We only maximize if we're not in fullscreen.
if self.fullscreen.borrow().is_some() { return; }
let window = self.window.clone();
unsafe {
// And because ShowWindow will resize the window
// We call it in the main thread
// `ShowWindow` resizes the window, so it must be called from the main thread.
self.events_loop_proxy.execute_in_thread(move |_| {
winuser::ShowWindow(
window.0,
@ -469,15 +495,15 @@ impl Window {
unsafe fn set_fullscreen_style(&self) -> (LONG, LONG) {
let mut window_state = self.window_state.lock().unwrap();
if window_state.attributes.fullscreen.is_none() || window_state.saved_window_info.is_none() {
let mut rect: RECT = mem::zeroed();
winuser::GetWindowRect(self.window.0, &mut rect);
if self.fullscreen.borrow().is_none() || window_state.saved_window_info.is_none() {
let rect = util::get_window_rect(self.window.0).expect("`GetWindowRect` failed");
let dpi_factor = Some(self.get_hidpi_factor());
window_state.saved_window_info = Some(events_loop::SavedWindowInfo {
style: winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE),
ex_style: winuser::GetWindowLongW(self.window.0, winuser::GWL_EXSTYLE),
rect,
is_fullscreen: true,
dpi_factor,
});
}
@ -485,15 +511,14 @@ impl Window {
let mut placement: winuser::WINDOWPLACEMENT = mem::zeroed();
placement.length = mem::size_of::<winuser::WINDOWPLACEMENT>() as u32;
winuser::GetWindowPlacement(self.window.0, &mut placement);
window_state.attributes.maximized =
placement.showCmd == (winuser::SW_SHOWMAXIMIZED as u32);
self.maximized.replace(placement.showCmd == (winuser::SW_SHOWMAXIMIZED as u32));
let saved_window_info = window_state.saved_window_info.as_ref().unwrap();
(saved_window_info.style, saved_window_info.ex_style)
}
unsafe fn restore_saved_window(&self) {
let window_state = self.window_state.lock().unwrap();
let mut window_state = self.window_state.lock().unwrap();
// 'saved_window_info' can be None if the window has never been
// in fullscreen mode before this method gets called.
@ -504,18 +529,21 @@ impl Window {
// Reset original window style and size. The multiple window size/moves
// here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be
// repainted. Better-looking methods welcome.
{
let saved_window_info = window_state.saved_window_info.as_mut().unwrap();
saved_window_info.is_fullscreen = false;
}
let saved_window_info = window_state.saved_window_info.as_ref().unwrap();
let rect = saved_window_info.rect.clone();
let window = self.window.clone();
let (mut style, ex_style) = (saved_window_info.style, saved_window_info.ex_style);
let maximized = window_state.attributes.maximized;
let resizable = window_state.attributes.resizable;
let maximized = self.maximized.get();
let resizable = self.resizable.get();
// On restore, resize to the previous saved rect size.
// And because SetWindowPos will resize the window
// We call it in the main thread
// We're restoring the window to its size and position from before being fullscreened.
// `ShowWindow` resizes the window, so it must be called from the main thread.
self.events_loop_proxy.execute_in_thread(move |_| {
if resizable {
style |= winuser::WS_SIZEBOX as LONG;
@ -532,11 +560,13 @@ impl Window {
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOACTIVATE
| winuser::SWP_FRAMECHANGED,
winuser::SWP_ASYNCWINDOWPOS
| winuser::SWP_NOZORDER
| winuser::SWP_NOACTIVATE
| winuser::SWP_FRAMECHANGED,
);
// if it was set to maximized when it were fullscreened, we restore it as well
// We apply any requested changes to maximization state that occurred while we were in fullscreen.
winuser::ShowWindow(
window.0,
if maximized {
@ -555,8 +585,8 @@ impl Window {
unsafe {
match &monitor {
&Some(RootMonitorId { ref inner }) => {
let pos = inner.get_position();
let dim = inner.get_dimensions();
let (x, y): (i32, i32) = inner.get_position().into();
let (width, height): (u32, u32) = inner.get_dimensions().into();
let window = self.window.clone();
let (style, ex_style) = self.set_fullscreen_style();
@ -582,10 +612,10 @@ impl Window {
winuser::SetWindowPos(
window.0,
ptr::null_mut(),
pos.0,
pos.1,
dim.0 as i32,
dim.1 as i32,
x as c_int,
y as c_int,
width as c_int,
height as c_int,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER
| winuser::SWP_NOACTIVATE
| winuser::SWP_FRAMECHANGED,
@ -600,122 +630,119 @@ impl Window {
}
}
let mut window_state = self.window_state.lock().unwrap();
window_state.attributes.fullscreen = monitor;
self.fullscreen.replace(monitor);
}
#[inline]
pub fn set_decorations(&self, decorations: bool) {
if let Ok(mut window_state) = self.window_state.lock() {
if window_state.attributes.decorations == decorations {
return;
}
if self.decorations.get() == decorations {
return;
}
let style_flags = (winuser::WS_CAPTION | winuser::WS_THICKFRAME) as LONG;
let ex_style_flags = (winuser::WS_EX_WINDOWEDGE) as LONG;
let style_flags = (winuser::WS_CAPTION | winuser::WS_THICKFRAME) as LONG;
let ex_style_flags = (winuser::WS_EX_WINDOWEDGE) as LONG;
// if we are in fullscreen mode, we only change the saved window info
if window_state.attributes.fullscreen.is_some() {
{
let mut saved = window_state.saved_window_info.as_mut().unwrap();
// if we are in fullscreen mode, we only change the saved window info
if self.fullscreen.borrow().is_some() {
{
let mut window_state = self.window_state.lock().unwrap();
let saved = window_state.saved_window_info.as_mut().unwrap();
unsafe {
unjust_window_rect(&mut saved.rect, saved.style as _, saved.ex_style as _);
}
if decorations {
saved.style = saved.style | style_flags;
saved.ex_style = saved.ex_style | ex_style_flags;
} else {
saved.style = saved.style & !style_flags;
saved.ex_style = saved.ex_style & !ex_style_flags;
}
unsafe {
winuser::AdjustWindowRectEx(
&mut saved.rect,
saved.style as _,
0,
saved.ex_style as _,
);
}
unsafe {
unjust_window_rect(&mut saved.rect, saved.style as _, saved.ex_style as _);
}
window_state.attributes.decorations = decorations;
return;
}
unsafe {
let mut rect: RECT = mem::zeroed();
winuser::GetWindowRect(self.window.0, &mut rect);
let mut style = winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE);
let mut ex_style = winuser::GetWindowLongW(self.window.0, winuser::GWL_EXSTYLE);
unjust_window_rect(&mut rect, style as _, ex_style as _);
if decorations {
style = style | style_flags;
ex_style = ex_style | ex_style_flags;
saved.style = saved.style | style_flags;
saved.ex_style = saved.ex_style | ex_style_flags;
} else {
style = style & !style_flags;
ex_style = ex_style & !ex_style_flags;
saved.style = saved.style & !style_flags;
saved.ex_style = saved.ex_style & !ex_style_flags;
}
let window = self.window.clone();
self.events_loop_proxy.execute_in_thread(move |_| {
winuser::SetWindowLongW(window.0, winuser::GWL_STYLE, style);
winuser::SetWindowLongW(window.0, winuser::GWL_EXSTYLE, ex_style);
winuser::AdjustWindowRectEx(&mut rect, style as _, 0, ex_style as _);
winuser::SetWindowPos(
window.0,
ptr::null_mut(),
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER
| winuser::SWP_NOACTIVATE
| winuser::SWP_FRAMECHANGED,
unsafe {
winuser::AdjustWindowRectEx(
&mut saved.rect,
saved.style as _,
0,
saved.ex_style as _,
);
});
}
}
window_state.attributes.decorations = decorations;
self.decorations.replace(decorations);
return;
}
unsafe {
let mut rect: RECT = mem::zeroed();
winuser::GetWindowRect(self.window.0, &mut rect);
let mut style = winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE);
let mut ex_style = winuser::GetWindowLongW(self.window.0, winuser::GWL_EXSTYLE);
unjust_window_rect(&mut rect, style as _, ex_style as _);
if decorations {
style = style | style_flags;
ex_style = ex_style | ex_style_flags;
} else {
style = style & !style_flags;
ex_style = ex_style & !ex_style_flags;
}
let window = self.window.clone();
self.events_loop_proxy.execute_in_thread(move |_| {
winuser::SetWindowLongW(window.0, winuser::GWL_STYLE, style);
winuser::SetWindowLongW(window.0, winuser::GWL_EXSTYLE, ex_style);
winuser::AdjustWindowRectEx(&mut rect, style as _, 0, ex_style as _);
winuser::SetWindowPos(
window.0,
ptr::null_mut(),
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
winuser::SWP_ASYNCWINDOWPOS
| winuser::SWP_NOZORDER
| winuser::SWP_NOACTIVATE
| winuser::SWP_FRAMECHANGED,
);
});
}
self.decorations.replace(decorations);
}
#[inline]
pub fn set_always_on_top(&self, always_on_top: bool) {
if let Ok(mut window_state) = self.window_state.lock() {
if window_state.attributes.always_on_top == always_on_top {
return;
}
let window = self.window.clone();
self.events_loop_proxy.execute_in_thread(move |_| {
let insert_after = if always_on_top {
winuser::HWND_TOPMOST
} else {
winuser::HWND_NOTOPMOST
};
unsafe {
winuser::SetWindowPos(
window.0,
insert_after,
0,
0,
0,
0,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOMOVE | winuser::SWP_NOSIZE,
);
winuser::UpdateWindow(window.0);
}
});
window_state.attributes.always_on_top = always_on_top;
if self.always_on_top.get() == always_on_top {
return;
}
let window = self.window.clone();
self.events_loop_proxy.execute_in_thread(move |_| {
let insert_after = if always_on_top {
winuser::HWND_TOPMOST
} else {
winuser::HWND_NOTOPMOST
};
unsafe {
winuser::SetWindowPos(
window.0,
insert_after,
0,
0,
0,
0,
winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOMOVE | winuser::SWP_NOSIZE,
);
winuser::UpdateWindow(window.0);
}
});
self.always_on_top.replace(always_on_top);
}
#[inline]
@ -752,7 +779,7 @@ impl Window {
}
#[inline]
pub fn set_ime_spot(&self, _x: i32, _y: i32) {
pub fn set_ime_spot(&self, _logical_spot: LogicalPosition) {
unimplemented!();
}
}
@ -779,27 +806,26 @@ pub struct WindowWrapper(HWND, HDC);
// https://github.com/retep998/winapi-rs/issues/396
unsafe impl Send for WindowWrapper {}
pub unsafe fn adjust_size(
(x, y): (u32, u32), style: DWORD, ex_style: DWORD,
) -> (LONG, LONG) {
let mut rect = RECT { left: 0, right: x as LONG, top: 0, bottom: y as LONG };
pub unsafe fn adjust_size(physical_size: PhysicalSize, style: DWORD, ex_style: DWORD) -> (LONG, LONG) {
let (width, height): (u32, u32) = physical_size.into();
let mut rect = RECT { left: 0, right: width as LONG, top: 0, bottom: height as LONG };
winuser::AdjustWindowRectEx(&mut rect, style, 0, ex_style);
(rect.right - rect.left, rect.bottom - rect.top)
}
unsafe fn init(
mut window: WindowAttributes,
mut attributes: WindowAttributes,
mut pl_attribs: PlatformSpecificWindowBuilderAttributes,
inserter: events_loop::Inserter,
events_loop_proxy: events_loop::EventsLoopProxy,
) -> Result<Window, CreationError> {
let title = OsStr::new(&window.title)
let title = OsStr::new(&attributes.title)
.encode_wide()
.chain(Some(0).into_iter())
.collect::<Vec<_>>();
let window_icon = {
let icon = window.window_icon
let icon = attributes.window_icon
.take()
.map(WinIcon::from_icon);
if icon.is_some() {
@ -826,14 +852,19 @@ unsafe fn init(
// registering the window class
let class_name = register_window_class(&window_icon, &taskbar_icon);
let (width, height) = attributes.dimensions
.map(Into::into)
.unwrap_or((1024, 768));
// building a RECT object with coordinates
let mut rect = RECT {
left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as LONG,
top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as LONG,
left: 0,
right: width as LONG,
top: 0,
bottom: height as LONG,
};
// computing the style and extended style of the window
let (mut ex_style, style) = if !window.decorations {
let (mut ex_style, style) = if !attributes.decorations {
(winuser::WS_EX_APPWINDOW,
//winapi::WS_POPUP is incompatible with winapi::WS_CHILD
if pl_attribs.parent.is_some() {
@ -848,7 +879,7 @@ unsafe fn init(
winuser::WS_OVERLAPPEDWINDOW | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN)
};
if window.always_on_top {
if attributes.always_on_top {
ex_style |= winuser::WS_EX_TOPMOST;
}
@ -857,14 +888,15 @@ unsafe fn init(
// creating the real window this time, by using the functions in `extra_functions`
let real_window = {
let (width, height) = if window.dimensions.is_some() {
let min_dimensions = window.min_dimensions
.map(|d| adjust_size(d, style, ex_style))
let (adjusted_width, adjusted_height) = if attributes.dimensions.is_some() {
let min_dimensions = attributes.min_dimensions
.map(|logical_size| PhysicalSize::from_logical(logical_size, 1.0))
.map(|physical_size| adjust_size(physical_size, style, ex_style))
.unwrap_or((0, 0));
let max_dimensions = window.max_dimensions
.map(|d| adjust_size(d, style, ex_style))
.unwrap_or((raw::c_int::max_value(), raw::c_int::max_value()));
let max_dimensions = attributes.max_dimensions
.map(|logical_size| PhysicalSize::from_logical(logical_size, 1.0))
.map(|physical_size| adjust_size(physical_size, style, ex_style))
.unwrap_or((c_int::max_value(), c_int::max_value()));
(
Some((rect.right - rect.left).min(max_dimensions.0).max(min_dimensions.0)),
Some((rect.bottom - rect.top).min(max_dimensions.1).max(min_dimensions.1))
@ -873,13 +905,13 @@ unsafe fn init(
(None, None)
};
let mut style = if !window.visible {
let mut style = if !attributes.visible {
style
} else {
style | winuser::WS_VISIBLE
};
if !window.resizable {
if !attributes.resizable {
style &= !winuser::WS_SIZEBOX;
}
@ -892,10 +924,13 @@ unsafe fn init(
title.as_ptr() as LPCWSTR,
style | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN,
winuser::CW_USEDEFAULT, winuser::CW_USEDEFAULT,
width.unwrap_or(winuser::CW_USEDEFAULT), height.unwrap_or(winuser::CW_USEDEFAULT),
adjusted_width.unwrap_or(winuser::CW_USEDEFAULT),
adjusted_height.unwrap_or(winuser::CW_USEDEFAULT),
pl_attribs.parent.unwrap_or(ptr::null_mut()),
ptr::null_mut(), libloaderapi::GetModuleHandleW(ptr::null()),
ptr::null_mut());
ptr::null_mut(),
libloaderapi::GetModuleHandleW(ptr::null()),
ptr::null_mut(),
);
if handle.is_null() {
return Err(CreationError::OsError(format!("CreateWindowEx function failed: {}",
@ -922,21 +957,42 @@ unsafe fn init(
}
}
let (transparent, maximized, fullscreen) = (
window.transparent.clone(), window.maximized.clone(), window.fullscreen.clone()
);
let dpi = get_window_dpi(real_window.0, real_window.1);
let dpi_factor = dpi_to_scale_factor(dpi);
if dpi != BASE_DPI {
let mut packed_dimensions = 0;
// MAKELPARAM isn't provided by winapi yet.
let ptr = &mut packed_dimensions as *mut LPARAM as *mut WORD;
*ptr.offset(0) = width as WORD;
*ptr.offset(1) = height as WORD;
winuser::PostMessageW(
real_window.0,
*INITIAL_DPI_MSG_ID,
dpi as WPARAM,
packed_dimensions,
);
}
// Creating a mutex to track the current window state
let window_state = Arc::new(Mutex::new(events_loop::WindowState {
cursor: Cursor(winuser::IDC_ARROW), // use arrow by default
cursor_state: CursorState::Normal,
attributes: window,
mouse_in_window: false,
saved_window_info: None,
}));
let window_state = {
let max_size = attributes.max_dimensions
.map(|logical_size| PhysicalSize::from_logical(logical_size, dpi_factor));
let min_size = attributes.min_dimensions
.map(|logical_size| PhysicalSize::from_logical(logical_size, dpi_factor));
let mut window_state = events_loop::WindowState {
cursor: Cursor(winuser::IDC_ARROW), // use arrow by default
cursor_state: CursorState::Normal,
max_size,
min_size,
mouse_in_window: false,
saved_window_info: None,
dpi_factor,
};
// Creating a mutex to track the current window state
Arc::new(Mutex::new(window_state))
};
// making the window transparent
if transparent {
if attributes.transparent {
let bb = dwmapi::DWM_BLURBEHIND {
dwFlags: 0x1, // FIXME: DWM_BB_ENABLE;
fEnable: 1,
@ -950,14 +1006,19 @@ unsafe fn init(
let win = Window {
window: real_window,
window_state: window_state,
decorations: Cell::new(attributes.decorations),
maximized: Cell::new(attributes.maximized.clone()),
resizable: Cell::new(attributes.resizable.clone()),
fullscreen: RefCell::new(attributes.fullscreen.clone()),
always_on_top: Cell::new(attributes.always_on_top),
window_icon: Cell::new(window_icon),
taskbar_icon: Cell::new(taskbar_icon),
events_loop_proxy,
};
win.set_maximized(maximized);
if let Some(_) = fullscreen {
win.set_fullscreen(fullscreen);
win.set_maximized(attributes.maximized);
if let Some(_) = attributes.fullscreen {
win.set_fullscreen(attributes.fullscreen);
force_window_active(win.window.0);
}