Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/platform/win/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down
109 changes: 109 additions & 0 deletions src/platform/win/tests.rs
Original file line number Diff line number Diff line change
@@ -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<u16> = "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<WindowHandle<'_>, 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::<EmptyHandler, _>(BuildFailed.into()));
let Err(error) = result else {
panic!("creating the window should have failed");
};

let source = error.source().and_then(|source| source.downcast_ref::<BuildFailed>());
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::<windows_core::Error>())
.map(windows_core::Error::code);
assert_eq!(code, Some(HRESULT::from_win32(ERROR_INVALID_WINDOW_HANDLE)), "got: {error}");
}
2 changes: 1 addition & 1 deletion src/platform/win/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion src/platform/win/window_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ impl WindowState {

#[inline]
pub fn create_timer(&self, duration: Duration) -> Result<TimerHandle, super::PlatformError> {
Ok(self.shared.user_timers.add_new_timer(self.hwnd, duration)?)
self.shared.user_timers.add_new_timer(self.hwnd, duration)
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/wrappers/win32/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HWnd, Error> {
fn get_or_create_timer_window(&self, baseview_window: HWnd) -> PlatformResult<HWnd> {
if let Some(timer_window) = self.timer_window.get() {
return Ok(timer_window);
}
Expand Down Expand Up @@ -126,7 +126,7 @@ impl TimerList {

pub fn add_new_timer(
&self, baseview_window: HWnd, timeout: Duration,
) -> Result<TimerId, Error> {
) -> PlatformResult<TimerId> {
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();
Expand Down
16 changes: 13 additions & 3 deletions src/wrappers/win32/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -86,10 +89,13 @@ pub unsafe fn use_window<W: WindowImpl>(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<W: WindowImpl>(
title: &HSTRING, style: WindowStyle, nc_size: PhysicalSize<u32>, parent: Option<HWnd>,
_dpi_ctx: &DpiAwarenessGuard, initializer: impl FnOnce(HWnd) -> W + 'static,
) -> Result<HWnd> {
) -> core::result::Result<HWnd, PlatformError> {
let instance = HInstance::get_from_dll();
let window_class = RegisteredClass::register_new(instance, Some(wnd_proc::<W>))?;

Expand All @@ -112,7 +118,11 @@ pub fn create_window<W: WindowImpl>(
)
};

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) };

Expand Down
13 changes: 13 additions & 0 deletions src/wrappers/win32/window/data.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::*;
use crate::platform::PlatformError;
use std::cell::{Cell, OnceCell};
use std::mem::ManuallyDrop;
use std::ptr::NonNull;
Expand All @@ -12,6 +13,9 @@ type Initializer<W> = dyn FnOnce(HWnd) -> W + 'static;
pub struct WindowData<W> {
initializer: Cell<Option<Box<Initializer<W>>>>,
inner_impl: OnceCell<W>,
// 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<Option<PlatformError>>,
// Keep this around to ensure the class is not de-registered while this window is open
_window_class: RegisteredClass,
}
Expand All @@ -21,6 +25,7 @@ impl<W: WindowImpl> WindowData<W> {
Rc::new(Self {
initializer: Cell::new(Some(Box::new(initializer))),
inner_impl: OnceCell::new(),
creation_error: Cell::new(None),
_window_class: class,
})
}
Expand Down Expand Up @@ -72,4 +77,12 @@ impl<W: WindowImpl> WindowData<W> {
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<PlatformError> {
self.creation_error.take()
}
}
8 changes: 6 additions & 2 deletions src/wrappers/win32/window/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub unsafe extern "system" fn wnd_proc<W: WindowImpl>(
}
}

unsafe fn handle_error_as_fatal<W>(
unsafe fn handle_error_as_fatal<W: WindowImpl>(
result: core::result::Result<(), PlatformError>, window: HWnd,
inner_ptr: NonNull<WindowData<W>>,
) -> LRESULT {
Expand All @@ -107,11 +107,15 @@ unsafe fn handle_error_as_fatal<W>(
// 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::<W>());

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
}
}
Expand Down