aboutsummaryrefslogtreecommitdiffstats
path: root/src/cocoa
diff options
context:
space:
mode:
authorBrendan Zabarauskas <bjzaba@yahoo.com.au>2015-01-26 14:28:12 +1100
committerBrendan Zabarauskas <bjzaba@yahoo.com.au>2015-01-26 14:28:12 +1100
commit73078e0569a9cadc51d64e98f4653e66e2985b8d (patch)
tree6a5cfb09807594b51b9a84b87d65d0cd02b7e40a /src/cocoa
parent44c21c4bbb890400bf12cfb9e0d199e598eec0d1 (diff)
downloadglutin-73078e0569a9cadc51d64e98f4653e66e2985b8d.tar.gz
glutin-73078e0569a9cadc51d64e98f4653e66e2985b8d.zip
Rename osx->cocoa
Diffstat (limited to 'src/cocoa')
-rw-r--r--src/cocoa/event.rs136
-rw-r--r--src/cocoa/headless.rs110
-rw-r--r--src/cocoa/mod.rs574
-rw-r--r--src/cocoa/monitor.rs47
4 files changed, 867 insertions, 0 deletions
diff --git a/src/cocoa/event.rs b/src/cocoa/event.rs
new file mode 100644
index 0000000..31bed10
--- /dev/null
+++ b/src/cocoa/event.rs
@@ -0,0 +1,136 @@
+use events;
+
+pub fn vkeycode_to_element(code: u16) -> Option<events::VirtualKeyCode> {
+ Some(match code {
+ 0x00 => events::VirtualKeyCode::A,
+ 0x01 => events::VirtualKeyCode::S,
+ 0x02 => events::VirtualKeyCode::D,
+ 0x03 => events::VirtualKeyCode::F,
+ 0x04 => events::VirtualKeyCode::H,
+ 0x05 => events::VirtualKeyCode::G,
+ 0x06 => events::VirtualKeyCode::Z,
+ 0x07 => events::VirtualKeyCode::X,
+ 0x08 => events::VirtualKeyCode::C,
+ 0x09 => events::VirtualKeyCode::V,
+ //0x0a => World 1,
+ 0x0b => events::VirtualKeyCode::B,
+ 0x0c => events::VirtualKeyCode::Q,
+ 0x0d => events::VirtualKeyCode::W,
+ 0x0e => events::VirtualKeyCode::E,
+ 0x0f => events::VirtualKeyCode::R,
+ 0x10 => events::VirtualKeyCode::Y,
+ 0x11 => events::VirtualKeyCode::T,
+ 0x12 => events::VirtualKeyCode::Key1,
+ 0x13 => events::VirtualKeyCode::Key2,
+ 0x14 => events::VirtualKeyCode::Key3,
+ 0x15 => events::VirtualKeyCode::Key4,
+ 0x16 => events::VirtualKeyCode::Key6,
+ 0x17 => events::VirtualKeyCode::Key5,
+ 0x18 => events::VirtualKeyCode::Equals,
+ 0x19 => events::VirtualKeyCode::Key9,
+ 0x1a => events::VirtualKeyCode::Key7,
+ 0x1b => events::VirtualKeyCode::Minus,
+ 0x1c => events::VirtualKeyCode::Key8,
+ 0x1d => events::VirtualKeyCode::Key0,
+ 0x1e => events::VirtualKeyCode::RBracket,
+ 0x1f => events::VirtualKeyCode::O,
+ 0x20 => events::VirtualKeyCode::U,
+ 0x21 => events::VirtualKeyCode::LBracket,
+ 0x22 => events::VirtualKeyCode::I,
+ 0x23 => events::VirtualKeyCode::P,
+ 0x24 => events::VirtualKeyCode::Return,
+ 0x25 => events::VirtualKeyCode::L,
+ 0x26 => events::VirtualKeyCode::J,
+ 0x27 => events::VirtualKeyCode::Apostrophe,
+ 0x28 => events::VirtualKeyCode::K,
+ 0x29 => events::VirtualKeyCode::Semicolon,
+ 0x2a => events::VirtualKeyCode::Backslash,
+ 0x2b => events::VirtualKeyCode::Comma,
+ 0x2c => events::VirtualKeyCode::Slash,
+ 0x2d => events::VirtualKeyCode::N,
+ 0x2e => events::VirtualKeyCode::M,
+ 0x2f => events::VirtualKeyCode::Period,
+ 0x30 => events::VirtualKeyCode::Tab,
+ 0x31 => events::VirtualKeyCode::Space,
+ 0x32 => events::VirtualKeyCode::Grave,
+ 0x33 => events::VirtualKeyCode::Back,
+ //0x34 => unkown,
+ 0x35 => events::VirtualKeyCode::Escape,
+ 0x36 => events::VirtualKeyCode::RWin,
+ 0x37 => events::VirtualKeyCode::LWin,
+ 0x38 => events::VirtualKeyCode::LShift,
+ //0x39 => Caps lock,
+ //0x3a => Left alt,
+ 0x3b => events::VirtualKeyCode::LControl,
+ 0x3c => events::VirtualKeyCode::RShift,
+ //0x3d => Right alt,
+ 0x3e => events::VirtualKeyCode::RControl,
+ //0x3f => Fn key,
+ //0x40 => F17 Key,
+ 0x41 => events::VirtualKeyCode::Decimal,
+ //0x42 -> unkown,
+ 0x43 => events::VirtualKeyCode::Multiply,
+ //0x44 => unkown,
+ 0x45 => events::VirtualKeyCode::Add,
+ //0x46 => unkown,
+ 0x47 => events::VirtualKeyCode::Numlock,
+ //0x48 => KeypadClear,
+ 0x49 => events::VirtualKeyCode::VolumeUp,
+ 0x4a => events::VirtualKeyCode::VolumeDown,
+ 0x4b => events::VirtualKeyCode::Divide,
+ 0x4c => events::VirtualKeyCode::NumpadEnter,
+ //0x4d => unkown,
+ 0x4e => events::VirtualKeyCode::Subtract,
+ //0x4f => F18 key,
+ //0x50 => F19 Key,
+ 0x51 => events::VirtualKeyCode::NumpadEquals,
+ 0x52 => events::VirtualKeyCode::Numpad0,
+ 0x53 => events::VirtualKeyCode::Numpad1,
+ 0x54 => events::VirtualKeyCode::Numpad2,
+ 0x55 => events::VirtualKeyCode::Numpad3,
+ 0x56 => events::VirtualKeyCode::Numpad4,
+ 0x57 => events::VirtualKeyCode::Numpad5,
+ 0x58 => events::VirtualKeyCode::Numpad6,
+ 0x59 => events::VirtualKeyCode::Numpad7,
+ //0x5a => F20 Key,
+ 0x5b => events::VirtualKeyCode::Numpad8,
+ 0x5c => events::VirtualKeyCode::Numpad9,
+ //0x5d => unkown,
+ //0x5e => unkown,
+ //0x5f => unkown,
+ 0x60 => events::VirtualKeyCode::F5,
+ 0x61 => events::VirtualKeyCode::F6,
+ 0x62 => events::VirtualKeyCode::F7,
+ 0x63 => events::VirtualKeyCode::F3,
+ 0x64 => events::VirtualKeyCode::F8,
+ 0x65 => events::VirtualKeyCode::F9,
+ //0x66 => unkown,
+ 0x67 => events::VirtualKeyCode::F11,
+ //0x68 => unkown,
+ 0x69 => events::VirtualKeyCode::F13,
+ //0x6a => F16 Key,
+ 0x6b => events::VirtualKeyCode::F14,
+ //0x6c => unkown,
+ 0x6d => events::VirtualKeyCode::F10,
+ //0x6e => unkown,
+ 0x6f => events::VirtualKeyCode::F12,
+ //0x70 => unkown,
+ 0x71 => events::VirtualKeyCode::F15,
+ 0x72 => events::VirtualKeyCode::Insert,
+ 0x73 => events::VirtualKeyCode::Home,
+ 0x74 => events::VirtualKeyCode::PageUp,
+ 0x75 => events::VirtualKeyCode::Delete,
+ 0x76 => events::VirtualKeyCode::F4,
+ 0x77 => events::VirtualKeyCode::End,
+ 0x78 => events::VirtualKeyCode::F2,
+ 0x79 => events::VirtualKeyCode::PageDown,
+ 0x7a => events::VirtualKeyCode::F1,
+ 0x7b => events::VirtualKeyCode::Left,
+ 0x7c => events::VirtualKeyCode::Right,
+ 0x7d => events::VirtualKeyCode::Down,
+ 0x7e => events::VirtualKeyCode::Up,
+ //0x7f => unkown,
+
+ _ => return None,
+ })
+}
diff --git a/src/cocoa/headless.rs b/src/cocoa/headless.rs
new file mode 100644
index 0000000..cc19457
--- /dev/null
+++ b/src/cocoa/headless.rs
@@ -0,0 +1,110 @@
+use CreationError;
+use CreationError::OsError;
+use BuilderAttribs;
+use libc;
+use std::ptr;
+
+use core_foundation::base::TCFType;
+use core_foundation::string::CFString;
+use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFunctionPointerForName};
+use cocoa::base::{id, nil};
+use cocoa::appkit::*;
+
+mod gl {
+ include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs"));
+}
+
+static mut framebuffer: u32 = 0;
+static mut texture: u32 = 0;
+
+pub struct HeadlessContext {
+ width: u32,
+ height: u32,
+ context: id,
+}
+
+impl HeadlessContext {
+ pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
+ let (width, height) = builder.dimensions.unwrap_or((1024, 768));
+ let context = unsafe {
+ let attributes = [
+ NSOpenGLPFADoubleBuffer as u32,
+ NSOpenGLPFAClosestPolicy as u32,
+ NSOpenGLPFAColorSize as u32, 24,
+ NSOpenGLPFAAlphaSize as u32, 8,
+ NSOpenGLPFADepthSize as u32, 24,
+ NSOpenGLPFAStencilSize as u32, 8,
+ NSOpenGLPFAOffScreen as u32,
+ 0
+ ];
+
+ let pixelformat = NSOpenGLPixelFormat::alloc(nil).initWithAttributes_(&attributes);
+ if pixelformat == nil {
+ return Err(OsError(format!("Could not create the pixel format")));
+ }
+ let context = NSOpenGLContext::alloc(nil).initWithFormat_shareContext_(pixelformat, nil);
+ if context == nil {
+ return Err(OsError(format!("Could not create the rendering context")));
+ }
+ context
+ };
+
+ let headless = HeadlessContext {
+ width: width,
+ height: height,
+ context: context,
+ };
+
+ // Load the function pointers as we need them to create the FBO
+ gl::load_with(|s| headless.get_proc_address(s) as *const libc::c_void);
+
+ Ok(headless)
+ }
+
+ pub unsafe fn make_current(&self) {
+ self.context.makeCurrentContext();
+
+ gl::GenFramebuffersEXT(1, &mut framebuffer);
+ gl::BindFramebufferEXT(gl::FRAMEBUFFER_EXT, framebuffer);
+ gl::GenTextures(1, &mut texture);
+ gl::BindTexture(gl::TEXTURE_2D, texture);
+ gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
+ gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
+ gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA8 as i32, self.width as i32, self.height as i32,
+ 0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
+ gl::FramebufferTexture2DEXT(gl::FRAMEBUFFER_EXT, gl::COLOR_ATTACHMENT0_EXT,
+ gl::TEXTURE_2D, texture, 0);
+ let status = gl::CheckFramebufferStatusEXT(gl::FRAMEBUFFER_EXT);
+ if status != gl::FRAMEBUFFER_COMPLETE_EXT {
+ panic!("Error while creating the framebuffer");
+ }
+ }
+
+ pub fn get_proc_address(&self, _addr: &str) -> *const () {
+ let symbol_name: CFString = _addr.parse().unwrap();
+ let framework_name: CFString = "com.apple.opengl".parse().unwrap();
+ let framework = unsafe {
+ CFBundleGetBundleWithIdentifier(framework_name.as_concrete_TypeRef())
+ };
+ let symbol = unsafe {
+ CFBundleGetFunctionPointerForName(framework, symbol_name.as_concrete_TypeRef())
+ };
+ symbol as *const ()
+ }
+
+ pub fn get_api(&self) -> ::Api {
+ ::Api::OpenGl
+ }
+}
+
+unsafe impl Send for HeadlessContext {}
+unsafe impl Sync for HeadlessContext {}
+
+impl Drop for HeadlessContext {
+ fn drop(&mut self) {
+ unsafe {
+ gl::DeleteTextures(1, &texture);
+ gl::DeleteFramebuffersEXT(1, &framebuffer);
+ }
+ }
+}
diff --git a/src/cocoa/mod.rs b/src/cocoa/mod.rs
new file mode 100644
index 0000000..94ac5b3
--- /dev/null
+++ b/src/cocoa/mod.rs
@@ -0,0 +1,574 @@
+#[cfg(feature = "headless")]
+pub use self::headless::HeadlessContext;
+
+use {CreationError, Event, MouseCursor};
+use CreationError::OsError;
+use libc;
+
+use BuilderAttribs;
+
+use cocoa::base::{Class, id, YES, NO, NSUInteger, nil, objc_allocateClassPair, class, objc_registerClassPair};
+use cocoa::base::{selector, msg_send, msg_send_stret, class_addMethod, class_addIvar};
+use cocoa::base::{object_setInstanceVariable, object_getInstanceVariable};
+use cocoa::appkit;
+use cocoa::appkit::*;
+
+use core_foundation::base::TCFType;
+use core_foundation::string::CFString;
+use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFunctionPointerForName};
+
+use std::cell::Cell;
+use std::ffi::{CString, c_str_to_bytes};
+use std::mem;
+use std::ptr;
+use std::collections::RingBuf;
+use std::str::FromStr;
+use std::str::from_utf8;
+use std::ascii::AsciiExt;
+
+use events::Event::{MouseInput, MouseMoved, ReceivedCharacter, KeyboardInput, MouseWheel};
+use events::ElementState::{Pressed, Released};
+use events::MouseButton::{LeftMouseButton, RightMouseButton};
+use events;
+
+pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor};
+
+mod monitor;
+mod event;
+
+#[cfg(feature = "headless")]
+mod headless;
+
+static mut shift_pressed: bool = false;
+static mut ctrl_pressed: bool = false;
+static mut win_pressed: bool = false;
+static mut alt_pressed: bool = false;
+
+struct DelegateState<'a> {
+ is_closed: bool,
+ context: id,
+ view: id,
+ window: id,
+ handler: Option<fn(u32, u32)>,
+}
+
+struct WindowDelegate {
+ this: id,
+}
+
+impl WindowDelegate {
+ fn class_name() -> &'static [u8] {
+ b"GlutinWindowDelegate\0"
+ }
+
+ fn state_ivar_name() -> &'static [u8] {
+ b"glutinState"
+ }
+
+ /// Get the delegate class, initiailizing it neccessary
+ fn class() -> Class {
+ use std::sync::{Once, ONCE_INIT};
+ use std::rt;
+
+ extern fn window_should_close(this: id, _: id) -> id {
+ unsafe {
+ let delegate = WindowDelegate { this: this };
+ (*delegate.get_state()).is_closed = true;
+ mem::forget(delegate);
+ }
+ 0
+ }
+
+ extern fn window_did_resize(this: id, _: id) -> id {
+ unsafe {
+ let delegate = WindowDelegate { this: this };
+ let state = &mut *delegate.get_state();
+ mem::forget(delegate);
+
+ let _: id = msg_send()(state.context, selector("update"));
+
+ if let Some(handler) = state.handler {
+ let rect = NSView::frame(state.view);
+ let scale_factor = state.window.backingScaleFactor() as f32;
+ (handler)((scale_factor * rect.size.width as f32) as u32,
+ (scale_factor * rect.size.height as f32) as u32);
+ }
+ }
+ 0
+ }
+
+ static mut delegate_class: Class = nil;
+ static mut init: Once = ONCE_INIT;
+
+ unsafe {
+ init.call_once(|| {
+ let ptr_size = mem::size_of::<libc::intptr_t>();
+ // Create new NSWindowDelegate
+ delegate_class = objc_allocateClassPair(
+ class("NSObject"),
+ WindowDelegate::class_name().as_ptr() as *const i8, 0);
+ // Add callback methods
+ class_addMethod(delegate_class,
+ selector("windowShouldClose:"),
+ window_should_close,
+ CString::from_slice("B@:@".as_bytes()).as_ptr());
+ class_addMethod(delegate_class,
+ selector("windowDidResize:"),
+ window_did_resize,
+ CString::from_slice("V@:@".as_bytes()).as_ptr());
+ // Store internal state as user data
+ class_addIvar(delegate_class, WindowDelegate::state_ivar_name().as_ptr() as *const i8,
+ ptr_size as u64, 3,
+ CString::from_slice("?".as_bytes()).as_ptr());
+ objc_registerClassPair(delegate_class);
+ // Free class at exit
+ rt::at_exit(|| {
+ // objc_disposeClassPair(delegate_class);
+ });
+ });
+ delegate_class
+ }
+ }
+
+ fn new(window: id) -> WindowDelegate {
+ unsafe {
+ let delegate: id = msg_send()(WindowDelegate::class(), selector("new"));
+ let _: id = msg_send()(window, selector("setDelegate:"), delegate);
+ WindowDelegate { this: delegate }
+ }
+ }
+
+ unsafe fn set_state(&self, state: *mut DelegateState) {
+ object_setInstanceVariable(self.this,
+ WindowDelegate::state_ivar_name().as_ptr() as *const i8,
+ state as *mut libc::c_void);
+ }
+
+ fn get_state(&self) -> *mut DelegateState {
+ unsafe {
+ let mut state = ptr::null_mut();
+ object_getInstanceVariable(self.this,
+ WindowDelegate::state_ivar_name().as_ptr() as *const i8,
+ &mut state);
+ state as *mut DelegateState
+ }
+ }
+}
+
+pub struct Window {
+ view: id,
+ window: id,
+ context: id,
+ delegate: WindowDelegate,
+ resize: Option<fn(u32, u32)>,
+
+ is_closed: Cell<bool>,
+}
+
+#[cfg(feature = "window")]
+unsafe impl Send for Window {}
+#[cfg(feature = "window")]
+unsafe impl Sync for Window {}
+
+#[cfg(feature = "window")]
+#[derive(Clone)]
+pub struct WindowProxy;
+
+impl WindowProxy {
+ pub fn wakeup_event_loop(&self) {
+ unsafe {
+ let pool = NSAutoreleasePool::new(nil);
+ let event =
+ NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
+ nil, NSApplicationDefined, NSPoint::new(0.0, 0.0), 0, 0.0, 0, ptr::null_mut(), 0, 0, 0);
+ NSApp().postEvent_atStart_(event, YES);
+ pool.drain();
+ }
+ }
+}
+
+impl Window {
+ #[cfg(feature = "window")]
+ pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
+ if builder.sharing.is_some() {
+ unimplemented!()
+ }
+
+ let app = match Window::create_app() {
+ Some(app) => app,
+ None => { return Err(OsError(format!("Couldn't create NSApplication"))); },
+ };
+ let window = match Window::create_window(builder.dimensions.unwrap_or((800, 600)),
+ &*builder.title,
+ builder.monitor)
+ {
+ Some(window) => window,
+ None => { return Err(OsError(format!("Couldn't create NSWindow"))); },
+ };
+ let view = match Window::create_view(window) {
+ Some(view) => view,
+ None => { return Err(OsError(format!("Couldn't create NSView"))); },
+ };
+
+ let context = match Window::create_context(view, builder.vsync, builder.gl_version) {
+ Some(context) => context,
+ None => { return Err(OsError(format!("Couldn't create OpenGL context"))); },
+ };
+
+ unsafe {
+ app.activateIgnoringOtherApps_(YES);
+ if builder.visible {
+ window.makeKeyAndOrderFront_(nil);
+ } else {
+ window.makeKeyWindow();
+ }
+ }
+
+ let window = Window {
+ view: view,
+ window: window,
+ context: context,
+ delegate: WindowDelegate::new(window),
+ resize: None,
+
+ is_closed: Cell::new(false),
+ };
+
+ Ok(window)
+ }
+
+ fn create_app() -> Option<id> {
+ unsafe {
+ let app = NSApp();
+ if app == nil {
+ None
+ } else {
+ app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
+ app.finishLaunching();
+ Some(app)
+ }
+ }
+ }
+
+ fn create_window(dimensions: (u32, u32), title: &str, monitor: Option<MonitorID>) -> Option<id> {
+ unsafe {
+ let frame = if monitor.is_some() {
+ let screen = NSScreen::mainScreen(nil);
+ NSScreen::frame(screen)
+ } else {
+ let (width, height) = dimensions;
+ NSRect::new(NSPoint::new(0., 0.), NSSize::new(width as f64, height as f64))
+ };
+
+ let masks = if monitor.is_some() {
+ NSBorderlessWindowMask as NSUInteger
+ } else {
+ NSTitledWindowMask as NSUInteger |
+ NSClosableWindowMask as NSUInteger |
+ NSMiniaturizableWindowMask as NSUInteger |
+ NSResizableWindowMask as NSUInteger
+ };
+
+ let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_(
+ frame,
+ masks,
+ NSBackingStoreBuffered,
+ NO,
+ );
+
+ if window == nil {
+ None
+ } else {
+ let title = NSString::alloc(nil).init_str(title);
+ window.setTitle_(title);
+ window.setAcceptsMouseMovedEvents_(YES);
+ if monitor.is_some() {
+ window.setLevel_(NSMainMenuWindowLevel as i64 + 1);
+ }
+ else {
+ window.center();
+ }
+ Some(window)
+ }
+ }
+ }
+
+ fn create_view(window: id) -> Option<id> {
+ unsafe {
+ let view = NSView::alloc(nil).init();
+ if view == nil {
+ None
+ } else {
+ view.setWantsBestResolutionOpenGLSurface_(YES);
+ window.setContentView_(view);
+ Some(view)
+ }
+ }
+ }
+
+ fn create_context(view: id, vsync: bool, gl_version: Option<(u32, u32)>) -> Option<id> {
+ let profile = match gl_version {
+ None | Some((0...2, _)) | Some((3, 0)) => NSOpenGLProfileVersionLegacy as u32,
+ Some((3, 1...2)) => NSOpenGLProfileVersion3_2Core as u32,
+ Some((_, _)) => NSOpenGLProfileVersion4_1Core as u32,
+ };
+ unsafe {
+ let attributes = [
+ NSOpenGLPFADoubleBuffer as u32,
+ NSOpenGLPFAClosestPolicy as u32,
+ NSOpenGLPFAColorSize as u32, 24,
+ NSOpenGLPFAAlphaSize as u32, 8,
+ NSOpenGLPFADepthSize as u32, 24,
+ NSOpenGLPFAStencilSize as u32, 8,
+ NSOpenGLPFAOpenGLProfile as u32, profile,
+ 0
+ ];
+
+ let pixelformat = NSOpenGLPixelFormat::alloc(nil).initWithAttributes_(&attributes);
+ if pixelformat == nil {
+ return None;
+ }
+
+ let context = NSOpenGLContext::alloc(nil).initWithFormat_shareContext_(pixelformat, nil);
+ if context == nil {
+ None
+ } else {
+ context.setView_(view);
+ if vsync {
+ let value = 1;
+ context.setValues_forParameter_(&value, NSOpenGLContextParameter::NSOpenGLCPSwapInterval);
+ }
+ Some(context)
+ }
+ }
+ }
+
+ pub fn is_closed(&self) -> bool {
+ self.is_closed.get()
+ }
+
+ pub fn set_title(&self, title: &str) {
+ unsafe {
+ let title = NSString::alloc(nil).init_str(title);
+ self.window.setTitle_(title);
+ }
+ }
+
+ pub fn show(&self) {
+ unsafe { NSWindow::makeKeyAndOrderFront_(self.window, nil); }
+ }
+
+ pub fn hide(&self) {
+ unsafe { NSWindow::orderOut_(self.window, nil); }
+ }
+
+ pub fn get_position(&self) -> Option<(i32, i32)> {
+ unsafe {
+ // let content_rect = NSWindow::contentRectForFrameRect_(self.window, NSWindow::frame(self.window));
+ let content_rect: NSRect = msg_send_stret()(self.window,
+ selector("contentRectForFrameRect:"),
+ NSWindow::frame(self.window));
+ // NOTE: coordinate system might be inconsistent with other backends
+ Some((content_rect.origin.x as i32, content_rect.origin.y as i32))
+ }
+ }
+
+ pub fn set_position(&self, x: i32, y: i32) {
+ unsafe {
+ // NOTE: coordinate system might be inconsistent with other backends
+ NSWindow::setFrameOrigin_(self.window, NSPoint::new(x as f64, y as f64));
+ }
+ }
+
+ pub fn get_inner_size(&self) -> Option<(u32, u32)> {
+ unsafe {
+ let view_frame = NSView::frame(self.view);
+ Some((view_frame.size.width as u32, view_frame.size.height as u32))
+ }
+ }
+
+ pub fn get_outer_size(&self) -> Option<(u32, u32)> {
+ unsafe {
+ let window_frame = NSWindow::frame(self.window);
+ Some((window_frame.size.width as u32, window_frame.size.height as u32))
+ }
+ }
+
+ pub fn set_inner_size(&self, width: u32, height: u32) {
+ unsafe {
+ NSWindow::setContentSize_(self.window, NSSize::new(width as f64, height as f64));
+ }
+ }
+
+ pub fn create_window_proxy(&self) -> WindowProxy {
+ WindowProxy
+ }
+
+ pub fn poll_events(&self) -> RingBuf<Event> {
+ let mut events = RingBuf::new();
+
+ loop {
+ unsafe {
+ let event = NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_(
+ NSAnyEventMask as u64,
+ NSDate::distantPast(nil),
+ NSDefaultRunLoopMode,
+ YES);
+ if event == nil { break; }
+ {
+ // Create a temporary structure with state that delegates called internally
+ // by sendEvent can read and modify. When that returns, update window state.
+ // This allows the synchronous resize loop to continue issuing callbacks
+ // to the user application, by passing handler through to the delegate state.
+ let mut ds = DelegateState {
+ is_closed: self.is_closed.get(),
+ context: self.context,
+ window: self.window,
+ view: self.view,
+ handler: self.resize,
+ };
+ self.delegate.set_state(&mut ds);
+ NSApp().sendEvent_(event);
+ self.delegate.set_state(ptr::null_mut());
+ self.is_closed.set(ds.is_closed);
+ }
+
+ match event.get_type() {
+ NSLeftMouseDown => { events.push_back(MouseInput(Pressed, LeftMouseButton)); },
+ NSLeftMouseUp => { events.push_back(MouseInput(Released, LeftMouseButton)); },
+ NSRightMouseDown => { events.push_back(MouseInput(Pressed, RightMouseButton)); },
+ NSRightMouseUp => { events.push_back(MouseInput(Released, RightMouseButton)); },
+ NSMouseMoved => {
+ let window_point = event.locationInWindow();
+ let window: id = msg_send()(event, selector("window"));
+ let view_point = if window == 0 {
+ let window_rect = self.window.convertRectFromScreen_(NSRect::new(window_point, NSSize::new(0.0, 0.0)));
+ self.view.convertPoint_fromView_(window_rect.origin, nil)
+ } else {
+ self.view.convertPoint_fromView_(window_point, nil)
+ };
+ let view_rect = NSView::frame(self.view);
+ let scale_factor = self.hidpi_factor();
+ events.push_back(MouseMoved(((scale_factor * view_point.x as f32) as i32,
+ (scale_factor * (view_rect.size.height - view_point.y) as f32) as i32)));
+ },
+ NSKeyDown => {
+ let received_c_str = event.characters().UTF8String();
+ let received_str = CString::from_slice(c_str_to_bytes(&received_c_str));
+ for received_char in from_utf8(received_str.as_bytes()).unwrap().chars() {
+ if received_char.is_ascii() {
+ events.push_back(ReceivedCharacter(received_char));
+ }
+ }
+
+ let vkey = event::vkeycode_to_element(event.keycode());
+ events.push_back(KeyboardInput(Pressed, event.keycode() as u8, vkey));
+ },
+ NSKeyUp => {
+ let vkey = event::vkeycode_to_element(event.keycode());
+ events.push_back(KeyboardInput(Released, event.keycode() as u8, vkey));
+ },
+ NSFlagsChanged => {
+ let shift_modifier = Window::modifier_event(event, appkit::NSShiftKeyMask as u64, events::VirtualKeyCode::LShift, shift_pressed);
+ if shift_modifier.is_some() {
+ shift_pressed = !shift_pressed;
+ events.push_back(shift_modifier.unwrap());
+ }
+ let ctrl_modifier = Window::modifier_event(event, appkit::NSControlKeyMask as u64, events::VirtualKeyCode::LControl, ctrl_pressed);
+ if ctrl_modifier.is_some() {
+ ctrl_pressed = !ctrl_pressed;
+ events.push_back(ctrl_modifier.unwrap());
+ }
+ let win_modifier = Window::modifier_event(event, appkit::NSCommandKeyMask as u64, events::VirtualKeyCode::LWin, win_pressed);
+ if win_modifier.is_some() {
+ win_pressed = !win_pressed;
+ events.push_back(win_modifier.unwrap());
+ }
+ let alt_modifier = Window::modifier_event(event, appkit::NSAlternateKeyMask as u64, events::VirtualKeyCode::LAlt, alt_pressed);
+ if alt_modifier.is_some() {
+ alt_pressed = !alt_pressed;
+ events.push_back(alt_modifier.unwrap());
+ }
+ },
+ NSScrollWheel => { events.push_back(MouseWheel(-event.scrollingDeltaY() as i32)); },
+ NSOtherMouseDown => { },
+ NSOtherMouseUp => { },
+ NSOtherMouseDragged => { },
+ _ => { },
+ }
+ }
+ }
+ events
+ }
+
+ unsafe fn modifier_event(event: id, keymask: u64, key: events::VirtualKeyCode, key_pressed: bool) -> Option<Event> {
+ if !key_pressed && Window::modifier_key_pressed(event, keymask) {
+ return Some(KeyboardInput(Pressed, event.keycode() as u8, Some(key)));
+ }
+ else if key_pressed && !Window::modifier_key_pressed(event, keymask) {
+ return Some(KeyboardInput(Released, event.keycode() as u8, Some(key)));
+ }
+
+ return None;
+ }
+
+ unsafe fn modifier_key_pressed(event: id, modifier: u64) -> bool {
+ event.modifierFlags() & modifier != 0
+ }
+
+ pub fn wait_events(&self) -> RingBuf<Event> {
+ unsafe {
+ let event = NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_(
+ NSAnyEventMask as u64,
+ NSDate::distantFuture(nil),
+ NSDefaultRunLoopMode,
+ NO);
+ NSApp().sendEvent_(event);
+
+ self.poll_events()
+ }
+ }
+
+ pub unsafe fn make_current(&self) {
+ let _: id = msg_send()(self.context, selector("update"));
+ self.context.makeCurrentContext();
+ }
+
+ pub fn get_proc_address(&self, _addr: &str) -> *const () {
+ let symbol_name: CFString = FromStr::from_str(_addr).unwrap();
+ let framework_name: CFString = FromStr::from_str("com.apple.opengl").unwrap();
+ let framework = unsafe {
+ CFBundleGetBundleWithIdentifier(framework_name.as_concrete_TypeRef())
+ };
+ let symbol = unsafe {
+ CFBundleGetFunctionPointerForName(framework, symbol_name.as_concrete_TypeRef())
+ };
+ symbol as *const ()
+ }
+
+ pub fn swap_buffers(&self) {
+ unsafe { self.context.flushBuffer(); }
+ }
+
+ pub fn platform_display(&self) -> *mut libc::c_void {
+ unimplemented!()
+ }
+
+ pub fn get_api(&self) -> ::Api {
+ ::Api::OpenGl
+ }
+
+ pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
+ self.resize = callback;
+ }
+
+ pub fn set_cursor(&self, cursor: MouseCursor) {
+ unimplemented!()
+ }
+
+ pub fn hidpi_factor(&self) -> f32 {
+ unsafe {
+ self.window.backingScaleFactor() as f32
+ }
+ }
+}
diff --git a/src/cocoa/monitor.rs b/src/cocoa/monitor.rs
new file mode 100644
index 0000000..912c02d
--- /dev/null
+++ b/src/cocoa/monitor.rs
@@ -0,0 +1,47 @@
+use core_graphics::display;
+use std::collections::RingBuf;
+
+pub struct MonitorID(u32);
+
+pub fn get_available_monitors() -> RingBuf<MonitorID> {
+ let mut monitors = RingBuf::new();
+ unsafe {
+ let max_displays = 10u32;
+ let mut active_displays = [0u32; 10];
+ let mut display_count = 0;
+ display::CGGetActiveDisplayList(max_displays,
+ &mut active_displays[0],
+ &mut display_count);
+ for i in range(0us, display_count as usize) {
+ monitors.push_back(MonitorID(active_displays[i]));
+ }
+ }
+ monitors
+}
+
+pub fn get_primary_monitor() -> MonitorID {
+ let id = unsafe {
+ MonitorID(display::CGMainDisplayID())
+ };
+ id
+}
+
+impl MonitorID {
+ pub fn get_name(&self) -> Option<String> {
+ let MonitorID(display_id) = *self;
+ let screen_num = unsafe {
+ display::CGDisplayModelNumber(display_id)
+ };
+ Some(format!("Monitor #{}", screen_num))
+ }
+
+ pub fn get_dimensions(&self) -> (u32, u32) {
+ let MonitorID(display_id) = *self;
+ let dimension = unsafe {
+ let height = display::CGDisplayPixelsHigh(display_id);
+ let width = display::CGDisplayPixelsWide(display_id);
+ (width as u32, height as u32)
+ };
+ dimension
+ }
+}