Update winapi to 0.3 (#346)

* Update to `winapi` 0.3

* Update max size comment

* Fix missing import

* Shorten import path

* Update to stable winapi version
This commit is contained in:
Gabriel Majeri 2017-12-24 15:46:47 +02:00 committed by Pierre Krieger
parent 463f316cb8
commit d92666c188
8 changed files with 379 additions and 381 deletions

View file

@ -26,12 +26,19 @@ cocoa = "0.11"
core-foundation = "0.4" core-foundation = "0.4"
core-graphics = "0.10" core-graphics = "0.10"
[target.'cfg(target_os = "windows")'.dependencies] [target.'cfg(target_os = "windows")'.dependencies.winapi]
winapi = "0.2" version = "0.3"
shell32-sys = "0.1" features = [
user32-sys = "~0.1.2" "winnt",
kernel32-sys = "0.2" "winuser",
dwmapi-sys = "0.1" "wingdi",
"shellapi",
"dwmapi",
"processthreadsapi",
"libloaderapi",
"windowsx",
"hidusage",
]
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))'.dependencies] [target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
wayland-client = { version = "0.12.0", features = ["dlopen"] } wayland-client = { version = "0.12.0", features = ["dlopen"] }

View file

@ -88,14 +88,6 @@ extern crate libc;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
extern crate winapi; extern crate winapi;
#[cfg(target_os = "windows")]
extern crate kernel32;
#[cfg(target_os = "windows")]
extern crate shell32;
#[cfg(target_os = "windows")]
extern crate user32;
#[cfg(target_os = "windows")]
extern crate dwmapi;
#[cfg(any(target_os = "macos", target_os = "ios"))] #[cfg(any(target_os = "macos", target_os = "ios"))]
#[macro_use] #[macro_use]
extern crate objc; extern crate objc;

View file

