Start splitting win32::init into multiple functions

This commit is contained in:
Pierre Krieger 2015-02-16 11:46:18 +01:00
parent 40591806dc
commit 353567b216

View file

@ -1,7 +1,10 @@
use std::sync::atomic::AtomicBool;
use std::ptr;
use std::mem;
use std::os;
use super::callback;
use super::Window;
use super::MonitorID;
use BuilderAttribs;
use CreationError;
use CreationError::OsError;
@ -23,9 +26,6 @@ unsafe impl Send for ContextHack {}
pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<ContextHack>)
-> Result<Window, CreationError>
{
use std::mem;
use std::os;
// initializing variables to be sent to the task
let title = builder.title.as_slice().utf16_units()
.chain(Some(0).into_iter()).collect::<Vec<u16>>(); // title to utf16
@ -36,36 +36,39 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
// so we create a new thread dedicated to this window.
// This is the only safe method. Using `nosend` wouldn't work for non-native runtime.
::std::thread::Thread::spawn(move || {
// sending
match init(title, builder, builder_sharelists) {
Ok(w) => tx.send(Ok(w)).ok(),
Err(e) => {
tx.send(Err(e)).ok();
return;
}
};
// now that the `Window` struct is initialized, the main `Window::new()` function will
// return and this events loop will run in parallel
loop {
let mut msg = unsafe { mem::uninitialized() };
if unsafe { user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) } == 0 {
break;
}
unsafe { user32::TranslateMessage(&msg) };
unsafe { user32::DispatchMessageW(&msg) }; // calls `callback` (see below)
}
});
rx.recv().unwrap()
}
fn init(title: Vec<u16>, builder: BuilderAttribs<'static>, builder_sharelists: Option<ContextHack>)
-> Result<Window, CreationError>
{
let builder_sharelists = builder_sharelists.map(|s| s.0);
// registering the window class
let class_name = {
let class_name: Vec<u16> = "Window Class".utf16_units().chain(Some(0).into_iter())
.collect::<Vec<u16>>();
let class = winapi::WNDCLASSEXW {
cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT,
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: callback::callback,
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: unsafe { kernel32::GetModuleHandleW(ptr::null()) },
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::null_mut(),
};
// We ignore errors because registering the same window class twice would trigger
// 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
// call to fail.
unsafe { user32::RegisterClassExW(&class) };
class_name
};
let class_name = register_window_class();
// building a RECT object with coordinates
let mut rect = winapi::RECT {
@ -78,31 +81,7 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
// and change the monitor's resolution if necessary
if builder.monitor.is_some() {
let monitor = builder.monitor.as_ref().unwrap();
// adjusting the rect
{
let pos = monitor.get_position();
rect.left += pos.0 as winapi::LONG;
rect.right += pos.0 as winapi::LONG;
rect.top += pos.1 as winapi::LONG;
rect.bottom += pos.1 as winapi::LONG;
}
// changing device settings
let mut screen_settings: winapi::DEVMODEW = unsafe { mem::zeroed() };
screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD;
screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD;
screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD;
screen_settings.dmBitsPerPel = 32; // TODO: ?
screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT;
let result = unsafe { user32::ChangeDisplaySettingsExW(monitor.get_system_name().as_ptr(),
&mut screen_settings, ptr::null_mut(), winapi::CDS_FULLSCREEN, ptr::null_mut()) };
if result != winapi::DISP_CHANGE_SUCCESSFUL {
tx.send(Err(OsError(format!("ChangeDisplaySettings failed: {}", result))));
return;
}
switch_to_fullscreen(&mut rect, monitor);
}
// computing the style and extended style of the window
@ -130,10 +109,8 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
ptr::null_mut());
if handle.is_null() {
use std::os;
tx.send(Err(OsError(format!("CreateWindowEx function failed: {}",
os::error_string(os::errno() as usize)))));
return;
return Err(OsError(format!("CreateWindowEx function failed: {}",
os::error_string(os::errno() as usize))));
}
handle
@ -143,10 +120,10 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
let dummy_hdc = {
let hdc = unsafe { user32::GetDC(dummy_window) };
if hdc.is_null() {
tx.send(Err(OsError(format!("GetDC function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("GetDC function failed: {}",
os::error_string(os::errno() as usize))));
unsafe { user32::DestroyWindow(dummy_window); }
return;
return err;
}
hdc
};
@ -171,19 +148,19 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
let pf_index = unsafe { gdi32::ChoosePixelFormat(dummy_hdc, &output) };
if pf_index == 0 {
tx.send(Err(OsError(format!("ChoosePixelFormat function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("ChoosePixelFormat function failed: {}",
os::error_string(os::errno() as usize))));
unsafe { user32::DestroyWindow(dummy_window); }
return;
return err;
}
if unsafe { gdi32::DescribePixelFormat(dummy_hdc, pf_index,
mem::size_of::<winapi::PIXELFORMATDESCRIPTOR>() as winapi::UINT, &mut output) } == 0
{
tx.send(Err(OsError(format!("DescribePixelFormat function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("DescribePixelFormat function failed: {}",
os::error_string(os::errno() as usize))));
unsafe { user32::DestroyWindow(dummy_window); }
return;
return err;
}
output
@ -192,10 +169,10 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
// calling SetPixelFormat
unsafe {
if gdi32::SetPixelFormat(dummy_hdc, 1, &pixel_format) == 0 {
tx.send(Err(OsError(format!("SetPixelFormat function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("SetPixelFormat function failed: {}",
os::error_string(os::errno() as usize))));
user32::DestroyWindow(dummy_window);
return;
return err;
}
}
@ -203,10 +180,10 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
let dummy_context = {
let ctxt = unsafe { gl::wgl::CreateContext(dummy_hdc as *const libc::c_void) };
if ctxt.is_null() {
tx.send(Err(OsError(format!("wglCreateContext function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("wglCreateContext function failed: {}",
os::error_string(os::errno() as usize))));
unsafe { user32::DestroyWindow(dummy_window); }
return;
return err;
}
ctxt
};
@ -261,10 +238,8 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
ptr::null_mut());
if handle.is_null() {
use std::os;
tx.send(Err(OsError(format!("CreateWindowEx function failed: {}",
os::error_string(os::errno() as usize)))));
return;
return Err(OsError(format!("CreateWindowEx function failed: {}",
os::error_string(os::errno() as usize))));
}
handle
@ -274,10 +249,10 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
let hdc = {
let hdc = unsafe { user32::GetDC(real_window) };
if hdc.is_null() {
tx.send(Err(OsError(format!("GetDC function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("GetDC function failed: {}",
os::error_string(os::errno() as usize))));
unsafe { user32::DestroyWindow(real_window); }
return;
return err;
}
hdc
};
@ -285,10 +260,10 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
// calling SetPixelFormat
unsafe {
if gdi32::SetPixelFormat(hdc, 1, &pixel_format) == 0 {
tx.send(Err(OsError(format!("SetPixelFormat function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("SetPixelFormat function failed: {}",
os::error_string(os::errno() as usize))));
user32::DestroyWindow(real_window);
return;
return err;
}
}
@ -330,10 +305,10 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
};
if ctxt.is_null() {
tx.send(Err(OsError(format!("OpenGL context creation failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("OpenGL context creation failed: {}",
os::error_string(os::errno() as usize))));
unsafe { user32::DestroyWindow(real_window); }
return;
return err;
}
ctxt
@ -360,11 +335,11 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
.collect::<Vec<u16>>().as_ptr();
let lib = unsafe { kernel32::LoadLibraryW(name) };
if lib.is_null() {
tx.send(Err(OsError(format!("LoadLibrary function failed: {}",
os::error_string(os::errno() as usize)))));
let err = Err(OsError(format!("LoadLibrary function failed: {}",
os::error_string(os::errno() as usize))));
unsafe { gl::wgl::DeleteContext(context); }
unsafe { user32::DestroyWindow(real_window); }
return;
return err;
}
lib
};
@ -374,10 +349,9 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
if extra_functions.SwapIntervalEXT.is_loaded() {
unsafe { gl::wgl::MakeCurrent(hdc as *const libc::c_void, context) };
if unsafe { extra_functions.SwapIntervalEXT(1) } == 0 {
tx.send(Err(OsError(format!("wglSwapIntervalEXT failed"))));
unsafe { gl::wgl::DeleteContext(context); }
unsafe { user32::DestroyWindow(real_window); }
return;
return Err(OsError(format!("wglSwapIntervalEXT failed")));
}
// it is important to remove the current context, otherwise you get very weird
@ -387,31 +361,68 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<C
}
// building the struct
let window = Window{
Ok(Window {
window: real_window,
hdc: hdc as winapi::HDC,
context: context as winapi::HGLRC,
gl_library: gl_library,
events_receiver: events_receiver,
is_closed: AtomicBool::new(false),
})
}
fn register_window_class() -> Vec<u16> {
let class_name: Vec<u16> = "Window Class".utf16_units().chain(Some(0).into_iter())
.collect::<Vec<u16>>();
let class = winapi::WNDCLASSEXW {
cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT,
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: callback::callback,
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: unsafe { kernel32::GetModuleHandleW(ptr::null()) },
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::null_mut(),
};
// sending
tx.send(Ok(window));
// We ignore errors because registering the same window class twice would trigger
// 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
// call to fail.
unsafe { user32::RegisterClassExW(&class) };
// now that the `Window` struct is initialized, the main `Window::new()` function will
// return and this events loop will run in parallel
loop {
let mut msg = unsafe { mem::uninitialized() };
if unsafe { user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) } == 0 {
break;
}
unsafe { user32::TranslateMessage(&msg) };
unsafe { user32::DispatchMessageW(&msg) }; // calls `callback` (see below)
}
});
rx.recv().unwrap()
class_name
}
fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorID) -> Result<(), CreationError> {
// adjusting the rect
{
let pos = monitor.get_position();
rect.left += pos.0 as winapi::LONG;
rect.right += pos.0 as winapi::LONG;
rect.top += pos.1 as winapi::LONG;
rect.bottom += pos.1 as winapi::LONG;
}
// changing device settings
let mut screen_settings: winapi::DEVMODEW = unsafe { mem::zeroed() };
screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD;
screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD;
screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD;
screen_settings.dmBitsPerPel = 32; // TODO: ?
screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT;
let result = unsafe { user32::ChangeDisplaySettingsExW(monitor.get_system_name().as_ptr(),
&mut screen_settings, ptr::null_mut(), winapi::CDS_FULLSCREEN, ptr::null_mut()) };
if result != winapi::DISP_CHANGE_SUCCESSFUL {
return Err(OsError(format!("ChangeDisplaySettings failed: {}", result)));
}
Ok(())
}