From 36619ee40ebc1a22ec8979b34a5aca27b0cf8975 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Sun, 1 Mar 2015 13:14:58 +0100 Subject: Mark functions as unsafe instead of having a lot of blocks --- src/win32/init.rs | 169 +++++++++++++++++++++++++++--------------------------- 1 file changed, 84 insertions(+), 85 deletions(-) (limited to 'src') diff --git a/src/win32/init.rs b/src/win32/init.rs index 260b0ab..13da111 100644 --- a/src/win32/init.rs +++ b/src/win32/init.rs @@ -40,34 +40,36 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option tx.send(Ok(w)).ok(), - Err(e) => { - tx.send(Err(e)).ok(); - return; + unsafe { + // 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 = mem::uninitialized(); + + if user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 { + break; + } + + user32::TranslateMessage(&msg); + user32::DispatchMessageW(&msg); // calls `callback` (see below) } - }; - - // 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, builder: BuilderAttribs<'static>, builder_sharelists: Option) - -> Result +unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, + builder_sharelists: Option) -> Result { let builder_sharelists = builder_sharelists.map(|s| s.0); @@ -85,7 +87,7 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O // and change the monitor's resolution if necessary if builder.monitor.is_some() { let monitor = builder.monitor.as_ref().unwrap(); - switch_to_fullscreen(&mut rect, monitor); + try!(switch_to_fullscreen(&mut rect, monitor)); } // computing the style and extended style of the window @@ -97,12 +99,12 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O }; // adjusting the window coordinates using the style - unsafe { user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style) }; + user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style); // getting the address of wglCreateContextAttribsARB let extra_functions = { // creating a dummy invisible window for GL initialization - let dummy_window = unsafe { + let dummy_window = { let handle = user32::CreateWindowExW(ex_style, class_name.as_ptr(), title.as_ptr() as winapi::LPCWSTR, style | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN, @@ -121,11 +123,11 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O // getting the HDC of the dummy window let dummy_hdc = { - let hdc = unsafe { user32::GetDC(dummy_window) }; + let hdc = user32::GetDC(dummy_window); if hdc.is_null() { let err = Err(OsError(format!("GetDC function failed: {}", os::error_string(os::errno())))); - unsafe { user32::DestroyWindow(dummy_window); } + user32::DestroyWindow(dummy_window); return err; } hdc @@ -142,7 +144,8 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O let dummy_context = try!(create_context(None, dummy_hdc, None)); // making context current - unsafe { gl::wgl::MakeCurrent(dummy_hdc as *const libc::c_void, dummy_context as *const libc::c_void); } + gl::wgl::MakeCurrent(dummy_hdc as *const libc::c_void, + dummy_context as *const libc::c_void); // loading the extra WGL functions let extra_functions = gl::wgl_extra::Wgl::load_with(|addr| { @@ -151,24 +154,22 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O let addr = CString::from_slice(addr.as_bytes()); let addr = addr.as_ptr(); - unsafe { - gl::wgl::GetProcAddress(addr) as *const libc::c_void - } + gl::wgl::GetProcAddress(addr) as *const libc::c_void }); // removing current context - unsafe { gl::wgl::MakeCurrent(ptr::null(), ptr::null()); } + gl::wgl::MakeCurrent(ptr::null(), ptr::null()); // destroying the context and the window - unsafe { gl::wgl::DeleteContext(dummy_context as *const libc::c_void); } - unsafe { user32::DestroyWindow(dummy_window); } + gl::wgl::DeleteContext(dummy_context as *const libc::c_void); + user32::DestroyWindow(dummy_window); // returning the address extra_functions }; // creating the real window this time - let real_window = unsafe { + let real_window = { let (width, height) = if builder.monitor.is_some() || builder.dimensions.is_some() { (Some(rect.right - rect.left), Some(rect.bottom - rect.top)) } else { @@ -192,7 +193,7 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O if handle.is_null() { return Err(OsError(format!("CreateWindowEx function failed: {}", - os::error_string(os::errno())))); + os::error_string(os::errno())))); } handle @@ -200,11 +201,11 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O // getting the HDC of the window let hdc = { - let hdc = unsafe { user32::GetDC(real_window) }; + let hdc = user32::GetDC(real_window); if hdc.is_null() { let err = Err(OsError(format!("GetDC function failed: {}", - os::error_string(os::errno())))); - unsafe { user32::DestroyWindow(real_window); } + os::error_string(os::errno())))); + user32::DestroyWindow(real_window); return err; } hdc @@ -227,7 +228,7 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O // calling SetForegroundWindow if fullscreen if builder.monitor.is_some() { - unsafe { user32::SetForegroundWindow(real_window) }; + user32::SetForegroundWindow(real_window); } // filling the WINDOW task-local storage @@ -246,16 +247,16 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O // handling vsync if builder.vsync { if extra_functions.SwapIntervalEXT.is_loaded() { - unsafe { gl::wgl::MakeCurrent(hdc as *const libc::c_void, context as *const libc::c_void) }; - if unsafe { extra_functions.SwapIntervalEXT(1) } == 0 { - unsafe { gl::wgl::DeleteContext(context as *const libc::c_void); } - unsafe { user32::DestroyWindow(real_window); } + gl::wgl::MakeCurrent(hdc as *const libc::c_void, context as *const libc::c_void); + if extra_functions.SwapIntervalEXT(1) == 0 { + gl::wgl::DeleteContext(context as *const libc::c_void); + user32::DestroyWindow(real_window); return Err(OsError(format!("wglSwapIntervalEXT failed"))); } // it is important to remove the current context, otherwise you get very weird // errors - unsafe { gl::wgl::MakeCurrent(ptr::null(), ptr::null()); } + gl::wgl::MakeCurrent(ptr::null(), ptr::null()); } } @@ -270,7 +271,7 @@ fn init(title: Vec, builder: BuilderAttribs<'static>, builder_sharelists: O }) } -fn register_window_class() -> Vec { +unsafe fn register_window_class() -> Vec { let class_name: Vec = "Window Class".utf16_units().chain(Some(0).into_iter()) .collect::>(); @@ -280,7 +281,7 @@ fn register_window_class() -> Vec { lpfnWndProc: Some(callback::callback), cbClsExtra: 0, cbWndExtra: 0, - hInstance: unsafe { kernel32::GetModuleHandleW(ptr::null()) }, + hInstance: kernel32::GetModuleHandleW(ptr::null()), hIcon: ptr::null_mut(), hCursor: ptr::null_mut(), hbrBackground: ptr::null_mut(), @@ -293,12 +294,14 @@ fn register_window_class() -> Vec { // 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) }; + user32::RegisterClassExW(&class); class_name } -fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorID) -> Result<(), CreationError> { +unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorID) + -> Result<(), CreationError> +{ // adjusting the rect { let pos = monitor.get_position(); @@ -309,15 +312,16 @@ fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorID) -> Result< } // changing device settings - let mut screen_settings: winapi::DEVMODEW = unsafe { mem::zeroed() }; + let mut screen_settings: winapi::DEVMODEW = mem::zeroed(); screen_settings.dmSize = mem::size_of::() 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()) }; + let result = 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))); @@ -326,9 +330,9 @@ fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorID) -> Result< Ok(()) } -fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>)>, - hdc: winapi::HDC, share: Option) - -> Result +unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>)>, + hdc: winapi::HDC, share: Option) + -> Result { let share = share.unwrap_or(ptr::null_mut()); @@ -360,11 +364,10 @@ fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>)> attributes.push(0); - Some(unsafe { - extra_functions.CreateContextAttribsARB(hdc as *const libc::c_void, - share as *const libc::c_void, - attributes.as_slice().as_ptr()) - }) + Some(extra_functions.CreateContextAttribsARB(hdc as *const libc::c_void, + share as *const libc::c_void, + attributes.as_slice().as_ptr())) + } else { None } @@ -375,13 +378,11 @@ fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>)> let ctxt = match ctxt { Some(ctxt) => ctxt, None => { - unsafe { - let ctxt = gl::wgl::CreateContext(hdc as *const libc::c_void); - if !ctxt.is_null() && !share.is_null() { - gl::wgl::ShareLists(share as *const libc::c_void, ctxt); - }; - ctxt - } + let ctxt = gl::wgl::CreateContext(hdc as *const libc::c_void); + if !ctxt.is_null() && !share.is_null() { + gl::wgl::ShareLists(share as *const libc::c_void, ctxt); + }; + ctxt } }; @@ -393,18 +394,16 @@ fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>)> Ok(ctxt as winapi::HGLRC) } -fn enumerate_native_pixel_formats(hdc: winapi::HDC) -> Vec<(PixelFormat, libc::c_int)> { +unsafe fn enumerate_native_pixel_formats(hdc: winapi::HDC) -> Vec<(PixelFormat, libc::c_int)> { let size_of_pxfmtdescr = mem::size_of::() as u32; - let num = unsafe { gdi32::DescribePixelFormat(hdc, 1, size_of_pxfmtdescr, ptr::null_mut()) }; + let num = gdi32::DescribePixelFormat(hdc, 1, size_of_pxfmtdescr, ptr::null_mut()); let mut result = Vec::new(); for index in (0 .. num) { - let mut output: winapi::PIXELFORMATDESCRIPTOR = unsafe { mem::zeroed() }; + let mut output: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed(); - if unsafe { gdi32::DescribePixelFormat(hdc, index, size_of_pxfmtdescr, - &mut output) } == 0 - { + if gdi32::DescribePixelFormat(hdc, index, size_of_pxfmtdescr, &mut output) == 0 { continue; } @@ -438,14 +437,14 @@ fn enumerate_native_pixel_formats(hdc: winapi::HDC) -> Vec<(PixelFormat, libc::c result } -fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, hdc: winapi::HDC) - -> Vec<(PixelFormat, libc::c_int)> +unsafe fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, hdc: winapi::HDC) + -> Vec<(PixelFormat, libc::c_int)> { let get_info = |index: u32, attrib: u32| { - let mut value = unsafe { mem::uninitialized() }; - unsafe { extra.GetPixelFormatAttribivARB(hdc as *const libc::c_void, index as libc::c_int, - 0, 1, [attrib as libc::c_int].as_ptr(), - &mut value) }; + let mut value = mem::uninitialized(); + extra.GetPixelFormatAttribivARB(hdc as *const libc::c_void, index as libc::c_int, + 0, 1, [attrib as libc::c_int].as_ptr(), + &mut value); value as u32 }; @@ -489,17 +488,17 @@ fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, hdc: winapi::HDC) result } -fn set_pixel_format(hdc: winapi::HDC, id: libc::c_int) -> Result<(), CreationError> { - let mut output: winapi::PIXELFORMATDESCRIPTOR = unsafe { mem::zeroed() }; +unsafe fn set_pixel_format(hdc: winapi::HDC, id: libc::c_int) -> Result<(), CreationError> { + let mut output: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed(); - if unsafe { gdi32::DescribePixelFormat(hdc, id, - mem::size_of::() as winapi::UINT, &mut output) } == 0 + if gdi32::DescribePixelFormat(hdc, id, mem::size_of::() + as winapi::UINT, &mut output) == 0 { return Err(OsError(format!("DescribePixelFormat function failed: {}", os::error_string(os::errno())))); } - if unsafe { gdi32::SetPixelFormat(hdc, id, &output) } == 0 { + if gdi32::SetPixelFormat(hdc, id, &output) == 0 { return Err(OsError(format!("SetPixelFormat function failed: {}", os::error_string(os::errno())))); } @@ -507,11 +506,11 @@ fn set_pixel_format(hdc: winapi::HDC, id: libc::c_int) -> Result<(), CreationErr Ok(()) } -fn load_opengl32_dll() -> Result { +unsafe fn load_opengl32_dll() -> Result { let name = "opengl32.dll".utf16_units().chain(Some(0).into_iter()) .collect::>().as_ptr(); - let lib = unsafe { kernel32::LoadLibraryW(name) }; + let lib = kernel32::LoadLibraryW(name); if lib.is_null() { return Err(OsError(format!("LoadLibrary function failed: {}", -- cgit v1.2.3 From 65d5589e3ccfa4d6425d16a7df186dde9d9ed861 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Sun, 1 Mar 2015 13:18:36 +0100 Subject: Fix various warnings --- src/win32/init.rs | 5 +++-- src/win32/mod.rs | 5 ++--- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/win32/init.rs b/src/win32/init.rs index 13da111..23bb364 100644 --- a/src/win32/init.rs +++ b/src/win32/init.rs @@ -2,6 +2,7 @@ use std::sync::atomic::AtomicBool; use std::ptr; use std::mem; use std::os; +use std::thread; use super::callback; use super::Window; use super::MonitorID; @@ -39,7 +40,7 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option, builder: BuilderAttribs<'static>, let extra_functions = gl::wgl_extra::Wgl::load_with(|addr| { use libc; - let addr = CString::from_slice(addr.as_bytes()); + let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); gl::wgl::GetProcAddress(addr) as *const libc::c_void diff --git a/src/win32/mod.rs b/src/win32/mod.rs index 4846d59..5af2691 100644 --- a/src/win32/mod.rs +++ b/src/win32/mod.rs @@ -191,7 +191,7 @@ impl Window { /// See the docs in the crate root file. pub fn get_proc_address(&self, addr: &str) -> *const () { - let addr = CString::from_slice(addr.as_bytes()); + let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); unsafe { @@ -224,7 +224,7 @@ impl Window { pub fn set_window_resize_callback(&mut self, _: Option) { } - pub fn set_cursor(&self, cursor: MouseCursor) { + pub fn set_cursor(&self, _cursor: MouseCursor) { unimplemented!() } @@ -280,7 +280,6 @@ impl<'a> Iterator for WaitEventsIterator<'a> { #[unsafe_destructor] impl Drop for Window { fn drop(&mut self) { - use std::ptr; // we don't call MakeCurrent(0, 0) because we are not sure that the context // is still the current one unsafe { user32::PostMessageW(self.window, winapi::WM_DESTROY, 0, 0); } -- cgit v1.2.3 From cca23f8544e1f331677c0f9c0f6b255ac8d92d9b Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Sun, 1 Mar 2015 13:41:00 +0100 Subject: Add wrappers for safer error recovery during initialization --- src/win32/init.rs | 93 ++++++++++++++++++++++++------------------------------- src/win32/mod.rs | 76 ++++++++++++++++++++++++++++----------------- 2 files changed, 87 insertions(+), 82 deletions(-) (limited to 'src') diff --git a/src/win32/init.rs b/src/win32/init.rs index 23bb364..f842028 100644 --- a/src/win32/init.rs +++ b/src/win32/init.rs @@ -3,9 +3,12 @@ use std::ptr; use std::mem; use std::os; use std::thread; + use super::callback; use super::Window; use super::MonitorID; +use super::ContextWrapper; +use super::WindowWrapper; use Api; use BuilderAttribs; @@ -116,37 +119,32 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, if handle.is_null() { return Err(OsError(format!("CreateWindowEx function failed: {}", - os::error_string(os::errno())))); + os::error_string(os::errno())))); } - handle - }; - - // getting the HDC of the dummy window - let dummy_hdc = { - let hdc = user32::GetDC(dummy_window); + let hdc = user32::GetDC(handle); if hdc.is_null() { let err = Err(OsError(format!("GetDC function failed: {}", - os::error_string(os::errno())))); - user32::DestroyWindow(dummy_window); + os::error_string(os::errno())))); return err; } - hdc + + WindowWrapper(handle, hdc) }; // getting the pixel format that we will use and setting it { - let formats = enumerate_native_pixel_formats(dummy_hdc); + let formats = enumerate_native_pixel_formats(&dummy_window); let (id, _) = builder.choose_pixel_format(formats.into_iter().map(|(a, b)| (b, a))); - try!(set_pixel_format(dummy_hdc, id)); + try!(set_pixel_format(&dummy_window, id)); } // creating the dummy OpenGL context - let dummy_context = try!(create_context(None, dummy_hdc, None)); + let dummy_context = try!(create_context(None, &dummy_window, None)); // making context current - gl::wgl::MakeCurrent(dummy_hdc as *const libc::c_void, - dummy_context as *const libc::c_void); + gl::wgl::MakeCurrent(dummy_window.1 as *const libc::c_void, + dummy_context.0 as *const libc::c_void); // loading the extra WGL functions let extra_functions = gl::wgl_extra::Wgl::load_with(|addr| { @@ -161,10 +159,6 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, // removing current context gl::wgl::MakeCurrent(ptr::null(), ptr::null()); - // destroying the context and the window - gl::wgl::DeleteContext(dummy_context as *const libc::c_void); - user32::DestroyWindow(dummy_window); - // returning the address extra_functions }; @@ -197,39 +191,34 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, os::error_string(os::errno())))); } - handle - }; - - // getting the HDC of the window - let hdc = { - let hdc = user32::GetDC(real_window); + let hdc = user32::GetDC(handle); if hdc.is_null() { - let err = Err(OsError(format!("GetDC function failed: {}", - os::error_string(os::errno())))); - user32::DestroyWindow(real_window); - return err; + return Err(OsError(format!("GetDC function failed: {}", + os::error_string(os::errno())))); } - hdc + + WindowWrapper(handle, hdc) }; // calling SetPixelFormat { let formats = if extra_functions.GetPixelFormatAttribivARB.is_loaded() { - enumerate_arb_pixel_formats(&extra_functions, hdc) + enumerate_arb_pixel_formats(&extra_functions, &real_window) } else { - enumerate_native_pixel_formats(hdc) + enumerate_native_pixel_formats(&real_window) }; let (id, _) = builder.choose_pixel_format(formats.into_iter().map(|(a, b)| (b, a))); - try!(set_pixel_format(hdc, id)); + try!(set_pixel_format(&real_window, id)); } // creating the OpenGL context - let context = try!(create_context(Some((&extra_functions, &builder)), hdc, builder_sharelists)); + let context = try!(create_context(Some((&extra_functions, &builder)), &real_window, + builder_sharelists)); // calling SetForegroundWindow if fullscreen if builder.monitor.is_some() { - user32::SetForegroundWindow(real_window); + user32::SetForegroundWindow(real_window.0); } // filling the WINDOW task-local storage @@ -237,7 +226,7 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, let (tx, rx) = channel(); let mut tx = Some(tx); callback::WINDOW.with(|window| { - (*window.borrow_mut()) = Some((real_window, tx.take().unwrap())); + (*window.borrow_mut()) = Some((real_window.0, tx.take().unwrap())); }); rx }; @@ -248,10 +237,9 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, // handling vsync if builder.vsync { if extra_functions.SwapIntervalEXT.is_loaded() { - gl::wgl::MakeCurrent(hdc as *const libc::c_void, context as *const libc::c_void); + gl::wgl::MakeCurrent(real_window.1 as *const libc::c_void, + context.0 as *const libc::c_void); if extra_functions.SwapIntervalEXT(1) == 0 { - gl::wgl::DeleteContext(context as *const libc::c_void); - user32::DestroyWindow(real_window); return Err(OsError(format!("wglSwapIntervalEXT failed"))); } @@ -264,7 +252,6 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, // building the struct Ok(Window { window: real_window, - hdc: hdc as winapi::HDC, context: context, gl_library: gl_library, events_receiver: events_receiver, @@ -332,8 +319,8 @@ unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorID) } unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>)>, - hdc: winapi::HDC, share: Option) - -> Result + hdc: &WindowWrapper, share: Option) + -> Result { let share = share.unwrap_or(ptr::null_mut()); @@ -365,7 +352,7 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st attributes.push(0); - Some(extra_functions.CreateContextAttribsARB(hdc as *const libc::c_void, + Some(extra_functions.CreateContextAttribsARB(hdc.1 as *const libc::c_void, share as *const libc::c_void, attributes.as_slice().as_ptr())) @@ -379,7 +366,7 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st let ctxt = match ctxt { Some(ctxt) => ctxt, None => { - let ctxt = gl::wgl::CreateContext(hdc as *const libc::c_void); + let ctxt = gl::wgl::CreateContext(hdc.1 as *const libc::c_void); if !ctxt.is_null() && !share.is_null() { gl::wgl::ShareLists(share as *const libc::c_void, ctxt); }; @@ -392,19 +379,19 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st os::error_string(os::errno())))); } - Ok(ctxt as winapi::HGLRC) + Ok(ContextWrapper(ctxt as winapi::HGLRC)) } -unsafe fn enumerate_native_pixel_formats(hdc: winapi::HDC) -> Vec<(PixelFormat, libc::c_int)> { +unsafe fn enumerate_native_pixel_formats(hdc: &WindowWrapper) -> Vec<(PixelFormat, libc::c_int)> { let size_of_pxfmtdescr = mem::size_of::() as u32; - let num = gdi32::DescribePixelFormat(hdc, 1, size_of_pxfmtdescr, ptr::null_mut()); + let num = gdi32::DescribePixelFormat(hdc.1, 1, size_of_pxfmtdescr, ptr::null_mut()); let mut result = Vec::new(); for index in (0 .. num) { let mut output: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed(); - if gdi32::DescribePixelFormat(hdc, index, size_of_pxfmtdescr, &mut output) == 0 { + if gdi32::DescribePixelFormat(hdc.1, index, size_of_pxfmtdescr, &mut output) == 0 { continue; } @@ -438,12 +425,12 @@ unsafe fn enumerate_native_pixel_formats(hdc: winapi::HDC) -> Vec<(PixelFormat, result } -unsafe fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, hdc: winapi::HDC) +unsafe fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, hdc: &WindowWrapper) -> Vec<(PixelFormat, libc::c_int)> { let get_info = |index: u32, attrib: u32| { let mut value = mem::uninitialized(); - extra.GetPixelFormatAttribivARB(hdc as *const libc::c_void, index as libc::c_int, + extra.GetPixelFormatAttribivARB(hdc.1 as *const libc::c_void, index as libc::c_int, 0, 1, [attrib as libc::c_int].as_ptr(), &mut value); value as u32 @@ -489,17 +476,17 @@ unsafe fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, hdc: winapi::H result } -unsafe fn set_pixel_format(hdc: winapi::HDC, id: libc::c_int) -> Result<(), CreationError> { +unsafe fn set_pixel_format(hdc: &WindowWrapper, id: libc::c_int) -> Result<(), CreationError> { let mut output: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed(); - if gdi32::DescribePixelFormat(hdc, id, mem::size_of::() + if gdi32::DescribePixelFormat(hdc.1, id, mem::size_of::() as winapi::UINT, &mut output) == 0 { return Err(OsError(format!("DescribePixelFormat function failed: {}", os::error_string(os::errno())))); } - if gdi32::SetPixelFormat(hdc, id, &output) == 0 { + if gdi32::SetPixelFormat(hdc.1, id, &output) == 0 { return Err(OsError(format!("SetPixelFormat function failed: {}", os::error_string(os::errno())))); } diff --git a/src/win32/mod.rs b/src/win32/mod.rs index 5af2691..4e6a803 100644 --- a/src/win32/mod.rs +++ b/src/win32/mod.rs @@ -26,13 +26,10 @@ mod monitor; /// The Win32 implementation of the main `Window` object. pub struct Window { /// Main handle for the window. - window: winapi::HWND, - - /// This represents a "draw context" for the surface of the window. - hdc: winapi::HDC, + window: WindowWrapper, /// OpenGL context. - context: winapi::HGLRC, + context: ContextWrapper, /// Binded to `opengl32.dll`. /// @@ -50,12 +47,25 @@ pub struct Window { unsafe impl Send for Window {} unsafe impl Sync for Window {} -impl Window { - /// See the docs in the crate root file. - pub fn new(builder: BuilderAttribs) -> Result { - let (builder, sharing) = builder.extract_non_static(); - let sharing = sharing.map(|w| init::ContextHack(w.context)); - init::new_window(builder, sharing) +/// A simple wrapper that destroys the context when it is destroyed. +struct ContextWrapper(pub winapi::HGLRC); + +impl Drop for ContextWrapper { + fn drop(&mut self) { + unsafe { + gl::wgl::DeleteContext(self.0 as *const libc::c_void); + } + } +} + +/// A simple wrapper that destroys the window when it is destroyed. +struct WindowWrapper(pub winapi::HWND, pub winapi::HDC); + +impl Drop for WindowWrapper { + fn drop(&mut self) { + unsafe { + user32::DestroyWindow(self.0); + } } } @@ -69,6 +79,13 @@ impl WindowProxy { } impl Window { + /// See the docs in the crate root file. + pub fn new(builder: BuilderAttribs) -> Result { + let (builder, sharing) = builder.extract_non_static(); + let sharing = sharing.map(|w| init::ContextHack(w.context.0)); + init::new_window(builder, sharing) + } + /// See the docs in the crate root file. pub fn is_closed(&self) -> bool { use std::sync::atomic::Ordering::Relaxed; @@ -80,7 +97,7 @@ impl Window { /// Calls SetWindowText on the HWND. pub fn set_title(&self, text: &str) { unsafe { - user32::SetWindowTextW(self.window, + user32::SetWindowTextW(self.window.0, text.utf16_units().chain(Some(0).into_iter()) .collect::>().as_ptr() as winapi::LPCWSTR); } @@ -88,13 +105,13 @@ impl Window { pub fn show(&self) { unsafe { - user32::ShowWindow(self.window, winapi::SW_SHOW); + user32::ShowWindow(self.window.0, winapi::SW_SHOW); } } pub fn hide(&self) { unsafe { - user32::ShowWindow(self.window, winapi::SW_HIDE); + user32::ShowWindow(self.window.0, winapi::SW_HIDE); } } @@ -105,7 +122,7 @@ impl Window { let mut placement: winapi::WINDOWPLACEMENT = unsafe { mem::zeroed() }; placement.length = mem::size_of::() as winapi::UINT; - if unsafe { user32::GetWindowPlacement(self.window, &mut placement) } == 0 { + if unsafe { user32::GetWindowPlacement(self.window.0, &mut placement) } == 0 { return None } @@ -118,9 +135,9 @@ impl Window { use libc; unsafe { - user32::SetWindowPos(self.window, ptr::null_mut(), x as libc::c_int, y as libc::c_int, + user32::SetWindowPos(self.window.0, ptr::null_mut(), x as libc::c_int, y as libc::c_int, 0, 0, winapi::SWP_NOZORDER | winapi::SWP_NOSIZE); - user32::UpdateWindow(self.window); + user32::UpdateWindow(self.window.0); } } @@ -129,7 +146,7 @@ impl Window { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; - if unsafe { user32::GetClientRect(self.window, &mut rect) } == 0 { + if unsafe { user32::GetClientRect(self.window.0, &mut rect) } == 0 { return None } @@ -144,7 +161,7 @@ impl Window { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; - if unsafe { user32::GetWindowRect(self.window, &mut rect) } == 0 { + if unsafe { user32::GetWindowRect(self.window.0, &mut rect) } == 0 { return None } @@ -159,9 +176,9 @@ impl Window { use libc; unsafe { - user32::SetWindowPos(self.window, ptr::null_mut(), 0, 0, x as libc::c_int, + user32::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, x as libc::c_int, y as libc::c_int, winapi::SWP_NOZORDER | winapi::SWP_NOREPOSITION); - user32::UpdateWindow(self.window); + user32::UpdateWindow(self.window.0); } } @@ -186,7 +203,8 @@ impl Window { /// See the docs in the crate root file. pub unsafe fn make_current(&self) { // TODO: check return value - gl::wgl::MakeCurrent(self.hdc as *const libc::c_void, self.context as *const libc::c_void); + gl::wgl::MakeCurrent(self.window.1 as *const libc::c_void, + self.context.0 as *const libc::c_void); } /// See the docs in the crate root file. @@ -204,7 +222,7 @@ impl Window { /// See the docs in the crate root file. pub fn swap_buffers(&self) { unsafe { - gdi32::SwapBuffers(self.hdc); + gdi32::SwapBuffers(self.window.1); } } @@ -213,7 +231,7 @@ impl Window { } pub fn platform_window(&self) -> *mut libc::c_void { - self.window as *mut libc::c_void + self.window.0 as *mut libc::c_void } /// See the docs in the crate root file. @@ -280,10 +298,10 @@ impl<'a> Iterator for WaitEventsIterator<'a> { #[unsafe_destructor] impl Drop for Window { fn drop(&mut self) { - // we don't call MakeCurrent(0, 0) because we are not sure that the context - // is still the current one - unsafe { user32::PostMessageW(self.window, winapi::WM_DESTROY, 0, 0); } - unsafe { gl::wgl::DeleteContext(self.context as *const libc::c_void); } - unsafe { user32::DestroyWindow(self.window); } + unsafe { + // we don't call MakeCurrent(0, 0) because we are not sure that the context + // is still the current one + user32::PostMessageW(self.window.0, winapi::WM_DESTROY, 0, 0); + } } } -- cgit v1.2.3 From 4f98ea3128e406e351038646398aed93982bf4c4 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Sun, 1 Mar 2015 13:57:09 +0100 Subject: Add a guard for the calls to MakeCurrent during initialization --- src/win32/init.rs | 23 ++++++------------ src/win32/make_current_guard.rs | 53 +++++++++++++++++++++++++++++++++++++++++ src/win32/mod.rs | 1 + 3 files changed, 61 insertions(+), 16 deletions(-) create mode 100644 src/win32/make_current_guard.rs (limited to 'src') diff --git a/src/win32/init.rs b/src/win32/init.rs index f842028..09d5878 100644 --- a/src/win32/init.rs +++ b/src/win32/init.rs @@ -9,6 +9,7 @@ use super::Window; use super::MonitorID; use super::ContextWrapper; use super::WindowWrapper; +use super::make_current_guard::CurrentContextGuard; use Api; use BuilderAttribs; @@ -143,24 +144,18 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, let dummy_context = try!(create_context(None, &dummy_window, None)); // making context current - gl::wgl::MakeCurrent(dummy_window.1 as *const libc::c_void, - dummy_context.0 as *const libc::c_void); + let current_context = try!(CurrentContextGuard::make_current(&dummy_window, + &dummy_context)); // loading the extra WGL functions - let extra_functions = gl::wgl_extra::Wgl::load_with(|addr| { + gl::wgl_extra::Wgl::load_with(|addr| { use libc; let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); gl::wgl::GetProcAddress(addr) as *const libc::c_void - }); - - // removing current context - gl::wgl::MakeCurrent(ptr::null(), ptr::null()); - - // returning the address - extra_functions + }) }; // creating the real window this time @@ -237,15 +232,11 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, // handling vsync if builder.vsync { if extra_functions.SwapIntervalEXT.is_loaded() { - gl::wgl::MakeCurrent(real_window.1 as *const libc::c_void, - context.0 as *const libc::c_void); + let guard = try!(CurrentContextGuard::make_current(&real_window, &context)); + if extra_functions.SwapIntervalEXT(1) == 0 { return Err(OsError(format!("wglSwapIntervalEXT failed"))); } - - // it is important to remove the current context, otherwise you get very weird - // errors - gl::wgl::MakeCurrent(ptr::null(), ptr::null()); } } diff --git a/src/win32/make_current_guard.rs b/src/win32/make_current_guard.rs new file mode 100644 index 0000000..d6bcc8e --- /dev/null +++ b/src/win32/make_current_guard.rs @@ -0,0 +1,53 @@ +use std::marker::PhantomData; +use std::os; + +use libc; +use winapi; +use CreationError; + +use super::gl; +use super::ContextWrapper; +use super::WindowWrapper; + +/// A guard for when you want to make the context current. Destroying the guard restores the +/// previously-current context. +pub struct CurrentContextGuard<'a, 'b> { + previous_hdc: winapi::HDC, + previous_hglrc: winapi::HGLRC, + marker1: PhantomData<&'a ()>, + marker2: PhantomData<&'b ()>, +} + +impl<'a, 'b> CurrentContextGuard<'a, 'b> { + pub unsafe fn make_current(window: &'a WindowWrapper, context: &'b ContextWrapper) + -> Result, CreationError> + { + let previous_hdc = gl::wgl::GetCurrentDC() as winapi::HDC; + let previous_hglrc = gl::wgl::GetCurrentContext() as winapi::HGLRC; + + let result = gl::wgl::MakeCurrent(window.1 as *const libc::c_void, + context.0 as *const libc::c_void); + + if result == 0 { + return Err(CreationError::OsError(format!("wglMakeCurrent function failed: {}", + os::error_string(os::errno())))); + } + + Ok(CurrentContextGuard { + previous_hdc: previous_hdc, + previous_hglrc: previous_hglrc, + marker1: PhantomData, + marker2: PhantomData, + }) + } +} + +#[unsafe_destructor] +impl<'a, 'b> Drop for CurrentContextGuard<'a, 'b> { + fn drop(&mut self) { + unsafe { + gl::wgl::MakeCurrent(self.previous_hdc as *const libc::c_void, + self.previous_hglrc as *const libc::c_void); + } + } +} diff --git a/src/win32/mod.rs b/src/win32/mod.rs index 4e6a803..327b71d 100644 --- a/src/win32/mod.rs +++ b/src/win32/mod.rs @@ -21,6 +21,7 @@ mod event; mod gl; mod headless; mod init; +mod make_current_guard; mod monitor; /// The Win32 implementation of the main `Window` object. -- cgit v1.2.3 From d091323b22e2b8521a74273821d45a7a4ae08b2a Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Sun, 1 Mar 2015 14:07:50 +0100 Subject: Minor changes in documentation --- README.md | 1 - src/win32/init.rs | 26 ++++++++++++-------------- 2 files changed, 12 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/README.md b/README.md index 7596402..9dab387 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,6 @@ fn main() { ### Win32 - You must call `glFlush` before `swap_buffers`, or else on Windows 8 nothing will be visible on the window - - Pixel formats are not implemented - Changing the cursor (set_cursor) is not implemented ### X11 diff --git a/src/win32/init.rs b/src/win32/init.rs index 09d5878..b458d95 100644 --- a/src/win32/init.rs +++ b/src/win32/init.rs @@ -37,16 +37,15 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option>(); // title to utf16 - //let hints = hints.clone(); + .chain(Some(0).into_iter()).collect::>(); // title to utf16 + let (tx, rx) = channel(); - // GetMessage must be called in the same thread as CreateWindow, - // 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. + // `GetMessage` must be called in the same thread as CreateWindow, so we create a new thread + // dedicated to this window. thread::spawn(move || { unsafe { - // sending + // creating and sending the `Window` match init(title, builder, builder_sharelists) { Ok(w) => tx.send(Ok(w)).ok(), Err(e) => { @@ -65,7 +64,7 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option, builder: BuilderAttribs<'static>, // adjusting the window coordinates using the style user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style); - // getting the address of wglCreateContextAttribsARB + // the first step is to create a dummy window and a dummy context which we will use + // to load the pointers to some functions in the OpenGL driver in `extra_functions` let extra_functions = { - // creating a dummy invisible window for GL initialization + // creating a dummy invisible window let dummy_window = { let handle = user32::CreateWindowExW(ex_style, class_name.as_ptr(), title.as_ptr() as winapi::LPCWSTR, @@ -140,10 +140,8 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, try!(set_pixel_format(&dummy_window, id)); } - // creating the dummy OpenGL context + // creating the dummy OpenGL context and making it current let dummy_context = try!(create_context(None, &dummy_window, None)); - - // making context current let current_context = try!(CurrentContextGuard::make_current(&dummy_window, &dummy_context)); @@ -158,7 +156,7 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, }) }; - // creating the real window this time + // creating the real window this time, by using the functions in `extra_functions` let real_window = { let (width, height) = if builder.monitor.is_some() || builder.dimensions.is_some() { (Some(rect.right - rect.left), Some(rect.bottom - rect.top)) @@ -216,7 +214,7 @@ unsafe fn init(title: Vec, builder: BuilderAttribs<'static>, user32::SetForegroundWindow(real_window.0); } - // filling the WINDOW task-local storage + // filling the WINDOW task-local storage so that we can start receiving events let events_receiver = { let (tx, rx) = channel(); let mut tx = Some(tx); -- cgit v1.2.3