Skip to content

Commit

Permalink
Port over aux. crates
Browse files Browse the repository at this point in the history
  • Loading branch information
notgull committed Jul 15, 2023
1 parent bcf2996 commit 84c032f
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 76 deletions.
2 changes: 1 addition & 1 deletion glutin-winit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ wayland = ["glutin/wayland", "winit/wayland"]
[dependencies]
winit = { version = "0.29.0-beta.0", default-features = false }
glutin = { version = "0.30.1", path = "../glutin", default-features = false }
raw-window-handle = "0.5.0"
raw-window-handle = { version = "0.6.0", features = ["std"] }

[build-dependencies]
cfg_aliases = "0.1.1"
28 changes: 15 additions & 13 deletions glutin-winit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ use glutin::display::{Display, DisplayApiPreference};
use glutin::platform::x11::X11GlConfigExt;
use glutin::prelude::*;

use raw_window_handle::{HasRawDisplayHandle, RawWindowHandle};
use raw_window_handle::{HasDisplayHandle, WindowHandle};

#[cfg(wgl_backend)]
use raw_window_handle::HasRawWindowHandle;
use raw_window_handle::HasWindowHandle;

use winit::error::OsError;
use winit::event_loop::EventLoopWindowTarget;
use winit::event_loop::{EventLoopWindowTarget, OwnedDisplayHandle};
use winit::window::{Window, WindowBuilder};

