diff --git a/src/platform/win/mod.rs b/src/platform/win/mod.rs index 8982821f..844f0aa4 100644 --- a/src/platform/win/mod.rs +++ b/src/platform/win/mod.rs @@ -15,6 +15,9 @@ mod waker; mod window; mod window_state; +#[cfg(test)] +mod tests; + pub(crate) use dpi::DpiScalingStrategy; pub use error::{PlatformError, PlatformResult}; pub use parent_handle::*; diff --git a/src/platform/win/tests.rs b/src/platform/win/tests.rs new file mode 100644 index 00000000..fd0f84da --- /dev/null +++ b/src/platform/win/tests.rs @@ -0,0 +1,109 @@ +use std::error::Error as _; +use std::fmt::{Display, Formatter}; +use std::num::NonZeroIsize; +use std::ptr::null_mut; + +use raw_window_handle::{HandleError, HasWindowHandle, Win32WindowHandle, WindowHandle}; +use windows_core::HRESULT; +use windows_sys::Win32::Foundation::ERROR_INVALID_WINDOW_HANDLE; +use windows_sys::Win32::UI::WindowsAndMessaging::{CreateWindowExW, DestroyWindow}; + +use crate::{Event, EventStatus, HandlerError, Window, WindowHandler, WindowSettings, WindowSize}; + +#[derive(Debug)] +struct BuildFailed; + +impl Display for BuildFailed { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str("the handler could not be built") + } +} + +impl std::error::Error for BuildFailed {} + +struct EmptyHandler; + +impl WindowHandler for EmptyHandler { + fn draw(&self) -> Result<(), HandlerError> { + Ok(()) + } + + fn resized(&self, _new_size: WindowSize) -> Result<(), HandlerError> { + Ok(()) + } + + fn on_event(&self, _event: Event) -> EventStatus { + EventStatus::Ignored + } +} + +/// The handle of a window that has already been destroyed. +struct DestroyedWindow(NonZeroIsize); + +impl DestroyedWindow { + fn new() -> Self { + let class: Vec = "STATIC".encode_utf16().chain(Some(0)).collect(); + + // SAFETY: STATIC is a system class, the class name outlives the call, and every + // optional handle or pointer is null. + let hwnd = unsafe { + CreateWindowExW( + 0, + class.as_ptr(), + null_mut(), + 0, + 0, + 0, + 10, + 10, + null_mut(), + null_mut(), + null_mut(), + null_mut(), + ) + }; + let Some(handle) = NonZeroIsize::new(hwnd as isize) else { + panic!("could not create the STATIC window"); + }; + + // SAFETY: created above on this thread; afterwards only its stale handle value is used. + assert_ne!(unsafe { DestroyWindow(hwnd) }, 0, "could not destroy the STATIC window"); + + Self(handle) + } +} + +impl HasWindowHandle for DestroyedWindow { + fn window_handle(&self) -> Result, HandleError> { + // SAFETY: the handle is only handed to window creation, which rejects it. + Ok(unsafe { WindowHandle::borrow_raw(Win32WindowHandle::new(self.0).into()) }) + } +} + +#[test] +fn failed_create_returns_the_handler_error() { + let result = + Window::create(WindowSettings::new(), |_| Err::(BuildFailed.into())); + let Err(error) = result else { + panic!("creating the window should have failed"); + }; + + let source = error.source().and_then(|source| source.downcast_ref::()); + assert!(source.is_some(), "expected the handler's error, got: {error}"); +} + +#[test] +fn failed_create_without_a_window_returns_the_system_error() { + let parent = DestroyedWindow::new(); + + let result = Window::create(WindowSettings::new().with_parent(&parent), |_| Ok(EmptyHandler)); + let Err(error) = result else { + panic!("creating a window inside a destroyed parent should have failed"); + }; + + let code = error + .source() + .and_then(|source| source.downcast_ref::()) + .map(windows_core::Error::code); + assert_eq!(code, Some(HRESULT::from_win32(ERROR_INVALID_WINDOW_HANDLE)), "got: {error}"); +} diff --git a/src/platform/win/window.rs b/src/platform/win/window.rs index 25277861..57eeb78b 100644 --- a/src/platform/win/window.rs +++ b/src/platform/win/window.rs @@ -240,7 +240,7 @@ impl BaseviewWindow { } } }; - Ok(create_window(&title, style, rect.size(), parent, &dpi_ctx, initializer)?) + create_window(&title, style, rect.size(), parent, &dpi_ctx, initializer) } fn notify_destroyed_to_host(&self) { diff --git a/src/platform/win/window_state.rs b/src/platform/win/window_state.rs index 4b4c309b..a2a4af66 100644 --- a/src/platform/win/window_state.rs +++ b/src/platform/win/window_state.rs @@ -157,7 +157,7 @@ impl WindowState { #[inline] pub fn create_timer(&self, duration: Duration) -> Result { - Ok(self.shared.user_timers.add_new_timer(self.hwnd, duration)?) + self.shared.user_timers.add_new_timer(self.hwnd, duration) } } diff --git a/src/wrappers/win32/timer.rs b/src/wrappers/win32/timer.rs index f931cada..6c41dba9 100644 --- a/src/wrappers/win32/timer.rs +++ b/src/wrappers/win32/timer.rs @@ -92,7 +92,7 @@ impl TimerList { Self { timers: Vec::new().into(), timer_window: None.into(), timer_fn } } - fn get_or_create_timer_window(&self, baseview_window: HWnd) -> Result { + fn get_or_create_timer_window(&self, baseview_window: HWnd) -> PlatformResult { if let Some(timer_window) = self.timer_window.get() { return Ok(timer_window); } @@ -126,7 +126,7 @@ impl TimerList { pub fn add_new_timer( &self, baseview_window: HWnd, timeout: Duration, - ) -> Result { + ) -> PlatformResult { let timeout_msec = timeout.as_millis().try_into().unwrap_or(u32::MAX); let timer_window = self.get_or_create_timer_window(baseview_window)?; let new_timer_id = self.get_new_timer_id(); diff --git a/src/wrappers/win32/window.rs b/src/wrappers/win32/window.rs index bb2d862b..a6dbebb7 100644 --- a/src/wrappers/win32/window.rs +++ b/src/wrappers/win32/window.rs @@ -18,13 +18,16 @@ mod wgl; pub use wgl::*; use crate::dpi::PhysicalSize; +use crate::platform::PlatformError; pub use data::WindowData; pub use handle::*; pub use proc::wnd_proc; use std::ptr::{null_mut, NonNull}; use std::rc::Rc; use window_class::RegisteredClass; -use windows_core::{Error, Result, HSTRING}; +#[cfg(feature = "opengl")] +use windows_core::Result; +use windows_core::{Error, HSTRING}; use crate::wrappers::win32::dpi::DpiAwarenessGuard; use crate::wrappers::win32::h_instance::HInstance; @@ -86,10 +89,13 @@ pub unsafe fn use_window(hwnd: HWnd, handler: impl FnOnce(&W)) { /// its handler methods. /// For any non-trivial operations (e.g. window resizing, GL context creation, etc.), put them in /// [`WindowImpl::after_create`] instead. +/// +/// If [`WindowImpl::non_client_create`] or [`WindowImpl::after_create`] fails, the window is not +/// created and that error is returned. pub fn create_window( title: &HSTRING, style: WindowStyle, nc_size: PhysicalSize, parent: Option, _dpi_ctx: &DpiAwarenessGuard, initializer: impl FnOnce(HWnd) -> W + 'static, -) -> Result { +) -> core::result::Result { let instance = HInstance::get_from_dll(); let window_class = RegisteredClass::register_new(instance, Some(wnd_proc::))?; @@ -112,7 +118,11 @@ pub fn create_window( ) }; - let Some(hwnd) = NonNull::new(hwnd) else { return Err(Error::from_thread()) }; + let Some(hwnd) = NonNull::new(hwnd) else { + // If our window procedure aborted the creation, it left its error behind. Otherwise + // CreateWindowExW failed on its own, and the reason is in the thread's last error. + return Err(data.take_creation_error().unwrap_or_else(|| Error::from_thread().into())); + }; // SAFETY: This Hwnd is valid since it came from CreateWindowExW let hwnd = unsafe { HWnd::from_raw(hwnd) }; diff --git a/src/wrappers/win32/window/data.rs b/src/wrappers/win32/window/data.rs index 36ef2990..52774085 100644 --- a/src/wrappers/win32/window/data.rs +++ b/src/wrappers/win32/window/data.rs @@ -1,4 +1,5 @@ use super::*; +use crate::platform::PlatformError; use std::cell::{Cell, OnceCell}; use std::mem::ManuallyDrop; use std::ptr::NonNull; @@ -12,6 +13,9 @@ type Initializer = dyn FnOnce(HWnd) -> W + 'static; pub struct WindowData { initializer: Cell>>>, inner_impl: OnceCell, + // The error that made WM_NCCREATE or WM_CREATE abort the window creation, if any. + // CreateWindowExW only returns NULL in that case, so this is how create_window gets it back. + creation_error: Cell>, // Keep this around to ensure the class is not de-registered while this window is open _window_class: RegisteredClass, } @@ -21,6 +25,7 @@ impl WindowData { Rc::new(Self { initializer: Cell::new(Some(Box::new(initializer))), inner_impl: OnceCell::new(), + creation_error: Cell::new(None), _window_class: class, }) } @@ -72,4 +77,12 @@ impl WindowData { pub fn inner(&self) -> Option<&W> { self.inner_impl.get() } + + pub fn set_creation_error(&self, error: PlatformError) { + self.creation_error.set(Some(error)); + } + + pub fn take_creation_error(&self) -> Option { + self.creation_error.take() + } } diff --git a/src/wrappers/win32/window/proc.rs b/src/wrappers/win32/window/proc.rs index 80507904..d5ce035a 100644 --- a/src/wrappers/win32/window/proc.rs +++ b/src/wrappers/win32/window/proc.rs @@ -93,7 +93,7 @@ pub unsafe extern "system" fn wnd_proc( } } -unsafe fn handle_error_as_fatal( +unsafe fn handle_error_as_fatal( result: core::result::Result<(), PlatformError>, window: HWnd, inner_ptr: NonNull>, ) -> LRESULT { @@ -107,11 +107,15 @@ unsafe fn handle_error_as_fatal( // First, revoke ownership from the window, we don't want it to be used by any subsequent messages. let _ = window.set_userdata_ptr(core::ptr::null::()); + crate::error!("Window initializer failed while trying to create window: {}", &e); + + // Hand the error over to create_window, which still holds its own reference to the data. + inner_ptr.as_ref().set_creation_error(e); + // Try to recover and free the received pointer data. But if this also fails, better to leak // it than risk crashing drop(Rc::from_raw(inner_ptr.as_ptr())); - crate::error!("Window initializer failed while trying to create window: {}", e); -1 } }