Merge pull request #603 from tomaka/gl-attribs

Separate the builder attributes into multiple substates
This commit is contained in:
tomaka 2015-09-21 14:15:41 +02:00
commit 6787f1d434
20 changed files with 475 additions and 337 deletions

View file

@ -14,12 +14,14 @@ use events::MouseButton;
use std::collections::VecDeque; use std::collections::VecDeque;
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CursorState; use CursorState;
use GlAttributes;
use GlContext; use GlContext;
use GlRequest; use GlRequest;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use WindowAttributes;
use native_monitor::NativeMonitorId; use native_monitor::NativeMonitorId;
use api::egl; use api::egl;
@ -104,15 +106,20 @@ impl<'a> Iterator for WaitEventsIterator<'a> {
} }
impl Window { impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
use std::{mem, ptr}; use std::{mem, ptr};
let opengl = opengl.clone().map_sharing(|w| &w.context);
let native_window = unsafe { android_glue::get_native_window() }; let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() { if native_window.is_null() {
return Err(OsError(format!("Android's native window is null"))); return Err(OsError(format!("Android's native window is null")));
} }
let context = try!(EglContext::new(egl::ffi::egl::Egl, &builder, egl::NativeDisplay::Android) let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl,
egl::NativeDisplay::Android)
.and_then(|p| p.finish(native_window as *const _))); .and_then(|p| p.finish(native_window as *const _)));
let (tx, rx) = channel(); let (tx, rx) = channel();
@ -254,9 +261,13 @@ pub struct HeadlessContext(EglContext);
impl HeadlessContext { impl HeadlessContext {
/// See the docs in the crate root file. /// See the docs in the crate root file.
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
let context = try!(EglContext::new(egl::ffi::egl::Egl, &builder, egl::NativeDisplay::Android)); opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError>
let context = try!(context.finish_pbuffer()); {
let opengl = opengl.clone().map_sharing(|c| &c.0);
let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl,
egl::NativeDisplay::Android));
let context = try!(context.finish_pbuffer(dimensions)); // TODO:
Ok(HeadlessContext(context)) Ok(HeadlessContext(context))
} }
} }

View file