@ -5,7 +5,7 @@ use libc;
use MonitorId; use MonitorId;
use Window; use Window;
use WindowBuilder; use WindowBuilder;
use winapi; use winapi::shared::windef::HWND;
/// Additional methods on `Window` that are specific to Windows. /// Additional methods on `Window` that are specific to Windows.
pub trait WindowExt { pub trait WindowExt {
@ -24,13 +24,13 @@ impl WindowExt for Window {
/// Additional methods on `WindowBuilder` that are specific to Windows. /// Additional methods on `WindowBuilder` that are specific to Windows.
pub trait WindowBuilderExt { pub trait WindowBuilderExt {
fn with_parent_window(self, parent: winapi::HWND) -> WindowBuilder; fn with_parent_window(self, parent: HWND) -> WindowBuilder;
} }
impl WindowBuilderExt for WindowBuilder { impl WindowBuilderExt for WindowBuilder {
/// Sets a parent to the window to be created. /// Sets a parent to the window to be created.
#[inline] #[inline]
fn with_parent_window(mut self, parent: winapi::HWND) -> WindowBuilder { fn with_parent_window(mut self, parent: HWND) -> WindowBuilder {
self.platform_specific.parent = Some(parent); self.platform_specific.parent = Some(parent);
self self
} }

View file

@ -1,7 +1,9 @@
use events::VirtualKeyCode; use events::VirtualKeyCode;
use events::ModifiersState; use events::ModifiersState;
use winapi;
use user32; use winapi::shared::minwindef::{WPARAM, LPARAM};
use winapi::um::winuser;
use ScanCode; use ScanCode;
use std::char; use std::char;
@ -11,80 +13,80 @@ const MAPVK_VSC_TO_VK_EX: u32 = 3;
pub fn get_key_mods() -> ModifiersState { pub fn get_key_mods() -> ModifiersState {
let mut mods = ModifiersState::default(); let mut mods = ModifiersState::default();
unsafe { unsafe {
if user32::GetKeyState(winapi::VK_SHIFT) & (1 << 15) == (1 << 15) { if winuser::GetKeyState(winuser::VK_SHIFT) & (1 << 15) == (1 << 15) {
mods.shift = true; mods.shift = true;
} }
if user32::GetKeyState(winapi::VK_CONTROL) & (1 << 15) == (1 << 15) { if winuser::GetKeyState(winuser::VK_CONTROL) & (1 << 15) == (1 << 15) {
mods.ctrl = true; mods.ctrl = true;
} }
if user32::GetKeyState(winapi::VK_MENU) & (1 << 15) == (1 << 15) { if winuser::GetKeyState(winuser::VK_MENU) & (1 << 15) == (1 << 15) {
mods.alt = true; mods.alt = true;
} }
if (user32::GetKeyState(winapi::VK_LWIN) | user32::GetKeyState(winapi::VK_RWIN)) & (1 << 15) == (1 << 15) { if (winuser::GetKeyState(winuser::VK_LWIN) | winuser::GetKeyState(winuser::VK_RWIN)) & (1 << 15) == (1 << 15) {
mods.logo = true; mods.logo = true;
} }
} }
mods mods
} }
pub fn vkeycode_to_element(wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> (ScanCode, Option<VirtualKeyCode>) { pub fn vkeycode_to_element(wparam: WPARAM, lparam: LPARAM) -> (ScanCode, Option<VirtualKeyCode>) {
let scancode = ((lparam >> 16) & 0xff) as u32; let scancode = ((lparam >> 16) & 0xff) as u32;
let extended = (lparam & 0x01000000) != 0; let extended = (lparam & 0x01000000) != 0;
let vk = match wparam as i32 { let vk = match wparam as i32 {
winapi::VK_SHIFT => unsafe { user32::MapVirtualKeyA(scancode, MAPVK_VSC_TO_VK_EX) as i32 }, winuser::VK_SHIFT => unsafe { winuser::MapVirtualKeyA(scancode, MAPVK_VSC_TO_VK_EX) as i32 },
winapi::VK_CONTROL => if extended { winapi::VK_RCONTROL } else { winapi::VK_LCONTROL }, winuser::VK_CONTROL => if extended { winuser::VK_RCONTROL } else { winuser::VK_LCONTROL },
winapi::VK_MENU => if extended { winapi::VK_RMENU } else { winapi::VK_LMENU }, winuser::VK_MENU => if extended { winuser::VK_RMENU } else { winuser::VK_LMENU },
other => other other => other
}; };
// VK_* codes are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx // VK_* codes are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
(scancode, match vk { (scancode, match vk {
//winapi::VK_LBUTTON => Some(VirtualKeyCode::Lbutton), //winuser::VK_LBUTTON => Some(VirtualKeyCode::Lbutton),
//winapi::VK_RBUTTON => Some(VirtualKeyCode::Rbutton), //winuser::VK_RBUTTON => Some(VirtualKeyCode::Rbutton),
//winapi::VK_CANCEL => Some(VirtualKeyCode::Cancel), //winuser::VK_CANCEL => Some(VirtualKeyCode::Cancel),
//winapi::VK_MBUTTON => Some(VirtualKeyCode::Mbutton), //winuser::VK_MBUTTON => Some(VirtualKeyCode::Mbutton),
//winapi::VK_XBUTTON1 => Some(VirtualKeyCode::Xbutton1), //winuser::VK_XBUTTON1 => Some(VirtualKeyCode::Xbutton1),
//winapi::VK_XBUTTON2 => Some(VirtualKeyCode::Xbutton2), //winuser::VK_XBUTTON2 => Some(VirtualKeyCode::Xbutton2),
winapi::VK_BACK => Some(VirtualKeyCode::Back), winuser::VK_BACK => Some(VirtualKeyCode::Back),
winapi::VK_TAB => Some(VirtualKeyCode::Tab), winuser::VK_TAB => Some(VirtualKeyCode::Tab),
//winapi::VK_CLEAR => Some(VirtualKeyCode::Clear), //winuser::VK_CLEAR => Some(VirtualKeyCode::Clear),
winapi::VK_RETURN => Some(VirtualKeyCode::Return), winuser::VK_RETURN => Some(VirtualKeyCode::Return),
winapi::VK_LSHIFT => Some(VirtualKeyCode::LShift), winuser::VK_LSHIFT => Some(VirtualKeyCode::LShift),
winapi::VK_RSHIFT => Some(VirtualKeyCode::RShift), winuser::VK_RSHIFT => Some(VirtualKeyCode::RShift),
winapi::VK_LCONTROL => Some(VirtualKeyCode::LControl), winuser::VK_LCONTROL => Some(VirtualKeyCode::LControl),
winapi::VK_RCONTROL => Some(VirtualKeyCode::RControl), winuser::VK_RCONTROL => Some(VirtualKeyCode::RControl),
winapi::VK_LMENU => Some(VirtualKeyCode::LMenu), winuser::VK_LMENU => Some(VirtualKeyCode::LMenu),
winapi::VK_RMENU => Some(VirtualKeyCode::RMenu), winuser::VK_RMENU => Some(VirtualKeyCode::RMenu),
winapi::VK_PAUSE => Some(VirtualKeyCode::Pause), winuser::VK_PAUSE => Some(VirtualKeyCode::Pause),
winapi::VK_CAPITAL => Some(VirtualKeyCode::Capital), winuser::VK_CAPITAL => Some(VirtualKeyCode::Capital),
winapi::VK_KANA => Some(VirtualKeyCode::Kana), winuser::VK_KANA => Some(VirtualKeyCode::Kana),
//winapi::VK_HANGUEL => Some(VirtualKeyCode::Hanguel), //winuser::VK_HANGUEL => Some(VirtualKeyCode::Hanguel),
//winapi::VK_HANGUL => Some(VirtualKeyCode::Hangul), //winuser::VK_HANGUL => Some(VirtualKeyCode::Hangul),
//winapi::VK_JUNJA => Some(VirtualKeyCode::Junja), //winuser::VK_JUNJA => Some(VirtualKeyCode::Junja),
//winapi::VK_FINAL => Some(VirtualKeyCode::Final), //winuser::VK_FINAL => Some(VirtualKeyCode::Final),
//winapi::VK_HANJA => Some(VirtualKeyCode::Hanja), //winuser::VK_HANJA => Some(VirtualKeyCode::Hanja),
winapi::VK_KANJI => Some(VirtualKeyCode::Kanji), winuser::VK_KANJI => Some(VirtualKeyCode::Kanji),
winapi::VK_ESCAPE => Some(VirtualKeyCode::Escape), winuser::VK_ESCAPE => Some(VirtualKeyCode::Escape),
winapi::VK_CONVERT => Some(VirtualKeyCode::Convert), winuser::VK_CONVERT => Some(VirtualKeyCode::Convert),
winapi::VK_NONCONVERT => Some(VirtualKeyCode::NoConvert), winuser::VK_NONCONVERT => Some(VirtualKeyCode::NoConvert),
//winapi::VK_ACCEPT => Some(VirtualKeyCode::Accept), //winuser::VK_ACCEPT => Some(VirtualKeyCode::Accept),
//winapi::VK_MODECHANGE => Some(VirtualKeyCode::Modechange), //winuser::VK_MODECHANGE => Some(VirtualKeyCode::Modechange),
winapi::VK_SPACE => Some(VirtualKeyCode::Space), winuser::VK_SPACE => Some(VirtualKeyCode::Space),
winapi::VK_PRIOR => Some(VirtualKeyCode::PageUp), winuser::VK_PRIOR => Some(VirtualKeyCode::PageUp),
winapi::VK_NEXT => Some(VirtualKeyCode::PageDown), winuser::VK_NEXT => Some(VirtualKeyCode::PageDown),
winapi::VK_END => Some(VirtualKeyCode::End), winuser::VK_END => Some(VirtualKeyCode::End),
winapi::VK_HOME => Some(VirtualKeyCode::Home), winuser::VK_HOME => Some(VirtualKeyCode::Home),
winapi::VK_LEFT => Some(VirtualKeyCode::Left), winuser::VK_LEFT => Some(VirtualKeyCode::Left),
winapi::VK_UP => Some(VirtualKeyCode::Up), winuser::VK_UP => Some(VirtualKeyCode::Up),
winapi::VK_RIGHT => Some(VirtualKeyCode::Right), winuser::VK_RIGHT => Some(VirtualKeyCode::Right),
winapi::VK_DOWN => Some(VirtualKeyCode::Down), winuser::VK_DOWN => Some(VirtualKeyCode::Down),
//winapi::VK_SELECT => Some(VirtualKeyCode::Select), //winuser::VK_SELECT => Some(VirtualKeyCode::Select),
//winapi::VK_PRINT => Some(VirtualKeyCode::Print), //winuser::VK_PRINT => Some(VirtualKeyCode::Print),
//winapi::VK_EXECUTE => Some(VirtualKeyCode::Execute), //winuser::VK_EXECUTE => Some(VirtualKeyCode::Execute),
winapi::VK_SNAPSHOT => Some(VirtualKeyCode::Snapshot), winuser::VK_SNAPSHOT => Some(VirtualKeyCode::Snapshot),
winapi::VK_INSERT => Some(VirtualKeyCode::Insert), winuser::VK_INSERT => Some(VirtualKeyCode::Insert),
winapi::VK_DELETE => Some(VirtualKeyCode::Delete), winuser::VK_DELETE => Some(VirtualKeyCode::Delete),
//winapi::VK_HELP => Some(VirtualKeyCode::Help), //winuser::VK_HELP => Some(VirtualKeyCode::Help),
0x30 => Some(VirtualKeyCode::Key0), 0x30 => Some(VirtualKeyCode::Key0),
0x31 => Some(VirtualKeyCode::Key1), 0x31 => Some(VirtualKeyCode::Key1),
0x32 => Some(VirtualKeyCode::Key2), 0x32 => Some(VirtualKeyCode::Key2),
@ -121,94 +123,94 @@ pub fn vkeycode_to_element(wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> (S
0x58 => Some(VirtualKeyCode::X), 0x58 => Some(VirtualKeyCode::X),
0x59 => Some(VirtualKeyCode::Y), 0x59 => Some(VirtualKeyCode::Y),
0x5A => Some(VirtualKeyCode::Z), 0x5A => Some(VirtualKeyCode::Z),
//winapi::VK_LWIN => Some(VirtualKeyCode::Lwin), //winuser::VK_LWIN => Some(VirtualKeyCode::Lwin),
//winapi::VK_RWIN => Some(VirtualKeyCode::Rwin), //winuser::VK_RWIN => Some(VirtualKeyCode::Rwin),
winapi::VK_APPS => Some(VirtualKeyCode::Apps), winuser::VK_APPS => Some(VirtualKeyCode::Apps),
winapi::VK_SLEEP => Some(VirtualKeyCode::Sleep), winuser::VK_SLEEP => Some(VirtualKeyCode::Sleep),
winapi::VK_NUMPAD0 => Some(VirtualKeyCode::Numpad0), winuser::VK_NUMPAD0 => Some(VirtualKeyCode::Numpad0),
winapi::VK_NUMPAD1 => Some(VirtualKeyCode::Numpad1), winuser::VK_NUMPAD1 => Some(VirtualKeyCode::Numpad1),
winapi::VK_NUMPAD2 => Some(VirtualKeyCode::Numpad2), winuser::VK_NUMPAD2 => Some(VirtualKeyCode::Numpad2),
winapi::VK_NUMPAD3 => Some(VirtualKeyCode::Numpad3), winuser::VK_NUMPAD3 => Some(VirtualKeyCode::Numpad3),
winapi::VK_NUMPAD4 => Some(VirtualKeyCode::Numpad4), winuser::VK_NUMPAD4 => Some(VirtualKeyCode::Numpad4),
winapi::VK_NUMPAD5 => Some(VirtualKeyCode::Numpad5), winuser::VK_NUMPAD5 => Some(VirtualKeyCode::Numpad5),
winapi::VK_NUMPAD6 => Some(VirtualKeyCode::Numpad6), winuser::VK_NUMPAD6 => Some(VirtualKeyCode::Numpad6),
winapi::VK_NUMPAD7 => Some(VirtualKeyCode::Numpad7), winuser::VK_NUMPAD7 => Some(VirtualKeyCode::Numpad7),
winapi::VK_NUMPAD8 => Some(VirtualKeyCode::Numpad8), winuser::VK_NUMPAD8 => Some(VirtualKeyCode::Numpad8),
winapi::VK_NUMPAD9 => Some(VirtualKeyCode::Numpad9), winuser::VK_NUMPAD9 => Some(VirtualKeyCode::Numpad9),
winapi::VK_MULTIPLY => Some(VirtualKeyCode::Multiply), winuser::VK_MULTIPLY => Some(VirtualKeyCode::Multiply),
winapi::VK_ADD => Some(VirtualKeyCode::Add), winuser::VK_ADD => Some(VirtualKeyCode::Add),
//winapi::VK_SEPARATOR => Some(VirtualKeyCode::Separator), //winuser::VK_SEPARATOR => Some(VirtualKeyCode::Separator),
winapi::VK_SUBTRACT => Some(VirtualKeyCode::Subtract), winuser::VK_SUBTRACT => Some(VirtualKeyCode::Subtract),
winapi::VK_DECIMAL => Some(VirtualKeyCode::Decimal), winuser::VK_DECIMAL => Some(VirtualKeyCode::Decimal),
winapi::VK_DIVIDE => Some(VirtualKeyCode::Divide), winuser::VK_DIVIDE => Some(VirtualKeyCode::Divide),
winapi::VK_F1 => Some(VirtualKeyCode::F1), winuser::VK_F1 => Some(VirtualKeyCode::F1),
winapi::VK_F2 => Some(VirtualKeyCode::F2), winuser::VK_F2 => Some(VirtualKeyCode::F2),
winapi::VK_F3 => Some(VirtualKeyCode::F3), winuser::VK_F3 => Some(VirtualKeyCode::F3),
winapi::VK_F4 => Some(VirtualKeyCode::F4), winuser::VK_F4 => Some(VirtualKeyCode::F4),
winapi::VK_F5 => Some(VirtualKeyCode::F5), winuser::VK_F5 => Some(VirtualKeyCode::F5),
winapi::VK_F6 => Some(VirtualKeyCode::F6), winuser::VK_F6 => Some(VirtualKeyCode::F6),
winapi::VK_F7 => Some(VirtualKeyCode::F7), winuser::VK_F7 => Some(VirtualKeyCode::F7),
winapi::VK_F8 => Some(VirtualKeyCode::F8), winuser::VK_F8 => Some(VirtualKeyCode::F8),
winapi::VK_F9 => Some(VirtualKeyCode::F9), winuser::VK_F9 => Some(VirtualKeyCode::F9),
winapi::VK_F10 => Some(VirtualKeyCode::F10), winuser::VK_F10 => Some(VirtualKeyCode::F10),
winapi::VK_F11 => Some(VirtualKeyCode::F11), winuser::VK_F11 => Some(VirtualKeyCode::F11),
winapi::VK_F12 => Some(VirtualKeyCode::F12), winuser::VK_F12 => Some(VirtualKeyCode::F12),
winapi::VK_F13 => Some(VirtualKeyCode::F13), winuser::VK_F13 => Some(VirtualKeyCode::F13),
winapi::VK_F14 => Some(VirtualKeyCode::F14), winuser::VK_F14 => Some(VirtualKeyCode::F14),
winapi::VK_F15 => Some(VirtualKeyCode::F15), winuser::VK_F15 => Some(VirtualKeyCode::F15),
/*winapi::VK_F16 => Some(VirtualKeyCode::F16), /*winuser::VK_F16 => Some(VirtualKeyCode::F16),
winapi::VK_F17 => Some(VirtualKeyCode::F17), winuser::VK_F17 => Some(VirtualKeyCode::F17),
winapi::VK_F18 => Some(VirtualKeyCode::F18), winuser::VK_F18 => Some(VirtualKeyCode::F18),
winapi::VK_F19 => Some(VirtualKeyCode::F19), winuser::VK_F19 => Some(VirtualKeyCode::F19),
winapi::VK_F20 => Some(VirtualKeyCode::F20), winuser::VK_F20 => Some(VirtualKeyCode::F20),
winapi::VK_F21 => Some(VirtualKeyCode::F21), winuser::VK_F21 => Some(VirtualKeyCode::F21),
winapi::VK_F22 => Some(VirtualKeyCode::F22), winuser::VK_F22 => Some(VirtualKeyCode::F22),
winapi::VK_F23 => Some(VirtualKeyCode::F23), winuser::VK_F23 => Some(VirtualKeyCode::F23),
winapi::VK_F24 => Some(VirtualKeyCode::F24),*/ winuser::VK_F24 => Some(VirtualKeyCode::F24),*/
winapi::VK_NUMLOCK => Some(VirtualKeyCode::Numlock), winuser::VK_NUMLOCK => Some(VirtualKeyCode::Numlock),
winapi::VK_SCROLL => Some(VirtualKeyCode::Scroll), winuser::VK_SCROLL => Some(VirtualKeyCode::Scroll),
winapi::VK_BROWSER_BACK => Some(VirtualKeyCode::NavigateBackward), winuser::VK_BROWSER_BACK => Some(VirtualKeyCode::NavigateBackward),
winapi::VK_BROWSER_FORWARD => Some(VirtualKeyCode::NavigateForward), winuser::VK_BROWSER_FORWARD => Some(VirtualKeyCode::NavigateForward),
winapi::VK_BROWSER_REFRESH => Some(VirtualKeyCode::WebRefresh), winuser::VK_BROWSER_REFRESH => Some(VirtualKeyCode::WebRefresh),
winapi::VK_BROWSER_STOP => Some(VirtualKeyCode::WebStop), winuser::VK_BROWSER_STOP => Some(VirtualKeyCode::WebStop),
winapi::VK_BROWSER_SEARCH => Some(VirtualKeyCode::WebSearch), winuser::VK_BROWSER_SEARCH => Some(VirtualKeyCode::WebSearch),
winapi::VK_BROWSER_FAVORITES => Some(VirtualKeyCode::WebFavorites), winuser::VK_BROWSER_FAVORITES => Some(VirtualKeyCode::WebFavorites),
winapi::VK_BROWSER_HOME => Some(VirtualKeyCode::WebHome), winuser::VK_BROWSER_HOME => Some(VirtualKeyCode::WebHome),
winapi::VK_VOLUME_MUTE => Some(VirtualKeyCode::Mute), winuser::VK_VOLUME_MUTE => Some(VirtualKeyCode::Mute),
winapi::VK_VOLUME_DOWN => Some(VirtualKeyCode::VolumeDown), winuser::VK_VOLUME_DOWN => Some(VirtualKeyCode::VolumeDown),
winapi::VK_VOLUME_UP => Some(VirtualKeyCode::VolumeUp), winuser::VK_VOLUME_UP => Some(VirtualKeyCode::VolumeUp),
winapi::VK_MEDIA_NEXT_TRACK => Some(VirtualKeyCode::NextTrack), winuser::VK_MEDIA_NEXT_TRACK => Some(VirtualKeyCode::NextTrack),
winapi::VK_MEDIA_PREV_TRACK => Some(VirtualKeyCode::PrevTrack), winuser::VK_MEDIA_PREV_TRACK => Some(VirtualKeyCode::PrevTrack),
winapi::VK_MEDIA_STOP => Some(VirtualKeyCode::MediaStop), winuser::VK_MEDIA_STOP => Some(VirtualKeyCode::MediaStop),
winapi::VK_MEDIA_PLAY_PAUSE => Some(VirtualKeyCode::PlayPause), winuser::VK_MEDIA_PLAY_PAUSE => Some(VirtualKeyCode::PlayPause),
winapi::VK_LAUNCH_MAIL => Some(VirtualKeyCode::Mail), winuser::VK_LAUNCH_MAIL => Some(VirtualKeyCode::Mail),
winapi::VK_LAUNCH_MEDIA_SELECT => Some(VirtualKeyCode::MediaSelect), winuser::VK_LAUNCH_MEDIA_SELECT => Some(VirtualKeyCode::MediaSelect),
/*winapi::VK_LAUNCH_APP1 => Some(VirtualKeyCode::Launch_app1), /*winuser::VK_LAUNCH_APP1 => Some(VirtualKeyCode::Launch_app1),
winapi::VK_LAUNCH_APP2 => Some(VirtualKeyCode::Launch_app2),*/ winuser::VK_LAUNCH_APP2 => Some(VirtualKeyCode::Launch_app2),*/
winapi::VK_OEM_PLUS => Some(VirtualKeyCode::Equals), winuser::VK_OEM_PLUS => Some(VirtualKeyCode::Equals),
winapi::VK_OEM_COMMA => Some(VirtualKeyCode::Comma), winuser::VK_OEM_COMMA => Some(VirtualKeyCode::Comma),
winapi::VK_OEM_MINUS => Some(VirtualKeyCode::Minus), winuser::VK_OEM_MINUS => Some(VirtualKeyCode::Minus),
winapi::VK_OEM_PERIOD => Some(VirtualKeyCode::Period), winuser::VK_OEM_PERIOD => Some(VirtualKeyCode::Period),
winapi::VK_OEM_1 => map_text_keys(vk), winuser::VK_OEM_1 => map_text_keys(vk),
winapi::VK_OEM_2 => map_text_keys(vk), winuser::VK_OEM_2 => map_text_keys(vk),
winapi::VK_OEM_3 => map_text_keys(vk), winuser::VK_OEM_3 => map_text_keys(vk),
winapi::VK_OEM_4 => map_text_keys(vk), winuser::VK_OEM_4 => map_text_keys(vk),
winapi::VK_OEM_5 => map_text_keys(vk), winuser::VK_OEM_5 => map_text_keys(vk),
winapi::VK_OEM_6 => map_text_keys(vk), winuser::VK_OEM_6 => map_text_keys(vk),
winapi::VK_OEM_7 => map_text_keys(vk), winuser::VK_OEM_7 => map_text_keys(vk),
/*winapi::VK_OEM_8 => Some(VirtualKeyCode::Oem_8), */ /*winuser::VK_OEM_8 => Some(VirtualKeyCode::Oem_8), */
winapi::VK_OEM_102 => Some(VirtualKeyCode::OEM102), winuser::VK_OEM_102 => Some(VirtualKeyCode::OEM102),
/*winapi::VK_PROCESSKEY => Some(VirtualKeyCode::Processkey), /*winuser::VK_PROCESSKEY => Some(VirtualKeyCode::Processkey),
winapi::VK_PACKET => Some(VirtualKeyCode::Packet), winuser::VK_PACKET => Some(VirtualKeyCode::Packet),
winapi::VK_ATTN => Some(VirtualKeyCode::Attn), winuser::VK_ATTN => Some(VirtualKeyCode::Attn),
winapi::VK_CRSEL => Some(VirtualKeyCode::Crsel), winuser::VK_CRSEL => Some(VirtualKeyCode::Crsel),
winapi::VK_EXSEL => Some(VirtualKeyCode::Exsel), winuser::VK_EXSEL => Some(VirtualKeyCode::Exsel),
winapi::VK_EREOF => Some(VirtualKeyCode::Ereof), winuser::VK_EREOF => Some(VirtualKeyCode::Ereof),
winapi::VK_PLAY => Some(VirtualKeyCode::Play), winuser::VK_PLAY => Some(VirtualKeyCode::Play),
winapi::VK_ZOOM => Some(VirtualKeyCode::Zoom), winuser::VK_ZOOM => Some(VirtualKeyCode::Zoom),
winapi::VK_NONAME => Some(VirtualKeyCode::Noname), winuser::VK_NONAME => Some(VirtualKeyCode::Noname),
winapi::VK_PA1 => Some(VirtualKeyCode::Pa1), winuser::VK_PA1 => Some(VirtualKeyCode::Pa1),
winapi::VK_OEM_CLEAR => Some(VirtualKeyCode::Oem_clear),*/ winuser::VK_OEM_CLEAR => Some(VirtualKeyCode::Oem_clear),*/
_ => None _ => None
}) })
} }
@ -216,7 +218,7 @@ pub fn vkeycode_to_element(wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> (S
// This is needed as windows doesn't properly distinguish // This is needed as windows doesn't properly distinguish
// some virtual key codes for different keyboard layouts // some virtual key codes for different keyboard layouts
fn map_text_keys(win_virtual_key: i32) -> Option<VirtualKeyCode> { fn map_text_keys(win_virtual_key: i32) -> Option<VirtualKeyCode> {
let char_key = unsafe { user32::MapVirtualKeyA(win_virtual_key as u32, MAPVK_VK_TO_CHAR) } & 0x7FFF; let char_key = unsafe { winuser::MapVirtualKeyA(win_virtual_key as u32, MAPVK_VK_TO_CHAR) } & 0x7FFF;
match char::from_u32(char_key) { match char::from_u32(char_key) {
Some(';') => Some(VirtualKeyCode::Semicolon), Some(';') => Some(VirtualKeyCode::Semicolon),
Some('/') => Some(VirtualKeyCode::Slash), Some('/') => Some(VirtualKeyCode::Slash),

View file

@ -26,10 +26,10 @@ use std::sync::Mutex;
use std::sync::Condvar; use std::sync::Condvar;
use std::thread; use std::thread;
use kernel32; use winapi::shared::minwindef::{LOWORD, HIWORD, DWORD, WPARAM, LPARAM, UINT, LRESULT, MAX_PATH};
use shell32; use winapi::shared::windef::{HWND, POINT};
use user32; use winapi::shared::windowsx;
use winapi; use winapi::um::{winuser, shellapi, processthreadsapi};
use platform::platform::event; use platform::platform::event;
use platform::platform::Cursor; use platform::platform::Cursor;
@ -65,7 +65,7 @@ pub struct Inserter(*mut u8);
impl Inserter { impl Inserter {
/// Inserts a window's state for the callback to use. The state is removed automatically if the /// Inserts a window's state for the callback to use. The state is removed automatically if the
/// callback receives a `WM_CLOSE` message for the window. /// callback receives a `WM_CLOSE` message for the window.
pub fn insert(&self, window: winapi::HWND, state: Arc<Mutex<WindowState>>) { pub fn insert(&self, window: HWND, state: Arc<Mutex<WindowState>>) {
CONTEXT_STASH.with(|context_stash| { CONTEXT_STASH.with(|context_stash| {
let mut context_stash = context_stash.borrow_mut(); let mut context_stash = context_stash.borrow_mut();
let was_in = context_stash.as_mut().unwrap().windows.insert(window, state); let was_in = context_stash.as_mut().unwrap().windows.insert(window, state);
@ -76,7 +76,7 @@ impl Inserter {
pub struct EventsLoop { pub struct EventsLoop {
// Id of the background thread from the Win32 API. // Id of the background thread from the Win32 API.
thread_id: winapi::DWORD, thread_id: DWORD,
// Receiver for the events. The sender is in the background thread. // Receiver for the events. The sender is in the background thread.
receiver: mpsc::Receiver<Event>, receiver: mpsc::Receiver<Event>,
// Variable that contains the block state of the win32 event loop thread during a WM_SIZE event. // Variable that contains the block state of the win32 event loop thread during a WM_SIZE event.
@ -110,7 +110,7 @@ impl EventsLoop {
// Calling `PostThreadMessageA` on a thread that does not have an events queue yet // Calling `PostThreadMessageA` on a thread that does not have an events queue yet
// will fail. In order to avoid this situation, we call `IsGuiThread` to initialize // will fail. In order to avoid this situation, we call `IsGuiThread` to initialize
// it. // it.
user32::IsGUIThread(1); winuser::IsGUIThread(1);
// Then only we unblock the `new()` function. We are sure that we don't call // Then only we unblock the `new()` function. We are sure that we don't call
// `PostThreadMessageA()` before `new()` returns. // `PostThreadMessageA()` before `new()` returns.
barrier_clone.wait(); barrier_clone.wait();
@ -119,9 +119,9 @@ impl EventsLoop {
let mut msg = mem::uninitialized(); let mut msg = mem::uninitialized();
loop { loop {
if user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 { if winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 {
// Only happens if the message is `WM_QUIT`. // Only happens if the message is `WM_QUIT`.
debug_assert_eq!(msg.message, winapi::WM_QUIT); debug_assert_eq!(msg.message, winuser::WM_QUIT);
break; break;
} }
@ -135,8 +135,8 @@ impl EventsLoop {
}, },
_ => { _ => {
// Calls `callback` below. // Calls `callback` below.
user32::TranslateMessage(&msg); winuser::TranslateMessage(&msg);
user32::DispatchMessageW(&msg); winuser::DispatchMessageW(&msg);
} }
} }
} }
@ -146,8 +146,13 @@ impl EventsLoop {
// Blocks this function until the background thread has an events loop. See other comments. // Blocks this function until the background thread has an events loop. See other comments.
barrier.wait(); barrier.wait();
let thread_id = unsafe {
let handle = mem::transmute(thread.as_raw_handle());
processthreadsapi::GetThreadId(handle)
};
EventsLoop { EventsLoop {
thread_id: unsafe { kernel32::GetThreadId(thread.as_raw_handle()) }, thread_id,
receiver: rx, receiver: rx,
win32_block_loop win32_block_loop
} }
@ -225,8 +230,8 @@ impl EventsLoop {
let raw = Box::into_raw(boxed2); let raw = Box::into_raw(boxed2);
let res = user32::PostThreadMessageA(self.thread_id, *EXEC_MSG_ID, let res = winuser::PostThreadMessageA(self.thread_id, *EXEC_MSG_ID,
raw as *mut () as usize as winapi::WPARAM, 0); raw as *mut () as usize as WPARAM, 0);
// PostThreadMessage can only fail if the thread ID is invalid (which shouldn't happen // 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. // as the events loop is still alive) or if the queue is full.
assert!(res != 0, "PostThreadMessage failed ; is the messages queue full?"); assert!(res != 0, "PostThreadMessage failed ; is the messages queue full?");
@ -238,20 +243,20 @@ impl Drop for EventsLoop {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
// Posting `WM_QUIT` will cause `GetMessage` to stop. // Posting `WM_QUIT` will cause `GetMessage` to stop.
user32::PostThreadMessageA(self.thread_id, winapi::WM_QUIT, 0, 0); winuser::PostThreadMessageA(self.thread_id, winuser::WM_QUIT, 0, 0);
} }
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub struct EventsLoopProxy { pub struct EventsLoopProxy {
thread_id: winapi::DWORD, thread_id: DWORD,
} }
impl EventsLoopProxy { impl EventsLoopProxy {
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
unsafe { unsafe {
if user32::PostThreadMessageA(self.thread_id, *WAKEUP_MSG_ID, 0, 0) != 0 { if winuser::PostThreadMessageA(self.thread_id, *WAKEUP_MSG_ID, 0, 0) != 0 {
Ok(()) Ok(())
} else { } else {
// https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms644946(v=vs.85).aspx // https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms644946(v=vs.85).aspx
@ -272,7 +277,7 @@ lazy_static! {
// WPARAM and LPARAM are unused. // WPARAM and LPARAM are unused.
static ref WAKEUP_MSG_ID: u32 = { static ref WAKEUP_MSG_ID: u32 = {
unsafe { unsafe {
user32::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as *const i8) winuser::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as *const i8)
} }
}; };
// Message sent when we want to execute a closure in the thread. // Message sent when we want to execute a closure in the thread.
@ -280,7 +285,7 @@ lazy_static! {
// and LPARAM is unused. // and LPARAM is unused.
static ref EXEC_MSG_ID: u32 = { static ref EXEC_MSG_ID: u32 = {
unsafe { unsafe {
user32::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as *const i8) winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as *const i8)
} }
}; };
} }
@ -290,7 +295,7 @@ lazy_static! {
thread_local!(static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); thread_local!(static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None));
struct ThreadLocalData { struct ThreadLocalData {
sender: mpsc::Sender<Event>, sender: mpsc::Sender<Event>,
windows: HashMap<winapi::HWND, Arc<Mutex<WindowState>>>, windows: HashMap<HWND, Arc<Mutex<WindowState>>>,
win32_block_loop: Arc<(Mutex<bool>, Condvar)> win32_block_loop: Arc<(Mutex<bool>, Condvar)>
} }
@ -310,12 +315,12 @@ fn send_event(event: Event) {
// //
// Returning 0 tells the Win32 API that the message has been processed. // Returning 0 tells the Win32 API that the message has been processed.
// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary
pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT, pub unsafe extern "system" fn callback(window: HWND, msg: UINT,
wparam: winapi::WPARAM, lparam: winapi::LPARAM) wparam: WPARAM, lparam: LPARAM)
-> winapi::LRESULT -> LRESULT
{ {
match msg { match msg {
winapi::WM_CLOSE => { winuser::WM_CLOSE => {
use events::WindowEvent::Closed; use events::WindowEvent::Closed;
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
@ -325,17 +330,17 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
let mut context_stash = context_stash.borrow_mut(); let mut context_stash = context_stash.borrow_mut();
context_stash.as_mut().unwrap().windows.remove(&window); context_stash.as_mut().unwrap().windows.remove(&window);
}); });
user32::DefWindowProcW(window, msg, wparam, lparam) winuser::DefWindowProcW(window, msg, wparam, lparam)
}, },
winapi::WM_ERASEBKGND => { winuser::WM_ERASEBKGND => {
1 1
}, },
winapi::WM_SIZE => { winuser::WM_SIZE => {
use events::WindowEvent::Resized; use events::WindowEvent::Resized;
let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let w = LOWORD(lparam as DWORD) as u32;
let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; let h = HIWORD(lparam as DWORD) as u32;
// Wait for the parent thread to process the resize event before returning from the // Wait for the parent thread to process the resize event before returning from the
// callback. // callback.
@ -370,10 +375,10 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_MOVE => { winuser::WM_MOVE => {
use events::WindowEvent::Moved; use events::WindowEvent::Moved;
let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let x = LOWORD(lparam as DWORD) as i32;
let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; let y = HIWORD(lparam as DWORD) as i32;
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
event: Moved(x, y), event: Moved(x, y),
@ -381,7 +386,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_CHAR => { winuser::WM_CHAR => {
use std::mem; use std::mem;
use events::WindowEvent::ReceivedCharacter; use events::WindowEvent::ReceivedCharacter;
let chr: char = mem::transmute(wparam as u32); let chr: char = mem::transmute(wparam as u32);
@ -396,11 +401,11 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
// "ding" sounds. Alternatively could check for WM_SYSCOMMAND // "ding" sounds. Alternatively could check for WM_SYSCOMMAND
// with wparam being SC_KEYMENU, but this may prevent some // with wparam being SC_KEYMENU, but this may prevent some
// other unwanted default hotkeys as well. // other unwanted default hotkeys as well.
winapi::WM_SYSCHAR => { winuser::WM_SYSCHAR => {
0 0
} }
winapi::WM_MOUSEMOVE => { winuser::WM_MOUSEMOVE => {
use events::WindowEvent::{CursorEntered, CursorMoved}; use events::WindowEvent::{CursorEntered, CursorMoved};
let mouse_outside_window = CONTEXT_STASH.with(|context_stash| { let mouse_outside_window = CONTEXT_STASH.with(|context_stash| {
let mut context_stash = context_stash.borrow_mut(); let mut context_stash = context_stash.borrow_mut();
@ -424,16 +429,16 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
}); });
// Calling TrackMouseEvent in order to receive mouse leave events. // Calling TrackMouseEvent in order to receive mouse leave events.
user32::TrackMouseEvent(&mut winapi::TRACKMOUSEEVENT { winuser::TrackMouseEvent(&mut winuser::TRACKMOUSEEVENT {
cbSize: mem::size_of::<winapi::TRACKMOUSEEVENT>() as winapi::DWORD, cbSize: mem::size_of::<winuser::TRACKMOUSEEVENT>() as DWORD,
dwFlags: winapi::TME_LEAVE, dwFlags: winuser::TME_LEAVE,
hwndTrack: window, hwndTrack: window,
dwHoverTime: winapi::HOVER_DEFAULT, dwHoverTime: winuser::HOVER_DEFAULT,
}); });
} }
let x = winapi::GET_X_LPARAM(lparam) as f64; let x = windowsx::GET_X_LPARAM(lparam) as f64;
let y = winapi::GET_Y_LPARAM(lparam) as f64; let y = windowsx::GET_Y_LPARAM(lparam) as f64;
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
@ -443,7 +448,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_MOUSELEAVE => { winuser::WM_MOUSELEAVE => {
use events::WindowEvent::CursorLeft; use events::WindowEvent::CursorLeft;
let mouse_in_window = CONTEXT_STASH.with(|context_stash| { let mouse_in_window = CONTEXT_STASH.with(|context_stash| {
let mut context_stash = context_stash.borrow_mut(); let mut context_stash = context_stash.borrow_mut();
@ -470,14 +475,14 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_MOUSEWHEEL => { winuser::WM_MOUSEWHEEL => {
use events::{DeviceEvent, WindowEvent}; use events::{DeviceEvent, WindowEvent};
use events::MouseScrollDelta::LineDelta; use events::MouseScrollDelta::LineDelta;
use events::TouchPhase; use events::TouchPhase;
let value = (wparam >> 16) as i16; let value = (wparam >> 16) as i16;
let value = value as i32; let value = value as i32;
let value = value as f32 / winapi::WHEEL_DELTA as f32; let value = value as f32 / winuser::WHEEL_DELTA as f32;
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
@ -492,11 +497,11 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { winuser::WM_KEYDOWN | winuser::WM_SYSKEYDOWN => {
use events::ElementState::Pressed; use events::ElementState::Pressed;
use events::VirtualKeyCode; use events::VirtualKeyCode;
if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { if msg == winuser::WM_SYSKEYDOWN && wparam as i32 == winuser::VK_F4 {
user32::DefWindowProcW(window, msg, wparam, lparam) winuser::DefWindowProcW(window, msg, wparam, lparam)
} else { } else {
let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam);
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
@ -523,7 +528,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
} }
}, },
winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { winuser::WM_KEYUP | winuser::WM_SYSKEYUP => {
use events::ElementState::Released; use events::ElementState::Released;
let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam);
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
@ -541,7 +546,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_LBUTTONDOWN => { winuser::WM_LBUTTONDOWN => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Left; use events::MouseButton::Left;
use events::ElementState::Pressed; use events::ElementState::Pressed;
@ -552,7 +557,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_LBUTTONUP => { winuser::WM_LBUTTONUP => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Left; use events::MouseButton::Left;
use events::ElementState::Released; use events::ElementState::Released;
@ -563,7 +568,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_RBUTTONDOWN => { winuser::WM_RBUTTONDOWN => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Right; use events::MouseButton::Right;
use events::ElementState::Pressed; use events::ElementState::Pressed;
@ -574,7 +579,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_RBUTTONUP => { winuser::WM_RBUTTONUP => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Right; use events::MouseButton::Right;
use events::ElementState::Released; use events::ElementState::Released;
@ -585,7 +590,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_MBUTTONDOWN => { winuser::WM_MBUTTONDOWN => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Middle; use events::MouseButton::Middle;
use events::ElementState::Pressed; use events::ElementState::Pressed;
@ -596,7 +601,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_MBUTTONUP => { winuser::WM_MBUTTONUP => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Middle; use events::MouseButton::Middle;
use events::ElementState::Released; use events::ElementState::Released;
@ -607,11 +612,11 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_XBUTTONDOWN => { winuser::WM_XBUTTONDOWN => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Other; use events::MouseButton::Other;
use events::ElementState::Pressed; use events::ElementState::Pressed;
let xbutton = winapi::HIWORD(wparam as winapi::DWORD) as winapi::c_int; // waiting on PR for winapi to add GET_XBUTTON_WPARAM let xbutton = winuser::GET_XBUTTON_WPARAM(wparam);
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Other(xbutton as u8) } event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Other(xbutton as u8) }
@ -619,11 +624,11 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_XBUTTONUP => { winuser::WM_XBUTTONUP => {
use events::WindowEvent::MouseInput; use events::WindowEvent::MouseInput;
use events::MouseButton::Other; use events::MouseButton::Other;
use events::ElementState::Released; use events::ElementState::Released;
let xbutton = winapi::HIWORD(wparam as winapi::DWORD) as winapi::c_int; let xbutton = winuser::GET_XBUTTON_WPARAM(wparam);
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
event: MouseInput { device_id: DEVICE_ID, state: Released, button: Other(xbutton as u8) } event: MouseInput { device_id: DEVICE_ID, state: Released, button: Other(xbutton as u8) }
@ -631,18 +636,19 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_INPUT => { winuser::WM_INPUT => {
use events::DeviceEvent::{Motion, MouseMotion}; use events::DeviceEvent::{Motion, MouseMotion};
let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data: winuser::RAWINPUT = mem::uninitialized();
let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; let mut data_size = mem::size_of::<winuser::RAWINPUT>() as UINT;
user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, winuser::GetRawInputData(mem::transmute(lparam), winuser::RID_INPUT,
mem::transmute(&mut data), &mut data_size, mem::transmute(&mut data), &mut data_size,
mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); mem::size_of::<winuser::RAWINPUTHEADER>() as UINT);
if data.header.dwType == winapi::RIM_TYPEMOUSE { if data.header.dwType == winuser::RIM_TYPEMOUSE {
if data.mouse.usFlags & winapi::MOUSE_MOVE_RELATIVE == winapi::MOUSE_MOVE_RELATIVE { let mouse = data.data.mouse();
let x = data.mouse.lLastX as f64; if mouse.usFlags & winuser::MOUSE_MOVE_RELATIVE == winuser::MOUSE_MOVE_RELATIVE {
let y = data.mouse.lLastY as f64; let x = mouse.lLastX as f64;
let y = mouse.lLastY as f64;
if x != 0.0 { if x != 0.0 {
send_event(Event::DeviceEvent { send_event(Event::DeviceEvent {
@ -668,19 +674,19 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
} else { } else {
user32::DefWindowProcW(window, msg, wparam, lparam) winuser::DefWindowProcW(window, msg, wparam, lparam)
} }
}, },
winapi::WM_SETFOCUS => { winuser::WM_SETFOCUS => {
use events::WindowEvent::{Focused, CursorMoved}; use events::WindowEvent::{Focused, CursorMoved};
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
event: Focused(true) event: Focused(true)
}); });
let x = winapi::GET_X_LPARAM(lparam) as f64; let x = windowsx::GET_X_LPARAM(lparam) as f64;
let y = winapi::GET_Y_LPARAM(lparam) as f64; let y = windowsx::GET_Y_LPARAM(lparam) as f64;
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
@ -689,7 +695,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_KILLFOCUS => { winuser::WM_KILLFOCUS => {
use events::WindowEvent::Focused; use events::WindowEvent::Focused;
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
@ -698,7 +704,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
0 0
}, },
winapi::WM_SETCURSOR => { winuser::WM_SETCURSOR => {
let call_def_window_proc = CONTEXT_STASH.with(|context_stash| { let call_def_window_proc = CONTEXT_STASH.with(|context_stash| {
let cstash = context_stash.borrow(); let cstash = context_stash.borrow();
let mut call_def_window_proc = false; let mut call_def_window_proc = false;
@ -708,12 +714,12 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
if window_state.mouse_in_window { if window_state.mouse_in_window {
match window_state.cursor_state { match window_state.cursor_state {
CursorState::Normal => { CursorState::Normal => {
user32::SetCursor(user32::LoadCursorW( winuser::SetCursor(winuser::LoadCursorW(
ptr::null_mut(), ptr::null_mut(),
window_state.cursor)); window_state.cursor));
}, },
CursorState::Grab | CursorState::Hide => { CursorState::Grab | CursorState::Hide => {
user32::SetCursor(ptr::null_mut()); winuser::SetCursor(ptr::null_mut());
} }
} }
} else { } else {
@ -727,22 +733,22 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
}); });
if call_def_window_proc { if call_def_window_proc {
user32::DefWindowProcW(window, msg, wparam, lparam) winuser::DefWindowProcW(window, msg, wparam, lparam)
} else { } else {
0 0
} }
}, },
winapi::WM_DROPFILES => { winuser::WM_DROPFILES => {
use events::WindowEvent::DroppedFile; use events::WindowEvent::DroppedFile;
let hdrop = wparam as winapi::HDROP; let hdrop = wparam as shellapi::HDROP;
let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let mut pathbuf: [u16; MAX_PATH] = mem::uninitialized();
let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); let num_drops = shellapi::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0);
for i in 0..num_drops { for i in 0..num_drops {
let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), let nch = shellapi::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(),
winapi::MAX_PATH as u32) as usize; MAX_PATH as u32) as usize;
if nch > 0 { if nch > 0 {
send_event(Event::WindowEvent { send_event(Event::WindowEvent {
window_id: SuperWindowId(WindowId(window)), window_id: SuperWindowId(WindowId(window)),
@ -751,27 +757,14 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
} }
} }
shell32::DragFinish(hdrop); shellapi::DragFinish(hdrop);
0 0
}, },
winapi::WM_GETMINMAXINFO => { winuser::WM_GETMINMAXINFO => {
// Equivalent to the windows api [MINMAXINFO](https://msdn.microsoft.com/en-us/library/windows/desktop/ms632605%28v=vs.85%29.aspx) let mmi = lparam as *mut winuser::MINMAXINFO;
// struct. Used because winapi-rs doesn't have this declared. //(*mmi).max_position = winapi::shared::windef::POINT { x: -8, y: -8 }; // The upper left corner of the window if it were maximized on the primary monitor.
// TODO: replace with struct from winapi-rs //(*mmi).max_size = winapi::shared::windef::POINT { x: .., y: .. }; // The dimensions of the primary monitor.
#[repr(C)]
#[allow(dead_code)]
struct MinMaxInfo {
reserved: winapi::POINT, // Do not use/change
max_size: winapi::POINT,
max_position: winapi::POINT,
min_track: winapi::POINT,
max_track: winapi::POINT
}
let mmi = lparam as *mut MinMaxInfo;
//(*mmi).max_position = winapi::POINT { x: -8, y: -8 }; // The upper left corner of the window if it were maximized on the primary monitor.
//(*mmi).max_size = winapi::POINT { x: .., y: .. }; // The dimensions of the primary monitor.
CONTEXT_STASH.with(|context_stash| { CONTEXT_STASH.with(|context_stash| {
if let Some(cstash) = context_stash.borrow().as_ref() { if let Some(cstash) = context_stash.borrow().as_ref() {
@ -780,14 +773,14 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
match window_state.attributes.min_dimensions { match window_state.attributes.min_dimensions {
Some((width, height)) => { Some((width, height)) => {
(*mmi).min_track = winapi::POINT { x: width as i32, y: height as i32 }; (*mmi).ptMinTrackSize = POINT { x: width as i32, y: height as i32 };
}, },
None => { } None => { }
} }
match window_state.attributes.max_dimensions { match window_state.attributes.max_dimensions {
Some((width, height)) => { Some((width, height)) => {
(*mmi).max_track = winapi::POINT { x: width as i32, y: height as i32 }; (*mmi).ptMaxTrackSize = POINT { x: width as i32, y: height as i32 };
}, },
None => { } None => { }
} }
@ -799,7 +792,7 @@ pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT,
}, },
_ => { _ => {
user32::DefWindowProcW(window, msg, wparam, lparam) winuser::DefWindowProcW(window, msg, wparam, lparam)
} }
} }
} }

View file

@ -1,6 +1,7 @@
#![cfg(target_os = "windows")] #![cfg(target_os = "windows")]
use winapi; use winapi;
use winapi::shared::windef::HWND;
pub use self::events_loop::{EventsLoop, EventsLoopProxy}; pub use self::events_loop::{EventsLoop, EventsLoopProxy};
pub use self::monitor::MonitorId; pub use self::monitor::MonitorId;
@ -8,14 +9,14 @@ pub use self::window::Window;
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct PlatformSpecificWindowBuilderAttributes { pub struct PlatformSpecificWindowBuilderAttributes {
pub parent: Option<winapi::HWND>, pub parent: Option<HWND>,
} }
unsafe impl Send for PlatformSpecificWindowBuilderAttributes {} unsafe impl Send for PlatformSpecificWindowBuilderAttributes {}
unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {} unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {}
// TODO: document what this means // TODO: document what this means
pub type Cursor = *const winapi::wchar_t; pub type Cursor = *const winapi::ctypes::wchar_t;
// Constant device ID, to be removed when this backend is updated to report real device IDs. // Constant device ID, to be removed when this backend is updated to report real device IDs.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
@ -23,7 +24,7 @@ pub struct DeviceId;
const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId); const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WindowId(winapi::HWND); pub struct WindowId(HWND);
unsafe impl Send for WindowId {} unsafe impl Send for WindowId {}
unsafe impl Sync for WindowId {} unsafe impl Sync for WindowId {}

View file

@ -1,5 +1,7 @@
use winapi; use winapi::ctypes::wchar_t;
use user32; use winapi::shared::minwindef::{DWORD, LPARAM, BOOL, TRUE};
use winapi::shared::windef::{HMONITOR, HDC, LPRECT};
use winapi::um::winuser;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::{mem, ptr}; use std::{mem, ptr};
@ -10,7 +12,7 @@ use super::EventsLoop;
#[derive(Clone)] #[derive(Clone)]
pub struct MonitorId { pub struct MonitorId {
/// The system name of the adapter. /// The system name of the adapter.
adapter_name: [winapi::WCHAR; 32], adapter_name: [wchar_t; 32],
/// Monitor handle. /// Monitor handle.
hmonitor: HMonitor, hmonitor: HMonitor,
@ -38,49 +40,49 @@ pub struct MonitorId {
// https://github.com/retep998/winapi-rs/issues/360 // https://github.com/retep998/winapi-rs/issues/360
// https://github.com/retep998/winapi-rs/issues/396 // https://github.com/retep998/winapi-rs/issues/396
#[derive(Clone)] #[derive(Clone)]
struct HMonitor(winapi::HMONITOR); struct HMonitor(HMONITOR);
unsafe impl Send for HMonitor {} unsafe impl Send for HMonitor {}
fn wchar_as_string(wchar: &[winapi::WCHAR]) -> String { fn wchar_as_string(wchar: &[wchar_t]) -> String {
String::from_utf16_lossy(wchar) String::from_utf16_lossy(wchar)
.trim_right_matches(0 as char) .trim_right_matches(0 as char)
.to_string() .to_string()
} }
unsafe extern "system" fn monitor_enum_proc(hmonitor: winapi::HMONITOR, _: winapi::HDC, place: winapi::LPRECT, data: winapi::LPARAM) -> winapi::BOOL { unsafe extern "system" fn monitor_enum_proc(hmonitor: HMONITOR, _: HDC, place: LPRECT, data: LPARAM) -> BOOL {
let monitors = data as *mut VecDeque<MonitorId>; let monitors = data as *mut VecDeque<MonitorId>;
let place = *place; let place = *place;
let position = (place.left as i32, place.top as i32); 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 dimensions = ((place.right - place.left) as u32, (place.bottom - place.top) as u32);
let mut monitor_info: winapi::MONITORINFOEXW = mem::zeroed(); let mut monitor_info: winuser::MONITORINFOEXW = mem::zeroed();
monitor_info.cbSize = mem::size_of::<winapi::MONITORINFOEXW>() as winapi::DWORD; monitor_info.cbSize = mem::size_of::<winuser::MONITORINFOEXW>() as DWORD;
if user32::GetMonitorInfoW(hmonitor, &mut monitor_info as *mut winapi::MONITORINFOEXW as *mut winapi::MONITORINFO) == 0 { 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. // Some error occurred, just skip this monitor and go on.
return winapi::TRUE; return TRUE;
} }
(*monitors).push_back(MonitorId { (*monitors).push_back(MonitorId {
adapter_name: monitor_info.szDevice, adapter_name: monitor_info.szDevice,
hmonitor: HMonitor(hmonitor), hmonitor: HMonitor(hmonitor),
monitor_name: wchar_as_string(&monitor_info.szDevice), monitor_name: wchar_as_string(&monitor_info.szDevice),
primary: monitor_info.dwFlags & winapi::MONITORINFOF_PRIMARY != 0, primary: monitor_info.dwFlags & winuser::MONITORINFOF_PRIMARY != 0,
position, position,
dimensions, dimensions,
hidpi_factor: 1.0, hidpi_factor: 1.0,
}); });
// TRUE means continue enumeration. // TRUE means continue enumeration.
winapi::TRUE TRUE
} }
impl EventsLoop { impl EventsLoop {
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> { pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
unsafe { unsafe {
let mut result: VecDeque<MonitorId> = VecDeque::new(); let mut result: VecDeque<MonitorId> = VecDeque::new();
user32::EnumDisplayMonitors(ptr::null_mut(), ptr::null_mut(), Some(monitor_enum_proc), &mut result as *mut _ as winapi::LPARAM); winuser::EnumDisplayMonitors(ptr::null_mut(), ptr::null_mut(), Some(monitor_enum_proc), &mut result as *mut _ as LPARAM);
result result
} }
} }
@ -114,7 +116,7 @@ impl MonitorId {
/// See the docs of the crate root file. /// See the docs of the crate root file.
#[inline] #[inline]
pub fn get_hmonitor(&self) -> winapi::HMONITOR { pub fn get_hmonitor(&self) -> HMONITOR {
self.hmonitor.0 self.hmonitor.0
} }
@ -128,7 +130,7 @@ impl MonitorId {
/// This is a Win32-only function for `MonitorId` that returns the system name of the adapter /// This is a Win32-only function for `MonitorId` that returns the system name of the adapter
/// device. /// device.
#[inline] #[inline]
pub fn get_adapter_name(&self) -> &[winapi::WCHAR] { pub fn get_adapter_name(&self) -> &[wchar_t] {
&self.adapter_name &self.adapter_name
} }

View file

@ -22,10 +22,11 @@ use MouseCursor;
use WindowAttributes; use WindowAttributes;
use MonitorId as RootMonitorId; use MonitorId as RootMonitorId;
use dwmapi; use winapi::shared::minwindef::{UINT, WORD, DWORD, BOOL};
use kernel32; use winapi::shared::windef::{HWND, HDC, RECT, POINT};
use user32; use winapi::shared::hidusage;
use winapi; use winapi::um::{winuser, dwmapi, wingdi, libloaderapi, processthreadsapi};
use winapi::um::winnt::{LPCWSTR, LONG};
/// The Win32 implementation of the main `Window` object. /// The Win32 implementation of the main `Window` object.
pub struct Window { pub struct Window {
@ -62,21 +63,21 @@ impl Window {
let text = OsStr::new(text).encode_wide().chain(Some(0).into_iter()) let text = OsStr::new(text).encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
user32::SetWindowTextW(self.window.0, text.as_ptr() as winapi::LPCWSTR); winuser::SetWindowTextW(self.window.0, text.as_ptr() as LPCWSTR);
} }
} }
#[inline] #[inline]
pub fn show(&self) { pub fn show(&self) {
unsafe { unsafe {
user32::ShowWindow(self.window.0, winapi::SW_SHOW); winuser::ShowWindow(self.window.0, winuser::SW_SHOW);
} }
} }
#[inline] #[inline]
pub fn hide(&self) { pub fn hide(&self) {
unsafe { unsafe {
user32::ShowWindow(self.window.0, winapi::SW_HIDE); winuser::ShowWindow(self.window.0, winuser::SW_HIDE);
} }
} }
@ -84,10 +85,10 @@ impl Window {
pub fn get_position(&self) -> Option<(i32, i32)> { pub fn get_position(&self) -> Option<(i32, i32)> {
use std::mem; use std::mem;
let mut placement: winapi::WINDOWPLACEMENT = unsafe { mem::zeroed() }; let mut placement: winuser::WINDOWPLACEMENT = unsafe { mem::zeroed() };
placement.length = mem::size_of::<winapi::WINDOWPLACEMENT>() as winapi::UINT; placement.length = mem::size_of::<winuser::WINDOWPLACEMENT>() as UINT;
if unsafe { user32::GetWindowPlacement(self.window.0, &mut placement) } == 0 { if unsafe { winuser::GetWindowPlacement(self.window.0, &mut placement) } == 0 {
return None return None
} }
@ -98,18 +99,18 @@ impl Window {
/// See the docs in the crate root file. /// See the docs in the crate root file.
pub fn set_position(&self, x: i32, y: i32) { pub fn set_position(&self, x: i32, y: i32) {
unsafe { unsafe {
user32::SetWindowPos(self.window.0, ptr::null_mut(), x as raw::c_int, y as raw::c_int, winuser::SetWindowPos(self.window.0, ptr::null_mut(), x as raw::c_int, y as raw::c_int,
0, 0, winapi::SWP_ASYNCWINDOWPOS | winapi::SWP_NOZORDER | winapi::SWP_NOSIZE); 0, 0, winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOSIZE);
user32::UpdateWindow(self.window.0); winuser::UpdateWindow(self.window.0);
} }
} }
/// See the docs in the crate root file. /// See the docs in the crate root file.
#[inline] #[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> { pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; let mut rect: RECT = unsafe { mem::uninitialized() };
if unsafe { user32::GetClientRect(self.window.0, &mut rect) } == 0 { if unsafe { winuser::GetClientRect(self.window.0, &mut rect) } == 0 {
return None return None
} }
@ -122,9 +123,9 @@ impl Window {
/// See the docs in the crate root file. /// See the docs in the crate root file.
#[inline] #[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> { pub fn get_outer_size(&self) -> Option<(u32, u32)> {
let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; let mut rect: RECT = unsafe { mem::uninitialized() };
if unsafe { user32::GetWindowRect(self.window.0, &mut rect) } == 0 { if unsafe { winuser::GetWindowRect(self.window.0, &mut rect) } == 0 {
return None return None
} }
@ -138,17 +139,17 @@ impl Window {
pub fn set_inner_size(&self, x: u32, y: u32) { pub fn set_inner_size(&self, x: u32, y: u32) {
unsafe { unsafe {
// Calculate the outer size based upon the specified inner size // Calculate the outer size based upon the specified inner size
let mut rect = winapi::RECT { top: 0, left: 0, bottom: y as winapi::LONG, right: x as winapi::LONG }; let mut rect = RECT { top: 0, left: 0, bottom: y as LONG, right: x as LONG };
let dw_style = user32::GetWindowLongA(self.window.0, winapi::GWL_STYLE) as winapi::DWORD; let dw_style = winuser::GetWindowLongA(self.window.0, winuser::GWL_STYLE) as DWORD;
let b_menu = !user32::GetMenu(self.window.0).is_null() as winapi::BOOL; let b_menu = !winuser::GetMenu(self.window.0).is_null() as BOOL;
let dw_style_ex = user32::GetWindowLongA(self.window.0, winapi::GWL_EXSTYLE) as winapi::DWORD; let dw_style_ex = winuser::GetWindowLongA(self.window.0, winuser::GWL_EXSTYLE) as DWORD;
user32::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex); 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_x = (rect.right - rect.left).abs() as raw::c_int;
let outer_y = (rect.top - rect.bottom).abs() as raw::c_int; let outer_y = (rect.top - rect.bottom).abs() as raw::c_int;
user32::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, outer_x, outer_y, winuser::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, outer_x, outer_y,
winapi::SWP_ASYNCWINDOWPOS | winapi::SWP_NOZORDER | winapi::SWP_NOREPOSITION | winapi::SWP_NOMOVE); winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOREPOSITION | winuser::SWP_NOMOVE);
user32::UpdateWindow(self.window.0); winuser::UpdateWindow(self.window.0);
} }
} }
@ -163,27 +164,27 @@ impl Window {
/// Returns the `hwnd` of this window. /// Returns the `hwnd` of this window.
#[inline] #[inline]
pub fn hwnd(&self) -> winapi::HWND { pub fn hwnd(&self) -> HWND {
self.window.0 self.window.0
} }
#[inline] #[inline]
pub fn set_cursor(&self, cursor: MouseCursor) { pub fn set_cursor(&self, cursor: MouseCursor) {
let cursor_id = match cursor { let cursor_id = match cursor {
MouseCursor::Arrow | MouseCursor::Default => winapi::IDC_ARROW, MouseCursor::Arrow | MouseCursor::Default => winuser::IDC_ARROW,
MouseCursor::Hand => winapi::IDC_HAND, MouseCursor::Hand => winuser::IDC_HAND,
MouseCursor::Crosshair => winapi::IDC_CROSS, MouseCursor::Crosshair => winuser::IDC_CROSS,
MouseCursor::Text | MouseCursor::VerticalText => winapi::IDC_IBEAM, MouseCursor::Text | MouseCursor::VerticalText => winuser::IDC_IBEAM,
MouseCursor::NotAllowed | MouseCursor::NoDrop => winapi::IDC_NO, MouseCursor::NotAllowed | MouseCursor::NoDrop => winuser::IDC_NO,
MouseCursor::EResize => winapi::IDC_SIZEWE, MouseCursor::EResize => winuser::IDC_SIZEWE,
MouseCursor::NResize => winapi::IDC_SIZENS, MouseCursor::NResize => winuser::IDC_SIZENS,
MouseCursor::WResize => winapi::IDC_SIZEWE, MouseCursor::WResize => winuser::IDC_SIZEWE,
MouseCursor::SResize => winapi::IDC_SIZENS, MouseCursor::SResize => winuser::IDC_SIZENS,
MouseCursor::EwResize | MouseCursor::ColResize => winapi::IDC_SIZEWE, MouseCursor::EwResize | MouseCursor::ColResize => winuser::IDC_SIZEWE,
MouseCursor::NsResize | MouseCursor::RowResize => winapi::IDC_SIZENS, MouseCursor::NsResize | MouseCursor::RowResize => winuser::IDC_SIZENS,
MouseCursor::Wait | MouseCursor::Progress => winapi::IDC_WAIT, MouseCursor::Wait | MouseCursor::Progress => winuser::IDC_WAIT,
MouseCursor::Help => winapi::IDC_HELP, MouseCursor::Help => winuser::IDC_HELP,
_ => winapi::IDC_ARROW, // use arrow for the missing cases. _ => winuser::IDC_ARROW, // use arrow for the missing cases.
}; };
let mut cur = self.window_state.lock().unwrap(); let mut cur = self.window_state.lock().unwrap();
@ -195,10 +196,10 @@ impl Window {
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> { pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
let mut current_state = self.window_state.lock().unwrap(); let mut current_state = self.window_state.lock().unwrap();
let foreground_thread_id = unsafe { user32::GetWindowThreadProcessId(self.window.0, ptr::null_mut()) }; let foreground_thread_id = unsafe { winuser::GetWindowThreadProcessId(self.window.0, ptr::null_mut()) };
let current_thread_id = unsafe { kernel32::GetCurrentThreadId() }; let current_thread_id = unsafe { processthreadsapi::GetCurrentThreadId() };
unsafe { user32::AttachThreadInput(foreground_thread_id, current_thread_id, 1) }; unsafe { winuser::AttachThreadInput(foreground_thread_id, current_thread_id, 1) };
let res = match (state, current_state.cursor_state) { let res = match (state, current_state.cursor_state) {
(CursorState::Normal, CursorState::Normal) => Ok(()), (CursorState::Normal, CursorState::Normal) => Ok(()),
@ -218,12 +219,12 @@ impl Window {
(CursorState::Grab, CursorState::Normal) | (CursorState::Grab, CursorState::Hide) => { (CursorState::Grab, CursorState::Normal) | (CursorState::Grab, CursorState::Hide) => {
unsafe { unsafe {
let mut rect = mem::uninitialized(); let mut rect = mem::uninitialized();
if user32::GetClientRect(self.window.0, &mut rect) == 0 { if winuser::GetClientRect(self.window.0, &mut rect) == 0 {
return Err(format!("GetWindowRect failed")); return Err(format!("GetWindowRect failed"));
} }
user32::ClientToScreen(self.window.0, mem::transmute(&mut rect.left)); winuser::ClientToScreen(self.window.0, mem::transmute(&mut rect.left));
user32::ClientToScreen(self.window.0, mem::transmute(&mut rect.right)); winuser::ClientToScreen(self.window.0, mem::transmute(&mut rect.right));
if user32::ClipCursor(&rect) == 0 { if winuser::ClipCursor(&rect) == 0 {
return Err(format!("ClipCursor failed")); return Err(format!("ClipCursor failed"));
} }
current_state.cursor_state = CursorState::Grab; current_state.cursor_state = CursorState::Grab;
@ -233,7 +234,7 @@ impl Window {
(CursorState::Normal, CursorState::Grab) => { (CursorState::Normal, CursorState::Grab) => {
unsafe { unsafe {
if user32::ClipCursor(ptr::null()) == 0 { if winuser::ClipCursor(ptr::null()) == 0 {
return Err(format!("ClipCursor failed")); return Err(format!("ClipCursor failed"));
} }
current_state.cursor_state = CursorState::Normal; current_state.cursor_state = CursorState::Normal;
@ -244,7 +245,7 @@ impl Window {
_ => unimplemented!(), _ => unimplemented!(),
}; };
unsafe { user32::AttachThreadInput(foreground_thread_id, current_thread_id, 0) }; unsafe { winuser::AttachThreadInput(foreground_thread_id, current_thread_id, 0) };
res res
} }
@ -255,17 +256,17 @@ impl Window {
} }
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
let mut point = winapi::POINT { let mut point = POINT {
x: x, x: x,
y: y, y: y,
}; };
unsafe { unsafe {
if user32::ClientToScreen(self.window.0, &mut point) == 0 { if winuser::ClientToScreen(self.window.0, &mut point) == 0 {
return Err(()); return Err(());
} }
if user32::SetCursorPos(point.x, point.y) == 0 { if winuser::SetCursorPos(point.x, point.y) == 0 {
return Err(()); return Err(());
} }
} }
@ -305,20 +306,20 @@ impl Drop for Window {
unsafe { unsafe {
// We are sending WM_CLOSE, and our callback will process this by calling DefWindowProcW, // We are sending WM_CLOSE, and our callback will process this by calling DefWindowProcW,
// which in turn will send a WM_DESTROY. // which in turn will send a WM_DESTROY.
user32::PostMessageW(self.window.0, winapi::WM_CLOSE, 0, 0); winuser::PostMessageW(self.window.0, winuser::WM_CLOSE, 0, 0);
} }
} }
} }
/// A simple wrapper that destroys the window when it is destroyed. /// A simple wrapper that destroys the window when it is destroyed.
#[doc(hidden)] #[doc(hidden)]
pub struct WindowWrapper(winapi::HWND, winapi::HDC); pub struct WindowWrapper(HWND, HDC);
impl Drop for WindowWrapper { impl Drop for WindowWrapper {
#[inline] #[inline]
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
user32::DestroyWindow(self.0); winuser::DestroyWindow(self.0);
} }
} }
} }
@ -332,9 +333,9 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
let class_name = register_window_class(); let class_name = register_window_class();
// building a RECT object with coordinates // building a RECT object with coordinates
let mut rect = winapi::RECT { let mut rect = RECT {
left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG, left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as LONG,
top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG, top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as LONG,
}; };
// switching to fullscreen if necessary // switching to fullscreen if necessary
@ -349,22 +350,22 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
// computing the style and extended style of the window // computing the style and extended style of the window
let (ex_style, style) = if fullscreen || !window.decorations { let (ex_style, style) = if fullscreen || !window.decorations {
(winapi::WS_EX_APPWINDOW, (winuser::WS_EX_APPWINDOW,
//winapi::WS_POPUP is incompatible with winapi::WS_CHILD //winapi::WS_POPUP is incompatible with winapi::WS_CHILD
if pl_attribs.parent.is_some() { if pl_attribs.parent.is_some() {
winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN
} }
else { else {
winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN winuser::WS_POPUP | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN
} }
) )
} else { } else {
(winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE, (winuser::WS_EX_APPWINDOW | winuser::WS_EX_WINDOWEDGE,
winapi::WS_OVERLAPPEDWINDOW | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN) winuser::WS_OVERLAPPEDWINDOW | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN)
}; };
// adjusting the window coordinates using the style // adjusting the window coordinates using the style
user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style); winuser::AdjustWindowRectEx(&mut rect, style, 0, ex_style);
// creating the real window this time, by using the functions in `extra_functions` // creating the real window this time, by using the functions in `extra_functions`
let real_window = { let real_window = {
@ -383,21 +384,21 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
let mut style = if !window.visible { let mut style = if !window.visible {
style style
} else { } else {
style | winapi::WS_VISIBLE style | winuser::WS_VISIBLE
}; };
if pl_attribs.parent.is_some() { if pl_attribs.parent.is_some() {
style |= winapi::WS_CHILD; style |= winuser::WS_CHILD;
} }
let handle = user32::CreateWindowExW(ex_style | winapi::WS_EX_ACCEPTFILES, let handle = winuser::CreateWindowExW(ex_style | winuser::WS_EX_ACCEPTFILES,
class_name.as_ptr(), class_name.as_ptr(),
title.as_ptr() as winapi::LPCWSTR, title.as_ptr() as LPCWSTR,
style | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN, style | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN,
x.unwrap_or(winapi::CW_USEDEFAULT), y.unwrap_or(winapi::CW_USEDEFAULT), x.unwrap_or(winuser::CW_USEDEFAULT), y.unwrap_or(winuser::CW_USEDEFAULT),
width.unwrap_or(winapi::CW_USEDEFAULT), height.unwrap_or(winapi::CW_USEDEFAULT), width.unwrap_or(winuser::CW_USEDEFAULT), height.unwrap_or(winuser::CW_USEDEFAULT),
pl_attribs.parent.unwrap_or(ptr::null_mut()), pl_attribs.parent.unwrap_or(ptr::null_mut()),
ptr::null_mut(), kernel32::GetModuleHandleW(ptr::null()), ptr::null_mut(), libloaderapi::GetModuleHandleW(ptr::null()),
ptr::null_mut()); ptr::null_mut());
if handle.is_null() { if handle.is_null() {
@ -405,7 +406,7 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
format!("{}", io::Error::last_os_error())))); format!("{}", io::Error::last_os_error()))));
} }
let hdc = user32::GetDC(handle); let hdc = winuser::GetDC(handle);
if hdc.is_null() { if hdc.is_null() {
return Err(CreationError::OsError(format!("GetDC function failed: {}", return Err(CreationError::OsError(format!("GetDC function failed: {}",
format!("{}", io::Error::last_os_error())))); format!("{}", io::Error::last_os_error()))));
@ -416,18 +417,18 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
// Set up raw mouse input // Set up raw mouse input
{ {
let mut rid: winapi::RAWINPUTDEVICE = mem::uninitialized(); let mut rid: winuser::RAWINPUTDEVICE = mem::uninitialized();
rid.usUsagePage = winapi::HID_USAGE_PAGE_GENERIC; rid.usUsagePage = hidusage::HID_USAGE_PAGE_GENERIC;
rid.usUsage = winapi::HID_USAGE_GENERIC_MOUSE; rid.usUsage = hidusage::HID_USAGE_GENERIC_MOUSE;
rid.dwFlags = 0; rid.dwFlags = 0;
rid.hwndTarget = real_window.0; rid.hwndTarget = real_window.0;
user32::RegisterRawInputDevices(&rid, 1, mem::size_of::<winapi::RAWINPUTDEVICE>() as u32); winuser::RegisterRawInputDevices(&rid, 1, mem::size_of::<winuser::RAWINPUTDEVICE>() as u32);
} }
// Creating a mutex to track the current window state // Creating a mutex to track the current window state
let window_state = Arc::new(Mutex::new(events_loop::WindowState { let window_state = Arc::new(Mutex::new(events_loop::WindowState {
cursor: winapi::IDC_ARROW, // use arrow by default cursor: winuser::IDC_ARROW, // use arrow by default
cursor_state: CursorState::Normal, cursor_state: CursorState::Normal,
attributes: window.clone(), attributes: window.clone(),
mouse_in_window: false, mouse_in_window: false,
@ -437,7 +438,7 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
// making the window transparent // making the window transparent
if window.transparent { if window.transparent {
let bb = winapi::DWM_BLURBEHIND { let bb = dwmapi::DWM_BLURBEHIND {
dwFlags: 0x1, // FIXME: DWM_BB_ENABLE; dwFlags: 0x1, // FIXME: DWM_BB_ENABLE;
fEnable: 1, fEnable: 1,
hRgnBlur: ptr::null_mut(), hRgnBlur: ptr::null_mut(),
@ -449,7 +450,7 @@ unsafe fn init(window: WindowAttributes, pl_attribs: PlatformSpecificWindowBuild
// calling SetForegroundWindow if fullscreen // calling SetForegroundWindow if fullscreen
if fullscreen { if fullscreen {
user32::SetForegroundWindow(real_window.0); winuser::SetForegroundWindow(real_window.0);
} }
// Building the struct. // Building the struct.
@ -463,13 +464,13 @@ unsafe fn register_window_class() -> Vec<u16> {
let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter()) let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let class = winapi::WNDCLASSEXW { let class = winuser::WNDCLASSEXW {
cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT, cbSize: mem::size_of::<winuser::WNDCLASSEXW>() as UINT,
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC, style: winuser::CS_HREDRAW | winuser::CS_VREDRAW | winuser::CS_OWNDC,
lpfnWndProc: Some(events_loop::callback), lpfnWndProc: Some(events_loop::callback),
cbClsExtra: 0, cbClsExtra: 0,
cbWndExtra: 0, cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleW(ptr::null()), hInstance: libloaderapi::GetModuleHandleW(ptr::null()),
hIcon: ptr::null_mut(), hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly
hbrBackground: ptr::null_mut(), hbrBackground: ptr::null_mut(),
@ -482,36 +483,36 @@ unsafe fn register_window_class() -> Vec<u16> {
// an error, and because errors here are detected during CreateWindowEx anyway. // an error, and because errors here are detected during CreateWindowEx anyway.
// Also since there is no weird element in the struct, there is no reason for this // Also since there is no weird element in the struct, there is no reason for this
// call to fail. // call to fail.
user32::RegisterClassExW(&class); winuser::RegisterClassExW(&class);
class_name class_name
} }
unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorId) unsafe fn switch_to_fullscreen(rect: &mut RECT, monitor: &MonitorId)
-> Result<(), CreationError> -> Result<(), CreationError>
{ {
// adjusting the rect // adjusting the rect
{ {
let pos = monitor.get_position(); let pos = monitor.get_position();
rect.left += pos.0 as winapi::LONG; rect.left += pos.0 as LONG;
rect.right += pos.0 as winapi::LONG; rect.right += pos.0 as LONG;
rect.top += pos.1 as winapi::LONG; rect.top += pos.1 as LONG;
rect.bottom += pos.1 as winapi::LONG; rect.bottom += pos.1 as LONG;
} }
// changing device settings // changing device settings
let mut screen_settings: winapi::DEVMODEW = mem::zeroed(); let mut screen_settings: wingdi::DEVMODEW = mem::zeroed();
screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; screen_settings.dmSize = mem::size_of::<wingdi::DEVMODEW>() as WORD;
screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD; screen_settings.dmPelsWidth = (rect.right - rect.left) as DWORD;
screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD; screen_settings.dmPelsHeight = (rect.bottom - rect.top) as DWORD;
screen_settings.dmBitsPerPel = 32; // TODO: ? screen_settings.dmBitsPerPel = 32; // TODO: ?
screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT; screen_settings.dmFields = wingdi::DM_BITSPERPEL | wingdi::DM_PELSWIDTH | wingdi::DM_PELSHEIGHT;
let result = user32::ChangeDisplaySettingsExW(monitor.get_adapter_name().as_ptr(), let result = winuser::ChangeDisplaySettingsExW(monitor.get_adapter_name().as_ptr(),
&mut screen_settings, ptr::null_mut(), &mut screen_settings, ptr::null_mut(),
winapi::CDS_FULLSCREEN, ptr::null_mut()); winuser::CDS_FULLSCREEN, ptr::null_mut());
if result != winapi::DISP_CHANGE_SUCCESSFUL { if result != winuser::DISP_CHANGE_SUCCESSFUL {
return Err(CreationError::OsError(format!("ChangeDisplaySettings failed: {}", result))); return Err(CreationError::OsError(format!("ChangeDisplaySettings failed: {}", result)));
} }