#[cfg(glx_backend)]
Expand Down Expand Up @@ -90,11 +90,13 @@ impl DisplayBuilder {
pub fn build<T, Picker>(
mut self,
window_target: &EventLoopWindowTarget<T>,
template_builder: ConfigTemplateBuilder,
template_builder: ConfigTemplateBuilder<WindowHandle<'_>>,
config_picker: Picker,
) -> Result<(Option<Window>, Config), Box<dyn Error>>
) -> Result<(Option<Window>, Config<OwnedDisplayHandle>), Box<dyn Error>>
where
Picker: FnOnce(Box<dyn Iterator<Item = Config> + '_>) -> Config,
Picker: FnOnce(
Box<dyn Iterator<Item = Config<OwnedDisplayHandle>> + '_>,
) -> Config<OwnedDisplayHandle>,
{
// XXX with WGL backend window should be created first.
#[cfg(wgl_backend)]
Expand All @@ -105,7 +107,7 @@ impl DisplayBuilder {
};

#[cfg(wgl_backend)]
let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());
let raw_window_handle = window.as_ref().map(|w| w.window_handle()).transpose()?;
#[cfg(not(wgl_backend))]
let raw_window_handle = None;

Expand All @@ -122,7 +124,7 @@ impl DisplayBuilder {

let template = template_builder.build();

let gl_config = unsafe {
let gl_config = {
let configs = gl_display.find_configs(template)?;
config_picker(configs)
};
Expand All @@ -141,8 +143,8 @@ impl DisplayBuilder {
fn create_display<T>(
window_target: &EventLoopWindowTarget<T>,
_api_preference: ApiPreference,
_raw_window_handle: Option<RawWindowHandle>,
) -> Result<Display, Box<dyn Error>> {
_raw_window_handle: Option<WindowHandle<'_>>,
) -> Result<Display<OwnedDisplayHandle>, Box<dyn Error>> {
#[cfg(egl_backend)]
let _preference = DisplayApiPreference::Egl;

Expand Down Expand Up @@ -171,7 +173,7 @@ fn create_display<T>(
ApiPreference::FallbackEgl => DisplayApiPreference::WglThenEgl(_raw_window_handle),
};

unsafe { Ok(Display::new(window_target.raw_display_handle(), _preference)?) }
Ok(Display::new(window_target.owned_display_handle(), _preference)?)
}

/// Finalize [`Window`] creation by applying the options from the [`Config`], be
Expand All @@ -180,10 +182,10 @@ fn create_display<T>(
///
/// [`Window`]: winit::window::Window
/// [`Config`]: glutin::config::Config
pub fn finalize_window<T>(
pub fn finalize_window<D: HasDisplayHandle, T>(
window_target: &EventLoopWindowTarget<T>,
mut builder: WindowBuilder,
gl_config: &Config,
gl_config: &Config<D>,
) -> Result<Window, OsError> {
// Disable transparency if the end config doesn't support it.
if gl_config.supports_transparency() == Some(false) {
Expand Down
58 changes: 34 additions & 24 deletions glutin-winit/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use glutin::surface::{
GlSurface, ResizeableSurface, Surface, SurfaceAttributes, SurfaceAttributesBuilder,
SurfaceTypeTrait, WindowSurface,
};
use raw_window_handle::HasRawWindowHandle;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use std::num::NonZeroU32;

use winit::window::Window;

/// [`Window`] extensions for working with [`glutin`] surfaces.
pub trait GlWindow {
pub trait GlWindow: HasWindowHandle + Sized {
/// Build the surface attributes suitable to create a window surface.
///
/// # Panics
Expand All @@ -22,9 +23,9 @@ pub trait GlWindow {
/// let attrs = winit_window.build_surface_attributes(<_>::default());
/// ```
fn build_surface_attributes(
&self,
builder: SurfaceAttributesBuilder<WindowSurface>,
) -> SurfaceAttributes<WindowSurface>;
self,
builder: SurfaceAttributesBuilder<WindowSurface<Self>>,
) -> SurfaceAttributes<WindowSurface<Self>>;

/// Resize the surface to the window inner size.
///
Expand All @@ -39,33 +40,42 @@ pub trait GlWindow {
///
/// winit_window.resize_surface(&gl_surface, &gl_context);
/// ```
fn resize_surface(
fn resize_surface<D: HasDisplayHandle>(
&self,
surface: &Surface<impl SurfaceTypeTrait + ResizeableSurface>,
context: &PossiblyCurrentContext,
surface: &Surface<D, impl SurfaceTypeTrait + ResizeableSurface>,
context: &PossiblyCurrentContext<D>,
);
}

impl GlWindow for Window {
fn build_surface_attributes(
&self,
builder: SurfaceAttributesBuilder<WindowSurface>,
) -> SurfaceAttributes<WindowSurface> {
let (w, h) = self.inner_size().non_zero().expect("invalid zero inner size");
builder.build(self.raw_window_handle(), w, h)
}
macro_rules! implement_glwindow {
(<$($lt:lifetime)?> $ty:ty) => {
impl<$($lt)?> GlWindow for $ty {
fn build_surface_attributes(
self,
builder: SurfaceAttributesBuilder<WindowSurface<Self>>,
) -> SurfaceAttributes<WindowSurface<Self>> {
let (w, h) = self.inner_size().non_zero().expect("invalid zero inner size");
builder.build(self, 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)
fn resize_surface<D: HasDisplayHandle>(
&self,
surface: &Surface<D, impl SurfaceTypeTrait + ResizeableSurface>,
context: &PossiblyCurrentContext<D>,
) {
if let Some((w, h)) = self.inner_size().non_zero() {
surface.resize(context, w, h)
}
}
}
}
};
}

implement_glwindow!(<> Window);
implement_glwindow!(<'a> &'a Window);
implement_glwindow!(<> std::rc::Rc<Window>);
implement_glwindow!(<> std::sync::Arc<Window>);

/// [`winit::dpi::PhysicalSize<u32>`] non-zero extensions.
trait NonZeroU32PhysicalSize {
/// Converts to non-zero `(width, height)`.
Expand Down
12 changes: 5 additions & 7 deletions glutin/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ pub struct ConfigTemplateBuilder<W = super::NoWindow> {
template: ConfigTemplate<W>,
}

impl Default for ConfigTemplateBuilder {
impl<W> Default for ConfigTemplateBuilder<W> {
fn default() -> Self {
Self {
template: ConfigTemplate {
Expand All @@ -118,7 +118,7 @@ impl Default for ConfigTemplateBuilder {
}
}

impl ConfigTemplateBuilder {
impl<W: HasWindowHandle> ConfigTemplateBuilder<W> {
/// Create a new configuration template builder.
#[inline]
pub fn new() -> Self {
Expand All @@ -135,10 +135,10 @@ impl ConfigTemplateBuilder {
/// When using WGL it's the most reliable way to get a working
/// configuration. With GLX it'll use the visual passed in
/// `native_window` to match the config.
pub fn compatible_with_native_window<W: HasWindowHandle>(
pub fn compatible_with_native_window<W2: HasWindowHandle>(
self,
native_window: W,
) -> ConfigTemplateBuilder<W> {
native_window: W2,
) -> ConfigTemplateBuilder<W2> {
let ConfigTemplate {
color_buffer_type,
alpha_size,
Expand Down Expand Up @@ -180,9 +180,7 @@ impl ConfigTemplateBuilder {
},
}
}
}

impl<W: HasWindowHandle> ConfigTemplateBuilder<W> {
/// Number of alpha bits in the color buffer.
///
/// By default `8` is requested.
Expand Down
14 changes: 2 additions & 12 deletions glutin/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,18 +208,8 @@ impl ContextAttributesBuilder {
///
/// - **WGL:** you **must** pass a `raw_window_handle` if you plan to use
/// this context with that window.
pub fn build<W: HasWindowHandle>(self, window_handle: W) -> ContextAttributes<W> {
ContextAttributes { inner: self.attributes, _window: Some(window_handle) }
}

/// Build the context attributes without a window handle.
///
/// # Api-specific
///
/// - **WGL*:: Contexts created with this function will not be able to be
/// used with a window.
pub fn build_no_window(self) -> ContextAttributes<crate::NoWindow> {
ContextAttributes { inner: self.attributes, _window: None }
pub fn build<W: HasWindowHandle>(self, window_handle: Option<W>) -> ContextAttributes<W> {
ContextAttributes { inner: self.attributes, _window: window_handle }
}
}

Expand Down
2 changes: 1 addition & 1 deletion glutin_examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ wayland = ["glutin-winit/wayland", "winit/wayland-dlopen", "winit/wayland-csd-ad
glutin = { path = "../glutin", default-features = false }
winit = { version = "0.29.0-beta.0", default-features = false }
glutin-winit = { path = "../glutin-winit", default-features = false }
raw-window-handle = "0.5.0"
raw-window-handle = "0.6.0"
png = { version = "0.17.6", optional = true }

[target.'cfg(target_os = "android")'.dependencies]
Expand Down
16 changes: 9 additions & 7 deletions glutin_examples/examples/egl_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ mod example {
let device = devices.first().expect("No available devices");

// Create a display using the device.
let display =
unsafe { Display::with_device(device, None) }.expect("Failed to create display");
let display = unsafe { Display::<glutin::NoDisplay>::with_device(device, None) }
.expect("Failed to create display");

let template = config_template();
let config = unsafe { display.find_configs(template) }
let config = display
.find_configs(template)
.unwrap()
.reduce(
|config, acc| {
Expand All @@ -55,14 +56,15 @@ mod example {
//
// In particular, since we are doing offscreen rendering we have no raw window
// handle to provide.
let context_attributes = ContextAttributesBuilder::new().build(None);
let context_attributes = ContextAttributesBuilder::new().build::<glutin::NoWindow>(None);

// Since glutin by default tries to create OpenGL core context, which may not be
// present we should try gles.
let fallback_context_attributes =
ContextAttributesBuilder::new().with_context_api(ContextApi::Gles(None)).build(None);
let fallback_context_attributes = ContextAttributesBuilder::new()
.with_context_api(ContextApi::Gles(None))
.build::<glutin::NoWindow>(None);

let not_current = unsafe {
let not_current = {
display.create_context(&config, &context_attributes).unwrap_or_else(|_| {
display
.create_context(&config, &fallback_context_attributes)
Expand Down
27 changes: 16 additions & 11 deletions glutin_examples/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::ffi::{CStr, CString};
use std::num::NonZeroU32;
use std::ops::Deref;
use std::rc::Rc;

use winit::event::{Event, WindowEvent};
use winit::window::WindowBuilder;

use raw_window_handle::HasRawWindowHandle;
use raw_window_handle::HasWindowHandle;

use glutin::config::ConfigTemplateBuilder;
use glutin::context::{ContextApi, ContextAttributesBuilder, Version};
Expand Down Expand Up @@ -44,7 +45,7 @@ pub fn main(event_loop: winit::event_loop::EventLoop<()>) {

let display_builder = DisplayBuilder::new().with_window_builder(window_builder);

let (mut window, gl_config) = display_builder
let (window, gl_config) = display_builder
.build(&event_loop, template, |configs| {
// Find the config with the maximum number of samples, so our triangle will
// be smooth.
Expand All @@ -65,7 +66,8 @@ pub fn main(event_loop: winit::event_loop::EventLoop<()>) {

println!("Picked a config with {} samples", gl_config.num_samples());

let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());
let raw_window_handle =
window.as_ref().map(|window| window.window_handle()).transpose().unwrap();

// XXX The display could be obtained from the any object created by it, so we
// can query it from the config.
Expand All @@ -88,7 +90,7 @@ pub fn main(event_loop: winit::event_loop::EventLoop<()>) {
.with_context_api(ContextApi::OpenGl(Some(Version::new(2, 1))))
.build(raw_window_handle);

let mut not_current_gl_context = Some(unsafe {
let mut not_current_gl_context = Some({
gl_display.create_context(&gl_config, &context_attributes).unwrap_or_else(|_| {
gl_display.create_context(&gl_config, &fallback_context_attributes).unwrap_or_else(
|_| {
Expand All @@ -100,6 +102,7 @@ pub fn main(event_loop: winit::event_loop::EventLoop<()>) {
})
});

let mut window = window.map(Rc::new);
let mut state = None;
let mut renderer = None;
event_loop.run(move |event, window_target, control_flow| {
Expand All @@ -109,16 +112,17 @@ pub fn main(event_loop: winit::event_loop::EventLoop<()>) {
#[cfg(android_platform)]
println!("Android window available");

let window = window.take().unwrap_or_else(|| {
let window = window.clone().unwrap_or_else(|| {
let window_builder = WindowBuilder::new().with_transparent(true);
glutin_winit::finalize_window(window_target, window_builder, &gl_config)
.unwrap()
Rc::new(
glutin_winit::finalize_window(window_target, window_builder, &gl_config)
.unwrap(),
)
});

let attrs = window.build_surface_attributes(<_>::default());
let gl_surface = unsafe {
gl_config.display().create_window_surface(&gl_config, &attrs).unwrap()
};
let attrs = window.clone().build_surface_attributes(<_>::default());
let gl_surface =
{ gl_config.display().create_window_surface(&gl_config, attrs).unwrap() };

// Make it current.
let gl_context =
Expand Down Expand Up @@ -149,6 +153,7 @@ pub fn main(event_loop: winit::event_loop::EventLoop<()>) {
assert!(not_current_gl_context
.replace(gl_context.make_not_current().unwrap())
.is_none());
window = None;
},
Event::WindowEvent { event, .. } => match event {
WindowEvent::Resized(size) => {
Expand Down

0 comments on commit 84c032f

Please sign in to comment.