@ -5,14 +5,16 @@ use libc;
use api::osmesa::{OsMesaContext, OsMesaCreationError}; use api::osmesa::{OsMesaContext, OsMesaCreationError};
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use Event; use Event;
use GlAttributes;
use GlContext; use GlContext;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use CursorState; use CursorState;
use MouseCursor; use MouseCursor;
use WindowAttributes;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::path::Path; use std::path::Path;
@ -84,8 +86,14 @@ impl<'a> Iterator for WaitEventsIterator<'a> {
} }
impl Window { impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
let opengl = match OsMesaContext::new(builder) { opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|w| &w.opengl);
let opengl = match OsMesaContext::new(window.dimensions.unwrap_or((800, 600)), pf_reqs,
&opengl)
{
Err(OsMesaCreationError::NotSupported) => return Err(CreationError::NotSupported), Err(OsMesaCreationError::NotSupported) => return Err(CreationError::NotSupported),
Err(OsMesaCreationError::CreationError(e)) => return Err(e), Err(OsMesaCreationError::CreationError(e)) => return Err(e),
Ok(c) => c Ok(c) => c

View file

@ -1,8 +1,9 @@
use ContextError; use ContextError;
use CreationError; use CreationError;
use CreationError::OsError; use CreationError::OsError;
use BuilderAttribs; use GlAttributes;
use GlContext; use GlContext;
use PixelFormatRequirements;
use libc; use libc;
use std::ptr; use std::ptr;
@ -27,8 +28,9 @@ pub struct HeadlessContext {
} }
impl HeadlessContext { impl HeadlessContext {
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { pub fn new((width, height): (u32, u32), pf_reqs: &PixelFormatRequirements,
let (width, height) = builder.dimensions.unwrap_or((1024, 768)); opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError>
{
let context = unsafe { let context = unsafe {
let attributes = [ let attributes = [
NSOpenGLPFAAccelerated as u32, NSOpenGLPFAAccelerated as u32,

View file

@ -7,13 +7,15 @@ use CreationError::OsError;
use libc; use libc;
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use GlAttributes;
use GlContext; use GlContext;
use GlProfile; use GlProfile;
use GlRequest; use GlRequest;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use WindowAttributes;
use native_monitor::NativeMonitorId; use native_monitor::NativeMonitorId;
use objc::runtime::{Class, Object, Sel, BOOL, YES, NO}; use objc::runtime::{Class, Object, Sel, BOOL, YES, NO};
@ -266,12 +268,14 @@ impl<'a> Iterator for WaitEventsIterator<'a> {
impl Window { impl Window {
#[cfg(feature = "window")] #[cfg(feature = "window")]
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(win_attribs: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
if builder.sharing.is_some() { opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
if opengl.sharing.is_some() {
unimplemented!() unimplemented!()
} }
match builder.gl_robustness { match opengl.robustness {
Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => { Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => {
return Err(CreationError::RobustnessNotSupported); return Err(CreationError::RobustnessNotSupported);
}, },
@ -283,7 +287,7 @@ impl Window {
None => { return Err(OsError(format!("Couldn't create NSApplication"))); }, None => { return Err(OsError(format!("Couldn't create NSApplication"))); },
}; };
let window = match Window::create_window(&builder) let window = match Window::create_window(win_attribs)
{ {
Some(window) => window, Some(window) => window,
None => { return Err(OsError(format!("Couldn't create NSWindow"))); }, None => { return Err(OsError(format!("Couldn't create NSWindow"))); },
@ -295,13 +299,13 @@ impl Window {
// TODO: perhaps we should return error from create_context so we can // TODO: perhaps we should return error from create_context so we can
// determine the cause of failure and possibly recover? // determine the cause of failure and possibly recover?
let (context, pf) = match Window::create_context(*view, &builder) { let (context, pf) = match Window::create_context(*view, pf_reqs, opengl) {
Ok((context, pf)) => (context, pf), Ok((context, pf)) => (context, pf),
Err(e) => { return Err(OsError(format!("Couldn't create OpenGL context: {}", e))); }, Err(e) => { return Err(OsError(format!("Couldn't create OpenGL context: {}", e))); },
}; };
unsafe { unsafe {
if builder.transparent { if win_attribs.transparent {
let clear_col = { let clear_col = {
let cls = Class::get("NSColor").unwrap(); let cls = Class::get("NSColor").unwrap();
@ -317,7 +321,7 @@ impl Window {
} }
app.activateIgnoringOtherApps_(YES); app.activateIgnoringOtherApps_(YES);
if builder.visible { if win_attribs.visible {
window.makeKeyAndOrderFront_(nil); window.makeKeyAndOrderFront_(nil);
} else { } else {
window.makeKeyWindow(); window.makeKeyWindow();
@ -356,9 +360,9 @@ impl Window {
} }
} }
fn create_window(builder: &BuilderAttribs) -> Option<IdRef> { fn create_window(attrs: &WindowAttributes) -> Option<IdRef> {
unsafe { unsafe {
let screen = match builder.monitor { let screen = match attrs.monitor {
Some(ref monitor_id) => { Some(ref monitor_id) => {
let native_id = match monitor_id.get_native_identifier() { let native_id = match monitor_id.get_native_identifier() {
NativeMonitorId::Numeric(num) => num, NativeMonitorId::Numeric(num) => num,
@ -390,12 +394,12 @@ impl Window {
let frame = match screen { let frame = match screen {
Some(screen) => NSScreen::frame(screen), Some(screen) => NSScreen::frame(screen),
None => { None => {
let (width, height) = builder.dimensions.unwrap_or((800, 600)); let (width, height) = attrs.dimensions.unwrap_or((800, 600));
NSRect::new(NSPoint::new(0., 0.), NSSize::new(width as f64, height as f64)) NSRect::new(NSPoint::new(0., 0.), NSSize::new(width as f64, height as f64))
} }
}; };
let masks = if screen.is_some() || !builder.decorations { let masks = if screen.is_some() || !attrs.decorations {
NSBorderlessWindowMask as NSUInteger | NSBorderlessWindowMask as NSUInteger |
NSResizableWindowMask as NSUInteger NSResizableWindowMask as NSUInteger
} else { } else {
@ -412,7 +416,7 @@ impl Window {
NO, NO,
)); ));
window.non_nil().map(|window| { window.non_nil().map(|window| {
let title = IdRef::new(NSString::alloc(nil).init_str(&builder.title)); let title = IdRef::new(NSString::alloc(nil).init_str(&attrs.title));
window.setTitle_(*title); window.setTitle_(*title);
window.setAcceptsMouseMovedEvents_(YES); window.setAcceptsMouseMovedEvents_(YES);
if screen.is_some() { if screen.is_some() {
@ -437,8 +441,10 @@ impl Window {
} }
} }
fn create_context(view: id, builder: &BuilderAttribs) -> Result<(IdRef, PixelFormat), CreationError> { fn create_context(view: id, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>)
let profile = match (builder.gl_version, builder.gl_version.to_gl_version(), builder.gl_profile) { -> Result<(IdRef, PixelFormat), CreationError>
{
let profile = match (opengl.version, opengl.version.to_gl_version(), opengl.profile) {
// Note: we are not using ranges because of a rust bug that should be fixed here: // Note: we are not using ranges because of a rust bug that should be fixed here:
// https://github.com/rust-lang/rust/pull/27050 // https://github.com/rust-lang/rust/pull/27050
@ -471,16 +477,16 @@ impl Window {
// full color size and hope for the best. Another hiccup is that // full color size and hope for the best. Another hiccup is that
// `NSOpenGLPFAColorSize` also includes `NSOpenGLPFAAlphaSize`, // `NSOpenGLPFAColorSize` also includes `NSOpenGLPFAAlphaSize`,
// so we have to account for that as well. // so we have to account for that as well.
let alpha_depth = builder.alpha_bits.unwrap_or(8); let alpha_depth = pf_reqs.alpha_bits.unwrap_or(8);
let color_depth = builder.color_bits.unwrap_or(24) + alpha_depth; let color_depth = pf_reqs.color_bits.unwrap_or(24) + alpha_depth;
let mut attributes = vec![ let mut attributes = vec![
NSOpenGLPFADoubleBuffer as u32, NSOpenGLPFADoubleBuffer as u32,
NSOpenGLPFAClosestPolicy as u32, NSOpenGLPFAClosestPolicy as u32,
NSOpenGLPFAColorSize as u32, color_depth as u32, NSOpenGLPFAColorSize as u32, color_depth as u32,
NSOpenGLPFAAlphaSize as u32, alpha_depth as u32, NSOpenGLPFAAlphaSize as u32, alpha_depth as u32,
NSOpenGLPFADepthSize as u32, builder.depth_bits.unwrap_or(24) as u32, NSOpenGLPFADepthSize as u32, pf_reqs.depth_bits.unwrap_or(24) as u32,
NSOpenGLPFAStencilSize as u32, builder.stencil_bits.unwrap_or(8) as u32, NSOpenGLPFAStencilSize as u32, pf_reqs.stencil_bits.unwrap_or(8) as u32,
NSOpenGLPFAOpenGLProfile as u32, profile, NSOpenGLPFAOpenGLProfile as u32, profile,
]; ];
@ -491,7 +497,7 @@ impl Window {
attributes.push(NSOpenGLPFAColorFloat as u32); attributes.push(NSOpenGLPFAColorFloat as u32);
} }
builder.multisampling.map(|samples| { pf_reqs.multisampling.map(|samples| {
attributes.push(NSOpenGLPFAMultisample as u32); attributes.push(NSOpenGLPFAMultisample as u32);
attributes.push(NSOpenGLPFASampleBuffers as u32); attributes.push(1); attributes.push(NSOpenGLPFASampleBuffers as u32); attributes.push(1);
attributes.push(NSOpenGLPFASamples as u32); attributes.push(samples as u32); attributes.push(NSOpenGLPFASamples as u32); attributes.push(samples as u32);
@ -540,7 +546,7 @@ impl Window {
}; };
cxt.setView_(view); cxt.setView_(view);
let value = if builder.vsync { 1 } else { 0 }; let value = if opengl.vsync { 1 } else { 0 };
cxt.setValues_forParameter_(&value, NSOpenGLContextParameter::NSOpenGLCPSwapInterval); cxt.setValues_forParameter_(&value, NSOpenGLContextParameter::NSOpenGLCPSwapInterval);
CGLEnable(cxt.CGLContextObj(), kCGLCECrashOnRemovedFunctions); CGLEnable(cxt.CGLContextObj(), kCGLCECrashOnRemovedFunctions);

View file

@ -2,12 +2,13 @@
target_os = "dragonfly", target_os = "freebsd"))] target_os = "dragonfly", target_os = "freebsd"))]
#![allow(unused_variables)] #![allow(unused_variables)]
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use GlAttributes;
use GlContext; use GlContext;
use GlRequest; use GlRequest;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use Api; use Api;
@ -158,11 +159,11 @@ impl Context {
/// This function initializes some things and chooses the pixel format. /// This function initializes some things and chooses the pixel format.
/// ///
/// To finish the process, you must call `.finish(window)` on the `ContextPrototype`. /// To finish the process, you must call `.finish(window)` on the `ContextPrototype`.
pub fn new<'a>(egl: ffi::egl::Egl, builder: &'a BuilderAttribs<'a>, pub fn new<'a>(egl: ffi::egl::Egl, pf_reqs: &PixelFormatRequirements,
native_display: NativeDisplay) opengl: &'a GlAttributes<&'a Context>, native_display: NativeDisplay)
-> Result<ContextPrototype<'a>, CreationError> -> Result<ContextPrototype<'a>, CreationError>
{ {
if builder.sharing.is_some() { if opengl.sharing.is_some() {
unimplemented!() unimplemented!()
} }
@ -197,7 +198,7 @@ impl Context {
// binding the right API and choosing the version // binding the right API and choosing the version
let (version, api) = unsafe { let (version, api) = unsafe {
match builder.gl_version { match opengl.version {
GlRequest::Latest => { GlRequest::Latest => {
if egl_version >= (1, 4) { if egl_version >= (1, 4) {
if egl.BindAPI(ffi::egl::OPENGL_API) != 0 { if egl.BindAPI(ffi::egl::OPENGL_API) != 0 {
@ -246,10 +247,10 @@ impl Context {
}; };
let configs = unsafe { try!(enumerate_configs(&egl, display, &egl_version, api, version)) }; let configs = unsafe { try!(enumerate_configs(&egl, display, &egl_version, api, version)) };
let (config_id, pixel_format) = try!(builder.choose_pixel_format(configs.into_iter())); let (config_id, pixel_format) = try!(pf_reqs.choose_pixel_format(configs.into_iter()));
Ok(ContextPrototype { Ok(ContextPrototype {
builder: builder, opengl: opengl,
egl: egl, egl: egl,
display: display, display: display,
egl_version: egl_version, egl_version: egl_version,
@ -330,7 +331,7 @@ impl Drop for Context {
} }
pub struct ContextPrototype<'a> { pub struct ContextPrototype<'a> {
builder: &'a BuilderAttribs<'a>, opengl: &'a GlAttributes<&'a Context>,
egl: ffi::egl::Egl, egl: ffi::egl::Egl,
display: ffi::egl::types::EGLDisplay, display: ffi::egl::types::EGLDisplay,
egl_version: (ffi::egl::types::EGLint, ffi::egl::types::EGLint), egl_version: (ffi::egl::types::EGLint, ffi::egl::types::EGLint),
@ -366,9 +367,7 @@ impl<'a> ContextPrototype<'a> {
self.finish_impl(surface) self.finish_impl(surface)
} }
pub fn finish_pbuffer(self) -> Result<Context, CreationError> { pub fn finish_pbuffer(self, dimensions: (u32, u32)) -> Result<Context, CreationError> {
let dimensions = self.builder.dimensions.unwrap_or((800, 600));
let attrs = &[ let attrs = &[
ffi::egl::WIDTH as libc::c_int, dimensions.0 as libc::c_int, ffi::egl::WIDTH as libc::c_int, dimensions.0 as libc::c_int,
ffi::egl::HEIGHT as libc::c_int, dimensions.1 as libc::c_int, ffi::egl::HEIGHT as libc::c_int, dimensions.1 as libc::c_int,
@ -394,18 +393,18 @@ impl<'a> ContextPrototype<'a> {
if let Some(version) = self.version { if let Some(version) = self.version {
try!(create_context(&self.egl, self.display, &self.egl_version, try!(create_context(&self.egl, self.display, &self.egl_version,
&self.extensions, self.api, version, self.config_id, &self.extensions, self.api, version, self.config_id,
self.builder.gl_debug, self.builder.gl_robustness)) self.opengl.debug, self.opengl.robustness))
} else if self.api == Api::OpenGlEs { } else if self.api == Api::OpenGlEs {
if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version, if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version,
&self.extensions, self.api, (2, 0), self.config_id, &self.extensions, self.api, (2, 0), self.config_id,
self.builder.gl_debug, self.builder.gl_robustness) self.opengl.debug, self.opengl.robustness)
{ {
ctxt ctxt
} else if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version, } else if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version,
&self.extensions, self.api, (1, 0), &self.extensions, self.api, (1, 0),
self.config_id, self.builder.gl_debug, self.config_id, self.opengl.debug,
self.builder.gl_robustness) self.opengl.robustness)
{ {
ctxt ctxt
} else { } else {
@ -415,19 +414,19 @@ impl<'a> ContextPrototype<'a> {
} else { } else {
if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version, if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version,
&self.extensions, self.api, (3, 2), self.config_id, &self.extensions, self.api, (3, 2), self.config_id,
self.builder.gl_debug, self.builder.gl_robustness) self.opengl.debug, self.opengl.robustness)
{ {
ctxt ctxt
} else if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version, } else if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version,
&self.extensions, self.api, (3, 1), &self.extensions, self.api, (3, 1),
self.config_id, self.builder.gl_debug, self.config_id, self.opengl.debug,
self.builder.gl_robustness) self.opengl.robustness)
{ {
ctxt ctxt
} else if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version, } else if let Ok(ctxt) = create_context(&self.egl, self.display, &self.egl_version,
&self.extensions, self.api, (1, 0), &self.extensions, self.api, (1, 0),
self.config_id, self.builder.gl_debug, self.config_id, self.opengl.debug,
self.builder.gl_robustness) self.opengl.robustness)
{ {
ctxt ctxt
} else { } else {

View file

@ -83,7 +83,7 @@ impl Window {
// setting the attributes // setting the attributes
// FIXME: // FIXME:
/*match builder.gl_version { /*match builder.opengl.version {
Some((major, minor)) => { Some((major, minor)) => {
attributes.majorVersion = major as libc::c_int; attributes.majorVersion = major as libc::c_int;
attributes.minorVersion = minor as libc::c_int; attributes.minorVersion = minor as libc::c_int;

View file

@ -1,13 +1,14 @@
#![cfg(all(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), feature = "window"))] #![cfg(all(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), feature = "window"))]
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use GlAttributes;
use GlContext; use GlContext;
use GlProfile; use GlProfile;
use GlRequest; use GlRequest;
use Api; use Api;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use libc; use libc;
@ -34,14 +35,14 @@ fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) ->
} }
impl Context { impl Context {
pub fn new<'a>(glx: ffi::glx::Glx, xlib: &ffi::Xlib, builder: &'a BuilderAttribs<'a>, pub fn new<'a>(glx: ffi::glx::Glx, xlib: &ffi::Xlib, pf_reqs: &PixelFormatRequirements,
display: *mut ffi::Display) opengl: &'a GlAttributes<&'a Context>, display: *mut ffi::Display)
-> Result<ContextPrototype<'a>, CreationError> -> Result<ContextPrototype<'a>, CreationError>
{ {
// finding the pixel format we want // finding the pixel format we want
let (fb_config, pixel_format) = { let (fb_config, pixel_format) = {
let configs = unsafe { try!(enumerate_configs(&glx, xlib, display)) }; let configs = unsafe { try!(enumerate_configs(&glx, xlib, display)) };
try!(builder.choose_pixel_format(configs.into_iter())) try!(pf_reqs.choose_pixel_format(configs.into_iter()))
}; };
// getting the visual infos // getting the visual infos
@ -57,7 +58,7 @@ impl Context {
Ok(ContextPrototype { Ok(ContextPrototype {
glx: glx, glx: glx,
builder: builder, opengl: opengl,
display: display, display: display,
fb_config: fb_config, fb_config: fb_config,
visual_infos: unsafe { mem::transmute(visual_infos) }, visual_infos: unsafe { mem::transmute(visual_infos) },
@ -120,7 +121,7 @@ impl Drop for Context {
pub struct ContextPrototype<'a> { pub struct ContextPrototype<'a> {
glx: ffi::glx::Glx, glx: ffi::glx::Glx,
builder: &'a BuilderAttribs<'a>, opengl: &'a GlAttributes<&'a Context>,
display: *mut ffi::Display, display: *mut ffi::Display,
fb_config: ffi::glx::types::GLXFBConfig, fb_config: ffi::glx::types::GLXFBConfig,
visual_infos: ffi::XVisualInfo, visual_infos: ffi::XVisualInfo,
@ -133,16 +134,9 @@ impl<'a> ContextPrototype<'a> {
} }
pub fn finish(self, window: ffi::Window) -> Result<Context, CreationError> { pub fn finish(self, window: ffi::Window) -> Result<Context, CreationError> {
let share = if let Some(win) = self.builder.sharing { let share = match self.opengl.sharing {
match win { Some(ctxt) => ctxt.context,
&PlatformWindow::X(ref win) => match win.x.context { None => ptr::null()
::api::x11::Context::Glx(ref c) => c.context,
_ => panic!("Cannot share contexts between different APIs")
},
_ => panic!("Cannot use glx on a non-X11 window.")
}
} else {
ptr::null()
}; };
// loading the list of extensions // loading the list of extensions
@ -160,46 +154,46 @@ impl<'a> ContextPrototype<'a> {
}); });
// creating GL context // creating GL context
let context = match self.builder.gl_version { let context = match self.opengl.version {
GlRequest::Latest => { GlRequest::Latest => {
if let Ok(ctxt) = create_context(&self.glx, &extra_functions, &extensions, (3, 2), if let Ok(ctxt) = create_context(&self.glx, &extra_functions, &extensions, (3, 2),
self.builder.gl_profile, self.builder.gl_debug, self.opengl.profile, self.opengl.debug,
self.builder.gl_robustness, share, self.opengl.robustness, share,
self.display, self.fb_config, &self.visual_infos) self.display, self.fb_config, &self.visual_infos)
{ {
ctxt ctxt
} else if let Ok(ctxt) = create_context(&self.glx, &extra_functions, &extensions, } else if let Ok(ctxt) = create_context(&self.glx, &extra_functions, &extensions,
(3, 1), self.builder.gl_profile, (3, 1), self.opengl.profile,
self.builder.gl_debug, self.opengl.debug,
self.builder.gl_robustness, share, self.display, self.opengl.robustness, share, self.display,
self.fb_config, &self.visual_infos) self.fb_config, &self.visual_infos)
{ {
ctxt ctxt
} else { } else {
try!(create_context(&self.glx, &extra_functions, &extensions, (1, 0), try!(create_context(&self.glx, &extra_functions, &extensions, (1, 0),
self.builder.gl_profile, self.builder.gl_debug, self.opengl.profile, self.opengl.debug,
self.builder.gl_robustness, self.opengl.robustness,
share, self.display, self.fb_config, &self.visual_infos)) share, self.display, self.fb_config, &self.visual_infos))
} }
}, },
GlRequest::Specific(Api::OpenGl, (major, minor)) => { GlRequest::Specific(Api::OpenGl, (major, minor)) => {
try!(create_context(&self.glx, &extra_functions, &extensions, (major, minor), try!(create_context(&self.glx, &extra_functions, &extensions, (major, minor),
self.builder.gl_profile, self.builder.gl_debug, self.opengl.profile, self.opengl.debug,
self.builder.gl_robustness, share, self.display, self.fb_config, self.opengl.robustness, share, self.display, self.fb_config,
&self.visual_infos)) &self.visual_infos))
}, },
GlRequest::Specific(_, _) => panic!("Only OpenGL is supported"), GlRequest::Specific(_, _) => panic!("Only OpenGL is supported"),
GlRequest::GlThenGles { opengl_version: (major, minor), .. } => { GlRequest::GlThenGles { opengl_version: (major, minor), .. } => {
try!(create_context(&self.glx, &extra_functions, &extensions, (major, minor), try!(create_context(&self.glx, &extra_functions, &extensions, (major, minor),
self.builder.gl_profile, self.builder.gl_debug, self.opengl.profile, self.opengl.debug,
self.builder.gl_robustness, share, self.display, self.fb_config, self.opengl.robustness, share, self.display, self.fb_config,
&self.visual_infos)) &self.visual_infos))
}, },
}; };
// vsync // vsync
if self.builder.vsync { if self.opengl.vsync {
unsafe { self.glx.MakeCurrent(self.display as *mut _, window, context) }; unsafe { self.glx.MakeCurrent(self.display as *mut _, window, context) };
if extra_functions.SwapIntervalEXT.is_loaded() { if extra_functions.SwapIntervalEXT.is_loaded() {
@ -209,7 +203,8 @@ impl<'a> ContextPrototype<'a> {
} }
// checking that it worked // checking that it worked
if self.builder.strict { // TODO: handle this
/*if self.builder.strict {
let mut swap = unsafe { mem::uninitialized() }; let mut swap = unsafe { mem::uninitialized() };
unsafe { unsafe {
self.glx.QueryDrawable(self.display as *mut _, window, self.glx.QueryDrawable(self.display as *mut _, window,
@ -221,7 +216,7 @@ impl<'a> ContextPrototype<'a> {
return Err(CreationError::OsError(format!("Couldn't setup vsync: expected \ return Err(CreationError::OsError(format!("Couldn't setup vsync: expected \
interval `1` but got `{}`", swap))); interval `1` but got `{}`", swap)));
} }
} }*/
// GLX_MESA_swap_control is not official // GLX_MESA_swap_control is not official
/*} else if extra_functions.SwapIntervalMESA.is_loaded() { /*} else if extra_functions.SwapIntervalMESA.is_loaded() {
@ -234,9 +229,10 @@ impl<'a> ContextPrototype<'a> {
extra_functions.SwapIntervalSGI(1); extra_functions.SwapIntervalSGI(1);
} }
} else if self.builder.strict { }/* else if self.builder.strict {
// TODO: handle this
return Err(CreationError::OsError(format!("Couldn't find any available vsync extension"))); return Err(CreationError::OsError(format!("Couldn't find any available vsync extension")));
} }*/
unsafe { self.glx.MakeCurrent(self.display as *mut _, 0, ptr::null()) }; unsafe { self.glx.MakeCurrent(self.display as *mut _, 0, ptr::null()) };
} }

View file

@ -219,7 +219,7 @@ impl Window {
let state = &mut *self.delegate_state; let state = &mut *self.delegate_state;
if builder.multitouch { if builder.window.multitouch {
let _: () = msg_send![state.view, setMultipleTouchEnabled:YES]; let _: () = msg_send![state.view, setMultipleTouchEnabled:YES];
} }

View file

@ -3,11 +3,12 @@
extern crate osmesa_sys; extern crate osmesa_sys;
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use GlAttributes;
use GlContext; use GlContext;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use libc; use libc;
use std::{mem, ptr}; use std::{mem, ptr};
@ -32,20 +33,23 @@ impl From<CreationError> for OsMesaCreationError {
} }
impl OsMesaContext { impl OsMesaContext {
pub fn new(builder: BuilderAttribs) -> Result<OsMesaContext, OsMesaCreationError> { pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&OsMesaContext>) -> Result<OsMesaContext, OsMesaCreationError>
{
if let Err(_) = osmesa_sys::OsMesa::try_loading() { if let Err(_) = osmesa_sys::OsMesa::try_loading() {
return Err(OsMesaCreationError::NotSupported); return Err(OsMesaCreationError::NotSupported);
} }
let dimensions = builder.dimensions.unwrap(); if opengl.sharing.is_some() { unimplemented!() } // TODO: proper error
match builder.gl_robustness { match opengl.robustness {
Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => { Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => {
return Err(CreationError::RobustnessNotSupported.into()); return Err(CreationError::RobustnessNotSupported.into());
}, },
_ => () _ => ()
} }
// TODO: use `pf_reqs` for the format
// TODO: check OpenGL version and return `OpenGlVersionNotSupported` if necessary // TODO: check OpenGL version and return `OpenGlVersionNotSupported` if necessary
Ok(OsMesaContext { Ok(OsMesaContext {

View file

@ -13,14 +13,16 @@ use api::dlopen;
use api::egl; use api::egl;
use api::egl::Context as EglContext; use api::egl::Context as EglContext;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use Event; use Event;
use PixelFormat; use PixelFormat;
use CursorState; use CursorState;
use MouseCursor; use MouseCursor;
use GlAttributes;
use GlContext; use GlContext;
use PixelFormatRequirements;
use WindowAttributes;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
@ -241,7 +243,9 @@ impl<'a> Iterator for WaitEventsIterator<'a> {
} }
impl Window { impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
use self::wayland::internals::FFI; use self::wayland::internals::FFI;
let wayland_context = match *WAYLAND_CONTEXT { let wayland_context = match *WAYLAND_CONTEXT {
@ -251,7 +255,7 @@ impl Window {
if !is_egl_available() { return Err(CreationError::NotSupported) } if !is_egl_available() { return Err(CreationError::NotSupported) }
let (w, h) = builder.dimensions.unwrap_or((800, 600)); let (w, h) = window.dimensions.unwrap_or((800, 600));
let surface = EGLSurface::new( let surface = EGLSurface::new(
wayland_context.compositor.create_surface(), wayland_context.compositor.create_surface(),
@ -259,12 +263,12 @@ impl Window {
h as i32 h as i32
); );
let mut shell_window = if let Some(PlatformMonitorID::Wayland(ref monitor)) = builder.monitor { let mut shell_window = if let Some(PlatformMonitorID::Wayland(ref monitor)) = window.monitor {
let shell_surface = wayland_context.shell.get_shell_surface(surface); let shell_surface = wayland_context.shell.get_shell_surface(surface);
shell_surface.set_fullscreen(ShellFullscreenMethod::Default, Some(&monitor.output)); shell_surface.set_fullscreen(ShellFullscreenMethod::Default, Some(&monitor.output));
ShellWindow::Plain(shell_surface) ShellWindow::Plain(shell_surface)
} else { } else {
if builder.decorations { if window.decorations {
ShellWindow::Decorated(match DecoratedSurface::new( ShellWindow::Decorated(match DecoratedSurface::new(
surface, surface,
w as i32, w as i32,
@ -291,7 +295,7 @@ impl Window {
}); });
try!(EglContext::new( try!(EglContext::new(
egl, egl,
&builder, pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()), // TODO:
egl::NativeDisplay::Wayland(Some(wayland_context.display.ptr() as *const _))) egl::NativeDisplay::Wayland(Some(wayland_context.display.ptr() as *const _)))
.and_then(|p| p.finish((**shell_window.get_shell()).ptr() as *const _)) .and_then(|p| p.finish((**shell_window.get_shell()).ptr() as *const _))
) )

View file

@ -1,12 +1,13 @@
#![cfg(any(target_os = "windows"))] #![cfg(any(target_os = "windows"))]
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use GlAttributes;
use GlContext; use GlContext;
use GlRequest; use GlRequest;
use GlProfile; use GlProfile;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use Api; use Api;
@ -74,9 +75,8 @@ impl Context {
/// # Unsafety /// # Unsafety
/// ///
/// The `window` must continue to exist as long as the resulting `Context` exists. /// The `window` must continue to exist as long as the resulting `Context` exists.
pub unsafe fn new(builder: &BuilderAttribs<'static>, window: winapi::HWND, pub unsafe fn new(pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<winapi::HGLRC>,
builder_sharelists: Option<winapi::HGLRC>) window: winapi::HWND) -> Result<Context, CreationError>
-> Result<Context, CreationError>
{ {
let hdc = user32::GetDC(window); let hdc = user32::GetDC(window);
if hdc.is_null() { if hdc.is_null() {
@ -118,20 +118,20 @@ impl Context {
enumerate_native_pixel_formats(hdc) enumerate_native_pixel_formats(hdc)
}; };
let (id, f) = try!(builder.choose_pixel_format(formats)); let (id, f) = try!(pf_reqs.choose_pixel_format(formats));
try!(set_pixel_format(hdc, id)); try!(set_pixel_format(hdc, id));
f f
}; };
// creating the OpenGL context // creating the OpenGL context
let context = try!(create_context(Some((&extra_functions, builder, &extensions)), let context = try!(create_context(Some((&extra_functions, pf_reqs, opengl, &extensions)),
window, hdc, builder_sharelists)); window, hdc));
// loading the opengl32 module // loading the opengl32 module
let gl_library = try!(load_opengl32_dll()); let gl_library = try!(load_opengl32_dll());
// handling vsync // handling vsync
if builder.vsync { if opengl.vsync {
if extensions.split(' ').find(|&i| i == "WGL_EXT_swap_control").is_some() { if extensions.split(' ').find(|&i| i == "WGL_EXT_swap_control").is_some() {
let _guard = try!(CurrentContextGuard::make_current(hdc, context.0)); let _guard = try!(CurrentContextGuard::make_current(hdc, context.0));
@ -210,17 +210,20 @@ unsafe impl Sync for Context {}
/// ///
/// Otherwise, only the basic API will be used and the chances of `CreationError::NotSupported` /// Otherwise, only the basic API will be used and the chances of `CreationError::NotSupported`
/// being returned increase. /// being returned increase.
unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'static>, &str)>, unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &PixelFormatRequirements,
_: winapi::HWND, hdc: winapi::HDC, share: Option<winapi::HGLRC>) &GlAttributes<winapi::HGLRC>, &str)>,
_: winapi::HWND, hdc: winapi::HDC)
-> Result<ContextWrapper, CreationError> -> Result<ContextWrapper, CreationError>
{ {
let share = share.unwrap_or(ptr::null_mut()); let share;
if let Some((extra_functions, pf_reqs, opengl, extensions)) = extra {
share = opengl.sharing.unwrap_or(ptr::null_mut());
if let Some((extra_functions, builder, extensions)) = extra {
if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context").is_some() { if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context").is_some() {
let mut attributes = Vec::new(); let mut attributes = Vec::new();
match builder.gl_version { match opengl.version {
GlRequest::Latest => {}, GlRequest::Latest => {},
GlRequest::Specific(Api::OpenGl, (major, minor)) => { GlRequest::Specific(Api::OpenGl, (major, minor)) => {
attributes.push(gl::wgl_extra::CONTEXT_MAJOR_VERSION_ARB as libc::c_int); attributes.push(gl::wgl_extra::CONTEXT_MAJOR_VERSION_ARB as libc::c_int);
@ -252,7 +255,7 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st
}, },
} }
if let Some(profile) = builder.gl_profile { if let Some(profile) = opengl.profile {
if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context_profile").is_some() if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context_profile").is_some()
{ {
let flag = match profile { let flag = match profile {
@ -273,7 +276,7 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st
// robustness // robustness
if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context_robustness").is_some() { if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context_robustness").is_some() {
match builder.gl_robustness { match opengl.robustness {
Robustness::RobustNoResetNotification | Robustness::TryRobustNoResetNotification => { Robustness::RobustNoResetNotification | Robustness::TryRobustNoResetNotification => {
attributes.push(gl::wgl_extra::CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB as libc::c_int); attributes.push(gl::wgl_extra::CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB as libc::c_int);
attributes.push(gl::wgl_extra::NO_RESET_NOTIFICATION_ARB as libc::c_int); attributes.push(gl::wgl_extra::NO_RESET_NOTIFICATION_ARB as libc::c_int);
@ -288,7 +291,7 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st
Robustness::NoError => (), Robustness::NoError => (),
} }
} else { } else {
match builder.gl_robustness { match opengl.robustness {
Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => { Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => {
return Err(CreationError::RobustnessNotSupported); return Err(CreationError::RobustnessNotSupported);
}, },
@ -296,7 +299,7 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st
} }
} }
if builder.gl_debug { if opengl.debug {
flags = flags | gl::wgl_extra::CONTEXT_DEBUG_BIT_ARB as libc::c_int; flags = flags | gl::wgl_extra::CONTEXT_DEBUG_BIT_ARB as libc::c_int;
} }
@ -319,7 +322,10 @@ unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &BuilderAttribs<'st
return Ok(ContextWrapper(ctxt as winapi::HGLRC)); return Ok(ContextWrapper(ctxt as winapi::HGLRC));
} }
} }
};
} else {
share = ptr::null_mut();
}
let ctxt = gl::wgl::CreateContext(hdc as *const libc::c_void); let ctxt = gl::wgl::CreateContext(hdc as *const libc::c_void);
if ctxt.is_null() { if ctxt.is_null() {
@ -544,7 +550,7 @@ unsafe fn load_extra_functions(window: winapi::HWND) -> Result<gl::wgl_extra::Wg
} }
// creating the dummy OpenGL context and making it current // creating the dummy OpenGL context and making it current
let dummy_context = try!(create_context(None, dummy_window.0, dummy_window.1, None)); let dummy_context = try!(create_context(None, dummy_window.0, dummy_window.1));
let _current_context = try!(CurrentContextGuard::make_current(dummy_window.1, let _current_context = try!(CurrentContextGuard::make_current(dummy_window.1,
dummy_context.0)); dummy_context.0));

View file

@ -11,11 +11,13 @@ use super::WindowWrapper;
use super::Context; use super::Context;
use Api; use Api;
use BuilderAttribs;
use CreationError; use CreationError;
use CreationError::OsError; use CreationError::OsError;
use CursorState; use CursorState;
use GlAttributes;
use GlRequest; use GlRequest;
use PixelFormatRequirements;
use WindowAttributes;
use std::ffi::{OsStr}; use std::ffi::{OsStr};
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
@ -31,6 +33,7 @@ use api::egl;
use api::egl::Context as EglContext; use api::egl::Context as EglContext;
use api::egl::ffi::egl::Egl; use api::egl::ffi::egl::Egl;
#[derive(Clone)]
pub enum RawContext { pub enum RawContext {
Egl(egl::ffi::egl::types::EGLContext), Egl(egl::ffi::egl::types::EGLContext),
Wgl(winapi::HGLRC), Wgl(winapi::HGLRC),
@ -39,15 +42,18 @@ pub enum RawContext {
unsafe impl Send for RawContext {} unsafe impl Send for RawContext {}
unsafe impl Sync for RawContext {} unsafe impl Sync for RawContext {}
pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<RawContext>, pub fn new_window(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
egl: Option<&Egl>) opengl: &GlAttributes<RawContext>, egl: Option<&Egl>)
-> Result<Window, CreationError> -> Result<Window, CreationError>
{ {
let egl = egl.map(|e| e.clone()); let egl = egl.map(|e| e.clone());
let window = window.clone();
let pf_reqs = pf_reqs.clone();
let opengl = opengl.clone();
// initializing variables to be sent to the task // initializing variables to be sent to the task
let title = OsStr::new(&builder.title).encode_wide().chain(Some(0).into_iter()) let title = OsStr::new(&window.title).encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let (tx, rx) = channel(); let (tx, rx) = channel();
@ -57,7 +63,7 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<R
thread::spawn(move || { thread::spawn(move || {
unsafe { unsafe {
// creating and sending the `Window` // creating and sending the `Window`
match init(title, builder, builder_sharelists, egl) { match init(title, &window, &pf_reqs, &opengl, egl) {
Ok(w) => tx.send(Ok(w)).ok(), Ok(w) => tx.send(Ok(w)).ok(),
Err(e) => { Err(e) => {
tx.send(Err(e)).ok(); tx.send(Err(e)).ok();
@ -83,29 +89,36 @@ pub fn new_window(builder: BuilderAttribs<'static>, builder_sharelists: Option<R
rx.recv().unwrap() rx.recv().unwrap()
} }
unsafe fn init(title: Vec<u16>, builder: BuilderAttribs<'static>, unsafe fn init(title: Vec<u16>, window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
builder_sharelists: Option<RawContext>, egl: Option<Egl>) opengl: &GlAttributes<RawContext>, egl: Option<Egl>)
-> Result<Window, CreationError> -> Result<Window, CreationError>
{ {
let opengl = opengl.clone().map_sharing(|sharelists| {
match sharelists {
RawContext::Wgl(c) => c,
_ => unimplemented!()
}
});
// registering the window class // registering the window class
let class_name = register_window_class(); let class_name = register_window_class();
// building a RECT object with coordinates // building a RECT object with coordinates
let mut rect = winapi::RECT { let mut rect = winapi::RECT {
left: 0, right: builder.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG, left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG,
top: 0, bottom: builder.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG, top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG,
}; };
// switching to fullscreen if necessary // switching to fullscreen if necessary
// this means adjusting the window's position so that it overlaps the right monitor, // this means adjusting the window's position so that it overlaps the right monitor,
// and change the monitor's resolution if necessary // and change the monitor's resolution if necessary
if builder.monitor.is_some() { if window.monitor.is_some() {
let monitor = builder.monitor.as_ref().unwrap(); let monitor = window.monitor.as_ref().unwrap();
try!(switch_to_fullscreen(&mut rect, monitor)); try!(switch_to_fullscreen(&mut rect, monitor));
} }
// computing the style and extended style of the window // computing the style and extended style of the window
let (ex_style, style) = if builder.monitor.is_some() || builder.decorations == false { let (ex_style, style) = if window.monitor.is_some() || window.decorations == false {
(winapi::WS_EX_APPWINDOW, winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN) (winapi::WS_EX_APPWINDOW, winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN)
} else { } else {
(winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE, (winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE,
@ -117,19 +130,19 @@ unsafe fn init(title: Vec<u16>, builder: BuilderAttribs<'static>,
// creating the real window this time, by using the functions in `extra_functions` // creating the real window this time, by using the functions in `extra_functions`
let real_window = { let real_window = {
let (width, height) = if builder.monitor.is_some() || builder.dimensions.is_some() { let (width, height) = if window.monitor.is_some() || window.dimensions.is_some() {
(Some(rect.right - rect.left), Some(rect.bottom - rect.top)) (Some(rect.right - rect.left), Some(rect.bottom - rect.top))
} else { } else {
(None, None) (None, None)
}; };
let (x, y) = if builder.monitor.is_some() { let (x, y) = if window.monitor.is_some() {
(Some(rect.left), Some(rect.top)) (Some(rect.left), Some(rect.top))
} else { } else {
(None, None) (None, None)
}; };
let style = if !builder.visible || builder.headless { let style = if !window.visible {
style style
} else { } else {
style | winapi::WS_VISIBLE style | winapi::WS_VISIBLE
@ -159,51 +172,33 @@ unsafe fn init(title: Vec<u16>, builder: BuilderAttribs<'static>,
}; };
// creating the OpenGL context // creating the OpenGL context
let context = match builder.gl_version { let context = match opengl.version {
GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => { GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => {
if let Some(egl) = egl { if let Some(egl) = egl {
if let Ok(c) = EglContext::new(egl, &builder, if let Ok(c) = EglContext::new(egl, &pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()),
egl::NativeDisplay::Other(Some(ptr::null()))) egl::NativeDisplay::Other(Some(ptr::null())))
.and_then(|p| p.finish(real_window.0)) .and_then(|p| p.finish(real_window.0))
{ {
Context::Egl(c) Context::Egl(c)
} else { } else {
let builder_sharelists = match builder_sharelists { try!(WglContext::new(&pf_reqs, &opengl, real_window.0)
None => None,
Some(RawContext::Wgl(c)) => Some(c),
_ => unimplemented!()
};
try!(WglContext::new(&builder, real_window.0, builder_sharelists)
.map(Context::Wgl)) .map(Context::Wgl))
} }
} else { } else {
// falling back to WGL, which is always available // falling back to WGL, which is always available
let builder_sharelists = match builder_sharelists { try!(WglContext::new(&pf_reqs, &opengl, real_window.0)
None => None,
Some(RawContext::Wgl(c)) => Some(c),
_ => unimplemented!()
};
try!(WglContext::new(&builder, real_window.0, builder_sharelists)
.map(Context::Wgl)) .map(Context::Wgl))
} }
}, },
_ => { _ => {
let builder_sharelists = match builder_sharelists { try!(WglContext::new(&pf_reqs, &opengl, real_window.0).map(Context::Wgl))
None => None,
Some(RawContext::Wgl(c)) => Some(c),
_ => unimplemented!()
};
try!(WglContext::new(&builder, real_window.0, builder_sharelists).map(Context::Wgl))
} }
}; };
// making the window transparent // making the window transparent
if builder.transparent { if window.transparent {
let bb = winapi::DWM_BLURBEHIND { let bb = winapi::DWM_BLURBEHIND {
dwFlags: 0x1, // FIXME: DWM_BB_ENABLE; dwFlags: 0x1, // FIXME: DWM_BB_ENABLE;
fEnable: 1, fEnable: 1,
@ -215,7 +210,7 @@ unsafe fn init(title: Vec<u16>, builder: BuilderAttribs<'static>,
} }
// calling SetForegroundWindow if fullscreen // calling SetForegroundWindow if fullscreen
if builder.monitor.is_some() { if window.monitor.is_some() {
user32::SetForegroundWindow(real_window.0); user32::SetForegroundWindow(real_window.0);
} }

View file

@ -13,11 +13,13 @@ use libc;
use ContextError; use ContextError;
use {CreationError, Event, MouseCursor}; use {CreationError, Event, MouseCursor};
use CursorState; use CursorState;
use GlAttributes;
use GlContext; use GlContext;
use Api; use Api;
use PixelFormat; use PixelFormat;
use BuilderAttribs; use PixelFormatRequirements;
use WindowAttributes;
pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor};
@ -83,15 +85,18 @@ impl WindowProxy {
impl Window { impl Window {
/// See the docs in the crate root file. /// See the docs in the crate root file.
pub fn new(builder: BuilderAttribs, egl: Option<&Egl>) -> Result<Window, CreationError> { pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
let (builder, sharing) = builder.extract_non_static(); opengl: &GlAttributes<&Window>, egl: Option<&Egl>)
-> Result<Window, CreationError>
let sharing = sharing.map(|w| match w.context { {
let opengl = opengl.clone().map_sharing(|sharing| {
match sharing.context {
Context::Wgl(ref c) => RawContext::Wgl(c.get_hglrc()), Context::Wgl(ref c) => RawContext::Wgl(c.get_hglrc()),
Context::Egl(_) => unimplemented!(), // FIXME: Context::Egl(_) => unimplemented!(), // FIXME:
}
}); });
init::new_window(builder, sharing, egl) init::new_window(window, pf_reqs, &opengl, egl)
} }
/// See the docs in the crate root file. /// See the docs in the crate root file.

View file

@ -1,4 +1,4 @@
use {Event, BuilderAttribs, MouseCursor}; use {Event, MouseCursor};
use CreationError; use CreationError;
use CreationError::OsError; use CreationError::OsError;
use libc; use libc;
@ -12,9 +12,12 @@ use std::sync::{Arc, Mutex};
use Api; use Api;
use ContextError; use ContextError;
use CursorState; use CursorState;
use GlAttributes;
use GlContext; use GlContext;
use GlRequest; use GlRequest;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use WindowAttributes;
use api::glx::Context as GlxContext; use api::glx::Context as GlxContext;
use api::egl; use api::egl;
@ -295,10 +298,13 @@ pub struct Window {
} }
impl Window { impl Window {
pub fn new(display: &Arc<XConnection>, builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(display: &Arc<XConnection>, window_attrs: &WindowAttributes,
let dimensions = builder.dimensions.unwrap_or((800, 600)); pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<&Window>)
-> Result<Window, CreationError>
{
let dimensions = window_attrs.dimensions.unwrap_or((800, 600));
let screen_id = match builder.monitor { let screen_id = match window_attrs.monitor {
Some(PlatformMonitorID::X(MonitorID(_, monitor))) => monitor as i32, Some(PlatformMonitorID::X(MonitorID(_, monitor))) => monitor as i32,
_ => unsafe { (display.xlib.XDefaultScreen)(display.display) }, _ => unsafe { (display.xlib.XDefaultScreen)(display.display) },
}; };
@ -316,7 +322,7 @@ impl Window {
// FIXME: `XF86VidModeModeInfo` is missing its `hskew` field. Therefore we point to // FIXME: `XF86VidModeModeInfo` is missing its `hskew` field. Therefore we point to
// `vsyncstart` instead of `vdisplay` as a temporary hack. // `vsyncstart` instead of `vdisplay` as a temporary hack.
let mode_to_switch_to = if builder.monitor.is_some() { let mode_to_switch_to = if window_attrs.monitor.is_some() {
let matching_mode = (0 .. mode_num).map(|i| { let matching_mode = (0 .. mode_num).map(|i| {
let m: ffi::XF86VidModeModeInfo = ptr::read(*modes.offset(i as isize) as *const _); m let m: ffi::XF86VidModeModeInfo = ptr::read(*modes.offset(i as isize) as *const _); m
}).find(|m| m.hdisplay == dimensions.0 as u16 && m.vsyncstart == dimensions.1 as u16); }).find(|m| m.hdisplay == dimensions.0 as u16 && m.vsyncstart == dimensions.1 as u16);
@ -348,22 +354,23 @@ impl Window {
Glx(::api::glx::ContextPrototype<'a>), Glx(::api::glx::ContextPrototype<'a>),
Egl(::api::egl::ContextPrototype<'a>), Egl(::api::egl::ContextPrototype<'a>),
} }
let builder_clone = builder.clone(); let builder_clone_opengl_glx = opengl.clone().map_sharing(|_| unimplemented!()); // FIXME:
let context = match builder.gl_version { let builder_clone_opengl_egl = opengl.clone().map_sharing(|_| unimplemented!()); // FIXME:
let context = match opengl.version {
GlRequest::Latest | GlRequest::Specific(Api::OpenGl, _) | GlRequest::GlThenGles { .. } => { GlRequest::Latest | GlRequest::Specific(Api::OpenGl, _) | GlRequest::GlThenGles { .. } => {
// GLX should be preferred over EGL, otherwise crashes may occur // GLX should be preferred over EGL, otherwise crashes may occur
// on X11 issue #314 // on X11 issue #314
if let Some(ref glx) = display.glx { if let Some(ref glx) = display.glx {
Prototype::Glx(try!(GlxContext::new(glx.clone(), &display.xlib, &builder_clone, display.display))) Prototype::Glx(try!(GlxContext::new(glx.clone(), &display.xlib, pf_reqs, &builder_clone_opengl_glx, display.display)))
} else if let Some(ref egl) = display.egl { } else if let Some(ref egl) = display.egl {
Prototype::Egl(try!(EglContext::new(egl.clone(), &builder_clone, egl::NativeDisplay::X11(Some(display.display as *const _))))) Prototype::Egl(try!(EglContext::new(egl.clone(), pf_reqs, &builder_clone_opengl_egl, egl::NativeDisplay::X11(Some(display.display as *const _)))))
} else { } else {
return Err(CreationError::NotSupported); return Err(CreationError::NotSupported);
} }
}, },
GlRequest::Specific(Api::OpenGlEs, _) => { GlRequest::Specific(Api::OpenGlEs, _) => {
if let Some(ref egl) = display.egl { if let Some(ref egl) = display.egl {
Prototype::Egl(try!(EglContext::new(egl.clone(), &builder_clone, egl::NativeDisplay::X11(Some(display.display as *const _))))) Prototype::Egl(try!(EglContext::new(egl.clone(), pf_reqs, &builder_clone_opengl_egl, egl::NativeDisplay::X11(Some(display.display as *const _)))))
} else { } else {
return Err(CreationError::NotSupported); return Err(CreationError::NotSupported);
} }
@ -415,7 +422,7 @@ impl Window {
ffi::KeyReleaseMask | ffi::ButtonPressMask | ffi::KeyReleaseMask | ffi::ButtonPressMask |
ffi::ButtonReleaseMask | ffi::KeymapStateMask; ffi::ButtonReleaseMask | ffi::KeymapStateMask;
swa.border_pixel = 0; swa.border_pixel = 0;
if builder.transparent { if window_attrs.transparent {
swa.background_pixel = 0; swa.background_pixel = 0;
} }
swa.override_redirect = 0; swa.override_redirect = 0;
@ -424,7 +431,7 @@ impl Window {
let mut window_attributes = ffi::CWBorderPixel | ffi::CWColormap | ffi::CWEventMask; let mut window_attributes = ffi::CWBorderPixel | ffi::CWColormap | ffi::CWEventMask;
if builder.transparent { if window_attrs.transparent {
window_attributes |= ffi::CWBackPixel; window_attributes |= ffi::CWBackPixel;
} }
@ -448,7 +455,7 @@ impl Window {
}; };
// set visibility // set visibility
if builder.visible { if window_attrs.visible {
unsafe { unsafe {
(display.xlib.XMapRaised)(display.display, window); (display.xlib.XMapRaised)(display.display, window);
(display.xlib.XFlush)(display.display); (display.xlib.XFlush)(display.display);
@ -461,7 +468,7 @@ impl Window {
(display.xlib.XInternAtom)(display.display, delete_window, 0) (display.xlib.XInternAtom)(display.display, delete_window, 0)
); );
(display.xlib.XSetWMProtocols)(display.display, window, &mut wm_delete_window, 1); (display.xlib.XSetWMProtocols)(display.display, window, &mut wm_delete_window, 1);
with_c_str(&*builder.title, |title| {; with_c_str(&*window_attrs.title, |title| {;
(display.xlib.XStoreName)(display.display, window, title); (display.xlib.XStoreName)(display.display, window, title);
}); });
(display.xlib.XFlush)(display.display); (display.xlib.XFlush)(display.display);
@ -509,7 +516,7 @@ impl Window {
// Set ICCCM WM_CLASS property based on initial window title // Set ICCCM WM_CLASS property based on initial window title
unsafe { unsafe {
with_c_str(&*builder.title, |c_name| { with_c_str(&*window_attrs.title, |c_name| {
let hint = (display.xlib.XAllocClassHint)(); let hint = (display.xlib.XAllocClassHint)();
(*hint).res_name = c_name as *mut libc::c_char; (*hint).res_name = c_name as *mut libc::c_char;
(*hint).res_class = c_name as *mut libc::c_char; (*hint).res_class = c_name as *mut libc::c_char;
@ -518,7 +525,7 @@ impl Window {
}); });
} }
let is_fullscreen = builder.monitor.is_some(); let is_fullscreen = window_attrs.monitor.is_some();
// finish creating the OpenGL context // finish creating the OpenGL context
let context = match context { let context = match context {

View file

@ -1,11 +1,13 @@
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use GlAttributes;
use GlRequest; use GlRequest;
use GlContext; use GlContext;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use WindowAttributes;
use gl_common; use gl_common;
use libc; use libc;
@ -13,25 +15,25 @@ use libc;
use platform; use platform;
/// Object that allows you to build headless contexts. /// Object that allows you to build headless contexts.
pub struct HeadlessRendererBuilder { pub struct HeadlessRendererBuilder<'a> {
attribs: BuilderAttribs<'static>, dimensions: (u32, u32),
pf_reqs: PixelFormatRequirements,
opengl: GlAttributes<&'a platform::HeadlessContext>,
} }
impl HeadlessRendererBuilder { impl<'a> HeadlessRendererBuilder<'a> {
/// Initializes a new `HeadlessRendererBuilder` with default values. /// Initializes a new `HeadlessRendererBuilder` with default values.
pub fn new(width: u32, height: u32) -> HeadlessRendererBuilder { pub fn new(width: u32, height: u32) -> HeadlessRendererBuilder<'a> {
HeadlessRendererBuilder { HeadlessRendererBuilder {
attribs: BuilderAttribs { dimensions: (width, height),
headless: true, pf_reqs: Default::default(),
dimensions: Some((width, height)), opengl: Default::default(),
.. BuilderAttribs::new()
},
} }
} }
/// Sets how the backend should choose the OpenGL API and version. /// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> HeadlessRendererBuilder { pub fn with_gl(mut self, request: GlRequest) -> HeadlessRendererBuilder<'a> {
self.attribs.gl_version = request; self.opengl.version = request;
self self
} }
@ -39,14 +41,14 @@ impl HeadlessRendererBuilder {
/// ///
/// The default value for this flag is `cfg!(ndebug)`, which means that it's enabled /// The default value for this flag is `cfg!(ndebug)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`. /// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> HeadlessRendererBuilder { pub fn with_gl_debug_flag(mut self, flag: bool) -> HeadlessRendererBuilder<'a> {
self.attribs.gl_debug = flag; self.opengl.debug = flag;
self self
} }
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`. /// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> HeadlessRendererBuilder { pub fn with_gl_robustness(mut self, robustness: Robustness) -> HeadlessRendererBuilder<'a> {
self.attribs.gl_robustness = robustness; self.opengl.robustness = robustness;
self self
} }
@ -55,15 +57,15 @@ impl HeadlessRendererBuilder {
/// Error should be very rare and only occur in case of permission denied, incompatible system, /// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc. /// out of memory, etc.
pub fn build(self) -> Result<HeadlessContext, CreationError> { pub fn build(self) -> Result<HeadlessContext, CreationError> {
platform::HeadlessContext::new(self.attribs).map(|w| HeadlessContext { context: w }) platform::HeadlessContext::new(self.dimensions, &self.pf_reqs, &self.opengl)
.map(|w| HeadlessContext { context: w })
} }
/// Builds the headless context. /// Builds the headless context.
/// ///
/// The context is build in a *strict* way. That means that if the backend couldn't give /// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned. /// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<HeadlessContext, CreationError> { pub fn build_strict(self) -> Result<HeadlessContext, CreationError> {
self.attribs.strict = true;
self.build() self.build()
} }
} }

View file

@ -363,98 +363,20 @@ pub struct PixelFormat {
pub srgb: bool, pub srgb: bool,
} }
/// Attributes /// VERY UNSTABLE! Describes how the backend should choose a pixel format.
// FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[derive(Clone, Debug)]
#[derive(Clone)] #[allow(missing_docs)]
#[doc(hidden)] pub struct PixelFormatRequirements {
pub struct BuilderAttribs<'a> { pub multisampling: Option<u16>,
#[allow(dead_code)] pub depth_bits: Option<u8>,
headless: bool, pub stencil_bits: Option<u8>,
strict: bool, pub color_bits: Option<u8>,
sharing: Option<&'a platform::Window>, pub alpha_bits: Option<u8>,
dimensions: Option<(u32, u32)>, pub stereoscopy: bool,
title: String, pub srgb: Option<bool>,
monitor: Option<platform::MonitorID>,
gl_version: GlRequest,
gl_profile: Option<GlProfile>,
gl_debug: bool,
gl_robustness: Robustness,
vsync: bool,
visible: bool,
multisampling: Option<u16>,
depth_bits: Option<u8>,
stencil_bits: Option<u8>,
color_bits: Option<u8>,
alpha_bits: Option<u8>,
stereoscopy: bool,
srgb: Option<bool>,
transparent: bool,
decorations: bool,
multitouch: bool
} }
impl BuilderAttribs<'static> { impl PixelFormatRequirements {
fn new() -> BuilderAttribs<'static> {
BuilderAttribs {
headless: false,
strict: false,
sharing: None,
dimensions: None,
title: "glutin window".to_string(),
monitor: None,
gl_version: GlRequest::Latest,
gl_profile: None,
gl_debug: cfg!(debug_assertions),
gl_robustness: Robustness::NotRobust,
vsync: false,
visible: true,
multisampling: None,
depth_bits: None,
stencil_bits: None,
color_bits: None,
alpha_bits: None,
stereoscopy: false,
srgb: None,
transparent: false,
decorations: true,
multitouch: false
}
}
}
impl<'a> BuilderAttribs<'a> {
#[allow(dead_code)]
fn extract_non_static(mut self) -> (BuilderAttribs<'static>, Option<&'a platform::Window>) {
let sharing = self.sharing.take();
let new_attribs = BuilderAttribs {
headless: self.headless,
strict: self.strict,
sharing: None,
dimensions: self.dimensions,
title: self.title,
monitor: self.monitor,
gl_version: self.gl_version,
gl_profile: self.gl_profile,
gl_debug: self.gl_debug,
gl_robustness: self.gl_robustness,
vsync: self.vsync,
visible: self.visible,
multisampling: self.multisampling,
depth_bits: self.depth_bits,
stencil_bits: self.stencil_bits,
color_bits: self.color_bits,
alpha_bits: self.alpha_bits,
stereoscopy: self.stereoscopy,
srgb: self.srgb,
transparent: self.transparent,
decorations: self.decorations,
multitouch: self.multitouch
};
(new_attribs, sharing)
}
fn choose_pixel_format<T, I>(&self, iter: I) -> Result<(T, PixelFormat), CreationError> fn choose_pixel_format<T, I>(&self, iter: I) -> Result<(T, PixelFormat), CreationError>
where I: IntoIterator<Item=(T, PixelFormat)>, T: Clone where I: IntoIterator<Item=(T, PixelFormat)>, T: Clone
{ {
@ -555,6 +477,138 @@ impl<'a> BuilderAttribs<'a> {
} }
} }
impl Default for PixelFormatRequirements {
fn default() -> PixelFormatRequirements {
PixelFormatRequirements {
multisampling: None,
depth_bits: None,
stencil_bits: None,
color_bits: None,
alpha_bits: None,
stereoscopy: false,
srgb: None,
}
}
}
/// Attributes to use when creating a window.
#[derive(Clone)]
pub struct WindowAttributes {
/// The dimensions of the window. If this is `None`, some platform-specific dimensions will be
/// used.
///
/// The default is `None`.
pub dimensions: Option<(u32, u32)>,
/// If `Some`, the window will be in fullscreen mode with the given monitor.
///
/// The default is `None`.
pub monitor: Option<platform::MonitorID>,
/// The title of the window in the title bar.
///
/// The default is `"glutin window"`.
pub title: String,
/// Whether the window should be immediately visible upon creation.
///
/// The default is `true`.
pub visible: bool,
/// Whether the the window should be transparent. If this is true, writing colors
/// with alpha values different than `1.0` will produce a transparent window.
///
/// The default is `false`.
pub transparent: bool,
/// Whether the window should have borders and bars.
///
/// The default is `true`.
pub decorations: bool,
/// ??? TODO: document me
pub multitouch: bool,
}
impl Default for WindowAttributes {
fn default() -> WindowAttributes {
WindowAttributes {
dimensions: None,
monitor: None,
title: "glutin window".to_owned(),
visible: true,
transparent: false,
decorations: true,
multitouch: false,
}
}
}
/// Attributes to use when creating an OpenGL context.
#[derive(Clone)]
pub struct GlAttributes<S> {
/// An existing context to share the new the context with.
///
/// The default is `None`.
pub sharing: Option<S>,
/// Version to try create. See `GlRequest` for more infos.
///
/// The default is `Latest`.
pub version: GlRequest,
/// OpenGL profile to use.
///
/// The default is `None`.
pub profile: Option<GlProfile>,
/// Whether to enable the `debug` flag of the context.
///
/// Debug contexts are usually slower but give better error reporting.
///
/// The default is `true` in debug mode and `false` in release mode.
pub debug: bool,
/// How the OpenGL context should detect errors.
///
/// The default is `NotRobust` because this is what is typically expected when you create an
/// OpenGL context. However for safety you should consider `TryRobustLoseContextOnReset`.
pub robustness: Robustness,
/// Whether to use vsync. If vsync is enabled, calling `swap_buffers` will block until the
/// screen refreshes. This is typically used to prevent screen tearing.
///
/// The default is `false`.
pub vsync: bool,
}
impl<S> GlAttributes<S> {
/// Turns the `sharing` parameter into another type by calling a closure.
pub fn map_sharing<F, T>(self, f: F) -> GlAttributes<T> where F: FnOnce(S) -> T {
GlAttributes {
sharing: self.sharing.map(f),
version: self.version,
profile: self.profile,
debug: self.debug,
robustness: self.robustness,
vsync: self.vsync,
}
}
}
impl<S> Default for GlAttributes<S> {
fn default() -> GlAttributes<S> {
GlAttributes {
sharing: None,
version: GlRequest::Latest,
profile: None,
debug: cfg!(debug_assertions),
robustness: Robustness::NotRobust,
vsync: false,
}
}
}
mod native_monitor { mod native_monitor {
/// Native platform identifier for a monitor. Different platforms use fundamentally different types /// Native platform identifier for a monitor. Different platforms use fundamentally different types
/// to represent a monitor ID. /// to represent a monitor ID.

View file

@ -6,14 +6,16 @@ pub use api::x11::{WaitEventsIterator, PollEventsIterator};*/
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::Arc; use std::sync::Arc;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use CursorState; use CursorState;
use Event; use Event;
use GlAttributes;
use GlContext; use GlContext;
use MouseCursor; use MouseCursor;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use WindowAttributes;
use libc; use libc;
use api::wayland; use api::wayland;
@ -161,10 +163,28 @@ impl<'a> Iterator for WaitEventsIterator<'a> {
} }
impl Window { impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
match *BACKEND { match *BACKEND {
Backend::Wayland => wayland::Window::new(builder).map(Window::Wayland), Backend::Wayland => {
Backend::X(ref connec) => x11::Window::new(connec, builder).map(Window::X), let opengl = opengl.clone().map_sharing(|w| match w {
&Window::Wayland(ref w) => w,
_ => panic!() // TODO: return an error
});
wayland::Window::new(window, pf_reqs, &opengl).map(Window::Wayland)
},
Backend::X(ref connec) => {
let opengl = opengl.clone().map_sharing(|w| match w {
&Window::X(ref w) => w,
_ => panic!() // TODO: return an error
});
x11::Window::new(connec, window, pf_reqs, &opengl).map(Window::X)
},
Backend::Error(ref error) => Err(CreationError::NoBackendAvailable(Box::new(error.clone()))) Backend::Error(ref error) => Err(CreationError::NoBackendAvailable(Box::new(error.clone())))
} }
} }

View file

@ -1,11 +1,12 @@
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"))] #![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"))]
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use GlAttributes;
use GlContext; use GlContext;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use libc; use libc;
use api::osmesa::{self, OsMesaContext}; use api::osmesa::{self, OsMesaContext};
@ -25,8 +26,12 @@ pub type MonitorID = (); // TODO: hack to make things work
pub struct HeadlessContext(OsMesaContext); pub struct HeadlessContext(OsMesaContext);
impl HeadlessContext { impl HeadlessContext {
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
match OsMesaContext::new(builder) { opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError>
{
let opengl = opengl.clone().map_sharing(|c| &c.0);
match OsMesaContext::new(dimensions, pf_reqs, &opengl) {
Ok(c) => return Ok(HeadlessContext(c)), Ok(c) => return Ok(HeadlessContext(c)),
Err(osmesa::OsMesaCreationError::NotSupported) => (), Err(osmesa::OsMesaCreationError::NotSupported) => (),
Err(osmesa::OsMesaCreationError::CreationError(e)) => return Err(e), Err(osmesa::OsMesaCreationError::CreationError(e)) => return Err(e),

View file

@ -7,11 +7,13 @@ pub use api::win32::{WindowProxy, PollEventsIterator, WaitEventsIterator};
use libc; use libc;
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use GlAttributes;
use GlContext; use GlContext;
use WindowAttributes;
use api::egl::ffi::egl::Egl; use api::egl::ffi::egl::Egl;
use api::egl; use api::egl;
@ -57,8 +59,11 @@ pub struct Window(win32::Window);
impl Window { impl Window {
/// See the docs in the crate root file. /// See the docs in the crate root file.
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
win32::Window::new(builder, EGL.as_ref().map(|w| &w.0)).map(|w| Window(w)) opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
win32::Window::new(window, pf_reqs, &opengl.clone().map_sharing(|w| &w.0),
EGL.as_ref().map(|w| &w.0)).map(|w| Window(w))
} }
} }
@ -85,14 +90,15 @@ pub enum HeadlessContext {
} }
impl HeadlessContext { impl HeadlessContext {
pub fn new(mut builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
builder.visible = false; opengl: &GlAttributes<&HeadlessContext>) -> Result<HeadlessContext, CreationError>
{
// if EGL is available, we try using EGL first // if EGL is available, we try using EGL first
// if EGL returns an error, we try the hidden window method // if EGL returns an error, we try the hidden window method
if let &Some(ref egl) = &*EGL { if let &Some(ref egl) = &*EGL {
let context = EglContext::new(egl.0.clone(), &builder, egl::NativeDisplay::Other(None)) let context = EglContext::new(egl.0.clone(), pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()), // TODO:
.and_then(|prototype| prototype.finish_pbuffer()) egl::NativeDisplay::Other(None))
.and_then(|prototype| prototype.finish_pbuffer(dimensions))
.map(|ctxt| HeadlessContext::EglPbuffer(ctxt)); .map(|ctxt| HeadlessContext::EglPbuffer(ctxt));
if let Ok(context) = context { if let Ok(context) = context {
@ -100,7 +106,9 @@ impl HeadlessContext {
} }
} }
let window = try!(win32::Window::new(builder, EGL.as_ref().map(|w| &w.0))); let window = try!(win32::Window::new(&WindowAttributes { visible: false, .. Default::default() },
pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()), //TODO:
EGL.as_ref().map(|w| &w.0)));
Ok(HeadlessContext::HiddenWindow(window)) Ok(HeadlessContext::HiddenWindow(window))
} }
} }

View file

@ -2,17 +2,19 @@ use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default; use std::default::Default;
use Api; use Api;
use BuilderAttribs;
use ContextError; use ContextError;
use CreationError; use CreationError;
use CursorState; use CursorState;
use Event; use Event;
use GlAttributes;
use GlContext; use GlContext;
use GlProfile; use GlProfile;
use GlRequest; use GlRequest;
use MouseCursor; use MouseCursor;
use PixelFormat; use PixelFormat;
use PixelFormatRequirements;
use Robustness; use Robustness;
use WindowAttributes;
use native_monitor::NativeMonitorId; use native_monitor::NativeMonitorId;
use gl_common; use gl_common;
@ -22,14 +24,18 @@ use platform;
/// Object that allows you to build windows. /// Object that allows you to build windows.
pub struct WindowBuilder<'a> { pub struct WindowBuilder<'a> {
attribs: BuilderAttribs<'a> pf_reqs: PixelFormatRequirements,
window: WindowAttributes,
opengl: GlAttributes<&'a platform::Window>,
} }
impl<'a> WindowBuilder<'a> { impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values. /// Initializes a new `WindowBuilder` with default values.
pub fn new() -> WindowBuilder<'a> { pub fn new() -> WindowBuilder<'a> {
WindowBuilder { WindowBuilder {
attribs: BuilderAttribs::new(), pf_reqs: Default::default(),
window: Default::default(),
opengl: Default::default(),
} }
} }
@ -37,13 +43,13 @@ impl<'a> WindowBuilder<'a> {
/// ///
/// Width and height are in pixels. /// Width and height are in pixels.
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> { pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.attribs.dimensions = Some((width, height)); self.window.dimensions = Some((width, height));
self self
} }
/// Requests a specific title for the window. /// Requests a specific title for the window.
pub fn with_title(mut self, title: String) -> WindowBuilder<'a> { pub fn with_title(mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title; self.window.title = title;
self self
} }
@ -52,7 +58,7 @@ impl<'a> WindowBuilder<'a> {
/// If you don't specify dimensions for the window, it will match the monitor's. /// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> { pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
let MonitorID(monitor) = monitor; let MonitorID(monitor) = monitor;
self.attribs.monitor = Some(monitor); self.window.monitor = Some(monitor);
self self
} }
@ -60,19 +66,19 @@ impl<'a> WindowBuilder<'a> {
/// ///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation. /// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> { pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.attribs.sharing = Some(&other.window); self.opengl.sharing = Some(&other.window);
self self
} }
/// Sets how the backend should choose the OpenGL API and version. /// Sets how the backend should choose the OpenGL API and version.
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> { pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.attribs.gl_version = request; self.opengl.version = request;
self self
} }
/// Sets the desired OpenGL context profile. /// Sets the desired OpenGL context profile.
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> { pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.attribs.gl_profile = Some(profile); self.opengl.profile = Some(profile);
self self
} }
@ -81,25 +87,25 @@ impl<'a> WindowBuilder<'a> {
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled /// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`. /// when you run `cargo build` and disabled when you run `cargo build --release`.
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> { pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.attribs.gl_debug = flag; self.opengl.debug = flag;
self self
} }
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`. /// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> { pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.attribs.gl_robustness = robustness; self.opengl.robustness = robustness;
self self
} }
/// Requests that the window has vsync enabled. /// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> { pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true; self.opengl.vsync = true;
self self
} }
/// Sets whether the window will be initially hidden or visible. /// Sets whether the window will be initially hidden or visible.
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> { pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.attribs.visible = visible; self.window.visible = visible;
self self
} }
@ -110,56 +116,56 @@ impl<'a> WindowBuilder<'a> {
/// Will panic if `samples` is not a power of two. /// Will panic if `samples` is not a power of two.
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> { pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two()); assert!(samples.is_power_of_two());
self.attribs.multisampling = Some(samples); self.pf_reqs.multisampling = Some(samples);
self self
} }
/// Sets the number of bits in the depth buffer. /// Sets the number of bits in the depth buffer.
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> { pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.depth_bits = Some(bits); self.pf_reqs.depth_bits = Some(bits);
self self
} }
/// Sets the number of bits in the stencil buffer. /// Sets the number of bits in the stencil buffer.
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> { pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.attribs.stencil_bits = Some(bits); self.pf_reqs.stencil_bits = Some(bits);
self self
} }
/// Sets the number of bits in the color buffer. /// Sets the number of bits in the color buffer.
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> { pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.attribs.color_bits = Some(color_bits); self.pf_reqs.color_bits = Some(color_bits);
self.attribs.alpha_bits = Some(alpha_bits); self.pf_reqs.alpha_bits = Some(alpha_bits);
self self
} }
/// Request the backend to be stereoscopic. /// Request the backend to be stereoscopic.
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> { pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.attribs.stereoscopy = true; self.pf_reqs.stereoscopy = true;
self self
} }
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care". /// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> { pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.attribs.srgb = srgb_enabled; self.pf_reqs.srgb = srgb_enabled;
self self
} }
/// Sets whether the background of the window should be transparent. /// Sets whether the background of the window should be transparent.
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> { pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.attribs.transparent = transparent; self.window.transparent = transparent;
self self
} }
/// Sets whether the window should have a border, a title bar, etc. /// Sets whether the window should have a border, a title bar, etc.
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> { pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.attribs.decorations = decorations; self.window.decorations = decorations;
self self
} }
/// Enables multitouch /// Enables multitouch
pub fn with_multitouch(mut self) -> WindowBuilder<'a> { pub fn with_multitouch(mut self) -> WindowBuilder<'a> {
self.attribs.multitouch = true; self.window.multitouch = true;
self self
} }
@ -169,25 +175,25 @@ impl<'a> WindowBuilder<'a> {
/// out of memory, etc. /// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> { pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen // resizing the window to the dimensions of the monitor when fullscreen
if self.attribs.dimensions.is_none() && self.attribs.monitor.is_some() { if self.window.dimensions.is_none() && self.window.monitor.is_some() {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions()) self.window.dimensions = Some(self.window.monitor.as_ref().unwrap().get_dimensions())
} }
// default dimensions // default dimensions
if self.attribs.dimensions.is_none() { if self.window.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768)); self.window.dimensions = Some((1024, 768));
} }
// building // building
platform::Window::new(self.attribs).map(|w| Window { window: w }) platform::Window::new(&self.window, &self.pf_reqs, &self.opengl)
.map(|w| Window { window: w })
} }
/// Builds the window. /// Builds the window.
/// ///
/// The context is build in a *strict* way. That means that if the backend couldn't give /// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned. /// you what you requested, an `Err` will be returned.
pub fn build_strict(mut self) -> Result<Window, CreationError> { pub fn build_strict(self) -> Result<Window, CreationError> {
self.attribs.strict = true;
self.build() self.build()
} }
} }