use std::num::NonZeroU32;
use glutin::context::PossiblyCurrentContext;
use glutin::surface::{
GlSurface, ResizeableSurface, Surface, SurfaceAttributes, SurfaceAttributesBuilder,
SurfaceTypeTrait, WindowSurface,
};
use raw_window_handle::{HandleError, HasWindowHandle};
use winit::window::Window;
pub trait GlWindow {
fn build_surface_attributes(
&self,
builder: SurfaceAttributesBuilder<WindowSurface>,
) -> Result<SurfaceAttributes<WindowSurface>, HandleError>;
fn resize_surface(
&self,
surface: &Surface<impl SurfaceTypeTrait + ResizeableSurface>,
context: &PossiblyCurrentContext,
);
}
impl GlWindow for Window {
fn build_surface_attributes(
&self,
builder: SurfaceAttributesBuilder<WindowSurface>,
) -> Result<SurfaceAttributes<WindowSurface>, HandleError> {
let (w, h) = self.inner_size().non_zero().expect("invalid zero inner size");
let handle = self.window_handle()?.as_raw();
Ok(builder.build(handle, w, h))
}
fn resize_surface(
&self,
surface: &Surface<impl SurfaceTypeTrait + ResizeableSurface>,
context: &PossiblyCurrentContext,
) {
if let Some((w, h)) = self.inner_size().non_zero() {
surface.resize(context, w, h)
}
}
}
trait NonZeroU32PhysicalSize {
fn non_zero(self) -> Option<(NonZeroU32, NonZeroU32)>;
}
impl NonZeroU32PhysicalSize for winit::dpi::PhysicalSize<u32> {
fn non_zero(self) -> Option<(NonZeroU32, NonZeroU32)> {
let w = NonZeroU32::new(self.width)?;
let h = NonZeroU32::new(self.height)?;
Some((w, h))
}
}