Put GetMessage in the same thread as the window creation.

Fixes #6
This commit is contained in:
Tomaka17 2014-07-31 20:55:30 +02:00
parent 91b0eeae8d
commit fd20346829
2 changed files with 201 additions and 186 deletions

View file

@ -1,6 +1,8 @@
use std::kinds::marker::NoSend; extern crate native;
use self::native::NativeTaskBuilder;
use std::task::TaskBuilder;
use std::sync::atomics::AtomicBool; use std::sync::atomics::AtomicBool;
use std::sync::Mutex;
use std::ptr; use std::ptr;
use super::{event, ffi}; use super::{event, ffi};
use super::{MonitorID, Window}; use super::{MonitorID, Window};
@ -8,7 +10,7 @@ use {Event, Hints};
/// Stores the list of all the windows. /// Stores the list of all the windows.
/// Only available on callback thread. /// Only available on callback thread.
local_data_key!(pub WINDOWS_LIST: Mutex<Vec<(ffi::HWND, Sender<Event>)>>) local_data_key!(WINDOW: (ffi::HWND, Sender<Event>))
pub fn new_window(dimensions: Option<(uint, uint)>, title: &str, pub fn new_window(dimensions: Option<(uint, uint)>, title: &str,
_hints: &Hints, monitor: Option<MonitorID>) _hints: &Hints, monitor: Option<MonitorID>)
@ -17,190 +19,215 @@ pub fn new_window(dimensions: Option<(uint, uint)>, title: &str,
use std::mem; use std::mem;
use std::os; use std::os;
// initializing WINDOWS_LIST if needed let title = title.to_string();
// this is safe because WINDOWS_LIST is task-local //let hints = hints.clone();
if WINDOWS_LIST.get().is_none() {
WINDOWS_LIST.replace(Some(Mutex::new(Vec::new())));
}
// registering the window class let (tx, rx) = channel();
let class_name: Vec<u16> = "Window Class".utf16_units().collect::<Vec<u16>>()
.append_one(0);
let class = ffi::WNDCLASSEX { TaskBuilder::new().native().spawn(proc() {
cbSize: mem::size_of::<ffi::WNDCLASSEX>() as ffi::UINT, // registering the window class
style: ffi::CS_HREDRAW | ffi::CS_VREDRAW, let class_name: Vec<u16> = "Window Class".utf16_units().collect::<Vec<u16>>()
lpfnWndProc: callback, .append_one(0);
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: unsafe { ffi::GetModuleHandleW(ptr::null()) },
hIcon: ptr::mut_null(),
hCursor: ptr::mut_null(),
hbrBackground: ptr::mut_null(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::mut_null(),
};
if unsafe { ffi::RegisterClassExW(&class) } == 0 { let class = ffi::WNDCLASSEX {
use std::os; cbSize: mem::size_of::<ffi::WNDCLASSEX>() as ffi::UINT,
return Err(format!("RegisterClassEx function failed: {}", style: ffi::CS_HREDRAW | ffi::CS_VREDRAW,
os::error_string(os::errno() as uint))) lpfnWndProc: callback,
} cbClsExtra: 0,
cbWndExtra: 0,
hInstance: unsafe { ffi::GetModuleHandleW(ptr::null()) },
hIcon: ptr::mut_null(),
hCursor: ptr::mut_null(),
hbrBackground: ptr::mut_null(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::mut_null(),
};
// building a RECT object with coordinates if unsafe { ffi::RegisterClassExW(&class) } == 0 {
let mut rect = ffi::RECT {
left: 0, right: dimensions.map(|(w, _)| w as ffi::LONG).unwrap_or(1024),
top: 0, bottom: dimensions.map(|(_, h)| h as ffi::LONG).unwrap_or(768),
};
// switching to fullscreen
if monitor.is_some() {
let monitor = monitor.as_ref().unwrap();
// adjusting the rect
{
let pos = monitor.get_position();
rect.left += pos.val0() as ffi::LONG;
rect.right += pos.val0() as ffi::LONG;
rect.top += pos.val1() as ffi::LONG;
rect.bottom += pos.val1() as ffi::LONG;
}
// changing device settings
let mut screen_settings: ffi::DEVMODE = unsafe { mem::zeroed() };
screen_settings.dmSize = mem::size_of::<ffi::DEVMODE>() as ffi::WORD;
screen_settings.dmPelsWidth = 1024;
screen_settings.dmPelsHeight = 768;
screen_settings.dmBitsPerPel = 32;
screen_settings.dmFields = ffi::DM_BITSPERPEL | ffi::DM_PELSWIDTH | ffi::DM_PELSHEIGHT;
let result = unsafe { ffi::ChangeDisplaySettingsExW(monitor.get_system_name().as_ptr(),
&mut screen_settings, ptr::mut_null(), ffi::CDS_FULLSCREEN, ptr::mut_null()) };
if result != ffi::DISP_CHANGE_SUCCESSFUL {
return Err(format!("ChangeDisplaySettings failed: {}", result))
}
}
// computing the style and extended style
let (ex_style, style) = if monitor.is_some() {
(ffi::WS_EX_APPWINDOW, ffi::WS_POPUP | ffi::WS_CLIPSIBLINGS | ffi::WS_CLIPCHILDREN)
} else {
(ffi::WS_EX_APPWINDOW | ffi::WS_EX_WINDOWEDGE,
ffi::WS_OVERLAPPEDWINDOW | ffi::WS_CLIPSIBLINGS | ffi::WS_CLIPCHILDREN)
};
// adjusting
unsafe { ffi::AdjustWindowRectEx(&mut rect, style, 0, ex_style) };
// creating the window
let handle = unsafe {
let handle = ffi::CreateWindowExW(ex_style, class_name.as_ptr(),
title.utf16_units().collect::<Vec<u16>>().append_one(0).as_ptr() as ffi::LPCWSTR,
style | ffi::WS_VISIBLE | ffi::WS_CLIPSIBLINGS | ffi::WS_CLIPCHILDREN,
if monitor.is_some() { 0 } else { ffi::CW_USEDEFAULT},
if monitor.is_some() { 0 } else { ffi::CW_USEDEFAULT},
rect.right - rect.left, rect.bottom - rect.top,
ptr::mut_null(), ptr::mut_null(), ffi::GetModuleHandleW(ptr::null()),
ptr::mut_null());
if handle.is_null() {
use std::os; use std::os;
return Err(format!("CreateWindowEx function failed: {}", tx.send(Err(format!("RegisterClassEx function failed: {}",
os::error_string(os::errno() as uint))) os::error_string(os::errno() as uint))));
return;
} }
handle // building a RECT object with coordinates
}; let mut rect = ffi::RECT {
left: 0, right: dimensions.map(|(w, _)| w as ffi::LONG).unwrap_or(1024),
top: 0, bottom: dimensions.map(|(_, h)| h as ffi::LONG).unwrap_or(768),
};
// calling SetForegroundWindow if fullscreen // switching to fullscreen
if monitor.is_some() { if monitor.is_some() {
unsafe { ffi::SetForegroundWindow(handle) }; let monitor = monitor.as_ref().unwrap();
}
// adding it to WINDOWS_LIST // adjusting the rect
let events_receiver = { {
let (tx, rx) = channel(); let pos = monitor.get_position();
let list = WINDOWS_LIST.get().unwrap(); rect.left += pos.val0() as ffi::LONG;
let mut list = list.lock(); rect.right += pos.val0() as ffi::LONG;
list.push((handle, tx)); rect.top += pos.val1() as ffi::LONG;
rx rect.bottom += pos.val1() as ffi::LONG;
}; }
// Getting the HDC of the window // changing device settings
let hdc = { let mut screen_settings: ffi::DEVMODE = unsafe { mem::zeroed() };
let hdc = unsafe { ffi::GetDC(handle) }; screen_settings.dmSize = mem::size_of::<ffi::DEVMODE>() as ffi::WORD;
if hdc.is_null() { screen_settings.dmPelsWidth = 1024;
return Err(format!("GetDC function failed: {}", screen_settings.dmPelsHeight = 768;
os::error_string(os::errno() as uint))) screen_settings.dmBitsPerPel = 32;
} screen_settings.dmFields = ffi::DM_BITSPERPEL | ffi::DM_PELSWIDTH | ffi::DM_PELSHEIGHT;
hdc
};
// getting the pixel format that we will use let result = unsafe { ffi::ChangeDisplaySettingsExW(monitor.get_system_name().as_ptr(),
// TODO: use something cleaner which uses hints &mut screen_settings, ptr::mut_null(), ffi::CDS_FULLSCREEN, ptr::mut_null()) };
let pixel_format = { if result != ffi::DISP_CHANGE_SUCCESSFUL {
let mut output: ffi::PIXELFORMATDESCRIPTOR = unsafe { mem::uninitialized() }; tx.send(Err(format!("ChangeDisplaySettings failed: {}", result)));
return;
if unsafe { ffi::DescribePixelFormat(hdc, 1, }
mem::size_of::<ffi::PIXELFORMATDESCRIPTOR>() as ffi::UINT, &mut output) } == 0
{
return Err(format!("DescribePixelFormat function failed: {}",
os::error_string(os::errno() as uint)))
} }
output // computing the style and extended style
}; let (ex_style, style) = if monitor.is_some() {
(ffi::WS_EX_APPWINDOW, ffi::WS_POPUP | ffi::WS_CLIPSIBLINGS | ffi::WS_CLIPCHILDREN)
} else {
(ffi::WS_EX_APPWINDOW | ffi::WS_EX_WINDOWEDGE,
ffi::WS_OVERLAPPEDWINDOW | ffi::WS_CLIPSIBLINGS | ffi::WS_CLIPCHILDREN)
};
// calling SetPixelFormat // adjusting
unsafe { unsafe { ffi::AdjustWindowRectEx(&mut rect, style, 0, ex_style) };
if ffi::SetPixelFormat(hdc, 1, &pixel_format) == 0 {
return Err(format!("SetPixelFormat function failed: {}", // creating the window
os::error_string(os::errno() as uint))) let handle = unsafe {
let handle = ffi::CreateWindowExW(ex_style, class_name.as_ptr(),
title.as_slice().utf16_units().collect::<Vec<u16>>().append_one(0).as_ptr() as ffi::LPCWSTR,
style | ffi::WS_VISIBLE | ffi::WS_CLIPSIBLINGS | ffi::WS_CLIPCHILDREN,
if monitor.is_some() { 0 } else { ffi::CW_USEDEFAULT},
if monitor.is_some() { 0 } else { ffi::CW_USEDEFAULT},
rect.right - rect.left, rect.bottom - rect.top,
ptr::mut_null(), ptr::mut_null(), ffi::GetModuleHandleW(ptr::null()),
ptr::mut_null());
if handle.is_null() {
use std::os;
tx.send(Err(format!("CreateWindowEx function failed: {}",
os::error_string(os::errno() as uint))));
return;
}
handle
};
// calling SetForegroundWindow if fullscreen
if monitor.is_some() {
unsafe { ffi::SetForegroundWindow(handle) };
} }
}
// creating the context // adding it to WINDOWS_LIST
let context = { let events_receiver = {
let ctxt = unsafe { ffi::wglCreateContext(hdc) }; let (tx, rx) = channel();
if ctxt.is_null() { WINDOW.replace(Some((handle, tx)));
return Err(format!("wglCreateContext function failed: {}", rx
os::error_string(os::errno() as uint))) };
// Getting the HDC of the window
let hdc = {
let hdc = unsafe { ffi::GetDC(handle) };
if hdc.is_null() {
tx.send(Err(format!("GetDC function failed: {}",
os::error_string(os::errno() as uint))));
return;
}
hdc
};
// getting the pixel format that we will use
// TODO: use something cleaner which uses hints
let pixel_format = {
let mut output: ffi::PIXELFORMATDESCRIPTOR = unsafe { mem::uninitialized() };
if unsafe { ffi::DescribePixelFormat(hdc, 1,
mem::size_of::<ffi::PIXELFORMATDESCRIPTOR>() as ffi::UINT, &mut output) } == 0
{
tx.send(Err(format!("DescribePixelFormat function failed: {}",
os::error_string(os::errno() as uint))));
return;
}
output
};
// calling SetPixelFormat
unsafe {
if ffi::SetPixelFormat(hdc, 1, &pixel_format) == 0 {
tx.send(Err(format!("SetPixelFormat function failed: {}",
os::error_string(os::errno() as uint))));
return;
}
} }
ctxt
};
// loading opengl32 // creating the context
let gl_library = { let context = {
let name = "opengl32.dll".utf16_units().collect::<Vec<u16>>().append_one(0).as_ptr(); let ctxt = unsafe { ffi::wglCreateContext(hdc) };
let lib = unsafe { ffi::LoadLibraryW(name) }; if ctxt.is_null() {
if lib.is_null() { tx.send(Err(format!("wglCreateContext function failed: {}",
return Err(format!("LoadLibrary function failed: {}", os::error_string(os::errno() as uint))));
os::error_string(os::errno() as uint))) return;
}
ctxt
};
// loading opengl32
let gl_library = {
let name = "opengl32.dll".utf16_units().collect::<Vec<u16>>().append_one(0).as_ptr();
let lib = unsafe { ffi::LoadLibraryW(name) };
if lib.is_null() {
tx.send(Err(format!("LoadLibrary function failed: {}",
os::error_string(os::errno() as uint))));
return;
}
lib
};
// building the struct
tx.send(Ok(Window{
window: handle,
hdc: hdc,
context: context,
gl_library: gl_library,
events_receiver: events_receiver,
is_closed: AtomicBool::new(false),
}));
// starting the events loop
loop {
let mut msg = unsafe { mem::uninitialized() };
if unsafe { ffi::GetMessageW(&mut msg, ptr::mut_null(), 0, 0) } == 0 {
break
}
unsafe { ffi::TranslateMessage(&msg) };
unsafe { ffi::DispatchMessageW(&msg) };
} }
lib });
};
// building the struct rx.recv()
Ok(Window{
window: handle,
hdc: hdc,
context: context,
gl_library: gl_library,
events_receiver: events_receiver,
is_closed: AtomicBool::new(false),
nosend: NoSend,
})
} }
fn send_event(window: ffi::HWND, event: Event) { fn send_event(window: ffi::HWND, event: Event) {
let locked = WINDOWS_LIST.get().unwrap(); let stored = match WINDOW.get() {
let mut locked = locked.lock(); None => return,
locked.retain(|&(ref val, ref sender)| { Some(v) => v
if val != &window { return true } };
sender.send_opt(event).is_ok() let &(ref win, ref sender) = stored.deref();
});
if win != &window {
return;
}
sender.send_opt(event).ok(); // ignoring if closed
} }
extern "stdcall" fn callback(window: ffi::HWND, msg: ffi::UINT, extern "stdcall" fn callback(window: ffi::HWND, msg: ffi::UINT,

View file

@ -1,10 +1,8 @@
use std::kinds::marker::NoSend;
use std::sync::atomics::AtomicBool; use std::sync::atomics::AtomicBool;
use std::ptr; use std::ptr;
use {Event, Hints}; use {Event, Hints};
pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor};
pub use self::init::WINDOWS_LIST;
mod event; mod event;
mod ffi; mod ffi;
@ -18,7 +16,6 @@ pub struct Window {
gl_library: ffi::HMODULE, gl_library: ffi::HMODULE,
events_receiver: Receiver<Event>, events_receiver: Receiver<Event>,
is_closed: AtomicBool, is_closed: AtomicBool,
nosend: NoSend,
} }
impl Window { impl Window {
@ -106,19 +103,6 @@ impl Window {
// TODO: return iterator // TODO: return iterator
pub fn poll_events(&self) -> Vec<Event> { pub fn poll_events(&self) -> Vec<Event> {
use std::mem;
loop {
let mut msg = unsafe { mem::uninitialized() };
if unsafe { ffi::PeekMessageW(&mut msg, ptr::mut_null(), 0, 0, 0x1) } == 0 {
break
}
unsafe { ffi::TranslateMessage(&msg) };
unsafe { ffi::DispatchMessageW(&msg) };
}
let mut events = Vec::new(); let mut events = Vec::new();
loop { loop {
match self.events_receiver.try_recv() { match self.events_receiver.try_recv() {
@ -137,12 +121,16 @@ impl Window {
// TODO: return iterator // TODO: return iterator
pub fn wait_events(&self) -> Vec<Event> { pub fn wait_events(&self) -> Vec<Event> {
loop { match self.events_receiver.recv_opt() {
unsafe { ffi::WaitMessage() }; Ok(ev) => {
let mut result = self.poll_events();
let events = self.poll_events(); result.insert(0, ev);
if events.len() >= 1 { result
return events },
Err(_) => {
use std::sync::atomics::Relaxed;
self.is_closed.store(true, Relaxed);
vec![]
} }
} }
} }