4 Mac OS X OpenGL and input module, using Carbon and AGL
6 Copyright (C) 2005-2006 Mathieu Olivier
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 #include <OpenGL/OpenGL.h>
28 #include <Carbon/Carbon.h>
29 #include <IOKit/hidsystem/IOHIDLib.h>
30 #include <IOKit/hidsystem/IOHIDParameter.h>
31 #include <IOKit/hidsystem/event_status_driver.h>
33 #include "vid_agl_mackeys.h" // this is SDL/src/video/maccommon/SDL_mackeys.h
35 #ifndef kCGLCEMPEngine
36 #define kCGLCEMPEngine 313
39 // Tell startup code that we have a client
40 int cl_available = true;
42 qboolean vid_supportrefreshrate = true;
45 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
46 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
47 GLboolean (*qaglDestroyContext) (AGLContext ctx);
48 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
49 const GLubyte* (*qaglErrorString) (GLenum code);
50 GLenum (*qaglGetError) (void);
51 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
52 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
53 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
54 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
55 void (*qaglSwapBuffers) (AGLContext ctx);
56 CGLError (*qCGLEnable) (CGLContextObj ctx, CGLContextEnable pname);
57 CGLError (*qCGLDisable) (CGLContextObj ctx, CGLContextEnable pname);
58 CGLContextObj (*qCGLGetCurrentContext) (void);
60 static qboolean multithreadedgl;
61 static qboolean mouse_avail = true;
62 static qboolean vid_usingmouse = false;
63 static qboolean vid_usinghidecursor = false;
64 static qboolean vid_usingnoaccel = false;
66 static qboolean vid_isfullscreen = false;
67 static qboolean vid_usingvsync = false;
69 static qboolean sound_active = true;
71 static cvar_t apple_multithreadedgl = {CVAR_SAVE, "apple_multithreadedgl", "1", "makes use of a second thread for the OpenGL driver (if possible) rather than using the engine thread (note: this is done automatically on most other operating systems)"};
72 static cvar_t apple_mouse_noaccel = {CVAR_SAVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
74 static AGLContext context;
75 static WindowRef window;
77 static double originalMouseSpeed = -1.0;
79 io_connect_t IN_GetIOHandle(void)
81 io_connect_t iohandle = MACH_PORT_NULL;
83 io_service_t iohidsystem = MACH_PORT_NULL;
84 mach_port_t masterport;
86 status = IOMasterPort(MACH_PORT_NULL, &masterport);
87 if(status != KERN_SUCCESS)
90 iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
94 status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
95 IOObjectRelease(iohidsystem);
100 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
102 if (!mouse_avail || !window)
103 relative = hidecursor = false;
107 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
108 VID_SetMouse(false, false, false); // ungrab first!
114 SelectWindow(window);
116 // Put the mouse cursor at the center of the window
117 GetWindowBounds (window, kWindowContentRgn, &winBounds);
118 winCenter.x = (winBounds.left + winBounds.right) / 2;
119 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
120 CGWarpMouseCursorPosition(winCenter);
122 // Lock the mouse pointer at its current position
123 CGAssociateMouseAndMouseCursorPosition(false);
125 // Save the status of mouse acceleration
126 originalMouseSpeed = -1.0; // in case of error
127 if(apple_mouse_noaccel.integer)
129 io_connect_t mouseDev = IN_GetIOHandle();
132 if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
134 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
135 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
137 Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
138 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
143 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
144 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
146 IOServiceClose(mouseDev);
150 Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
151 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
155 vid_usingmouse = true;
156 vid_usingnoaccel = !!apple_mouse_noaccel.integer;
163 if(originalMouseSpeed != -1.0)
165 io_connect_t mouseDev = IN_GetIOHandle();
168 Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
169 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
170 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
171 IOServiceClose(mouseDev);
174 Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
177 CGAssociateMouseAndMouseCursorPosition(true);
179 vid_usingmouse = false;
183 if (vid_usinghidecursor != hidecursor)
185 vid_usinghidecursor = hidecursor;
187 CGDisplayHideCursor(CGMainDisplayID());
189 CGDisplayShowCursor(CGMainDisplayID());
193 #define GAMMA_TABLE_SIZE 256
194 void VID_Finish (void)
196 qboolean vid_usevsync;
198 // handle changes of the vsync option
199 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
200 if (vid_usingvsync != vid_usevsync)
202 GLint sync = (vid_usevsync ? 1 : 0);
204 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
206 vid_usingvsync = vid_usevsync;
207 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
210 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
215 if (r_speeds.integer == 2 || gl_finish.integer)
217 qaglSwapBuffers(context);
219 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
221 if (apple_multithreadedgl.integer)
223 if (!multithreadedgl)
225 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
227 CGLContextObj ctx = qCGLGetCurrentContext();
228 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
230 multithreadedgl = true;
233 Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
234 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
239 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
240 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
248 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
250 CGLContextObj ctx = qCGLGetCurrentContext();
251 qCGLDisable(ctx, kCGLCEMPEngine);
252 multithreadedgl = false;
258 int VID_SetGamma(unsigned short *ramps, int rampsize)
260 CGGammaValue table_red [GAMMA_TABLE_SIZE];
261 CGGammaValue table_green [GAMMA_TABLE_SIZE];
262 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
265 // Convert the unsigned short table into 3 float tables
266 for (i = 0; i < rampsize; i++)
267 table_red[i] = (float)ramps[i] / 65535.0f;
268 for (i = 0; i < rampsize; i++)
269 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
270 for (i = 0; i < rampsize; i++)
271 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
273 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
275 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
282 int VID_GetGamma(unsigned short *ramps, int rampsize)
284 CGGammaValue table_red [GAMMA_TABLE_SIZE];
285 CGGammaValue table_green [GAMMA_TABLE_SIZE];
286 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
287 CGTableCount actualsize = 0;
290 // Get the gamma ramps from the system
291 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
293 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
296 if (actualsize != (unsigned int)rampsize)
298 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
302 // Convert the 3 float tables into 1 unsigned short table
303 for (i = 0; i < rampsize; i++)
304 ramps[i] = table_red[i] * 65535.0f;
305 for (i = 0; i < rampsize; i++)
306 ramps[i + rampsize] = table_green[i] * 65535.0f;
307 for (i = 0; i < rampsize; i++)
308 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
313 void signal_handler(int sig)
315 printf("Received signal %d, exiting...\n", sig);
316 VID_RestoreSystemGamma();
322 signal(SIGHUP, signal_handler);
323 signal(SIGINT, signal_handler);
324 signal(SIGQUIT, signal_handler);
325 signal(SIGILL, signal_handler);
326 signal(SIGTRAP, signal_handler);
327 signal(SIGIOT, signal_handler);
328 signal(SIGBUS, signal_handler);
329 signal(SIGFPE, signal_handler);
330 signal(SIGSEGV, signal_handler);
331 signal(SIGTERM, signal_handler);
336 InitSig(); // trap evil signals
337 Cvar_RegisterVariable(&apple_multithreadedgl);
338 Cvar_RegisterVariable(&apple_mouse_noaccel);
339 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
340 if (COM_CheckParm ("-nomouse"))
344 static void *prjobj = NULL;
345 static void *cglobj = NULL;
347 static void GL_CloseLibrary(void)
358 gl_platformextensions = "";
361 static int GL_OpenLibrary(void)
363 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
364 const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
366 Con_Printf("Loading OpenGL driver %s\n", name);
368 if (!(prjobj = dlopen(name, RTLD_LAZY)))
370 Con_Printf("Unable to open symbol list for %s\n", name);
373 strlcpy(gl_driver, name, sizeof(gl_driver));
375 Con_Printf("Loading OpenGL driver %s\n", name2);
376 if (!(cglobj = dlopen(name2, RTLD_LAZY)))
377 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
382 void *GL_GetProcAddress(const char *name)
384 return dlsym(prjobj, name);
387 static void *CGL_GetProcAddress(const char *name)
391 return dlsym(cglobj, name);
394 void VID_Shutdown(void)
396 if (context == NULL && window == NULL)
399 VID_SetMouse(false, false, false);
400 VID_RestoreSystemGamma();
404 qaglDestroyContext(context);
408 if (vid_isfullscreen)
409 CGReleaseAllDisplays();
413 DisposeWindow(window);
418 vid_isfullscreen = false;
424 // Since the event handler can be called at any time, we store the events for later processing
425 static qboolean AsyncEvent_Quitting = false;
426 static qboolean AsyncEvent_Collapsed = false;
427 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
429 OSStatus err = noErr;
431 switch (GetEventKind (event))
433 case kEventWindowClosed:
434 AsyncEvent_Quitting = true;
438 case kEventWindowCollapsing:
439 AsyncEvent_Collapsed = true;
442 // Undocked / restored (end)
443 case kEventWindowExpanded:
444 AsyncEvent_Collapsed = false;
448 err = eventNotHandledErr;
455 static void VID_AppFocusChanged(qboolean windowIsActive)
457 if (vid_activewindow != windowIsActive)
459 vid_activewindow = windowIsActive;
460 if (!vid_activewindow)
461 VID_RestoreSystemGamma();
464 if (windowIsActive || !snd_mutewhenidle.integer)
477 sound_active = false;
482 static void VID_ProcessPendingAsyncEvents (void)
484 // Collapsed / expanded
485 if (AsyncEvent_Collapsed != vid_hidden)
487 vid_hidden = !vid_hidden;
488 VID_AppFocusChanged(!vid_hidden);
492 if (AsyncEvent_Quitting)
496 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer, int samples)
498 *attrib++ = AGL_RGBA;
499 *attrib++ = AGL_RED_SIZE;*attrib++ = stencil ? 8 : 5;
500 *attrib++ = AGL_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
501 *attrib++ = AGL_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
502 *attrib++ = AGL_DOUBLEBUFFER;
503 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
505 // if stencil is enabled, ask for alpha too
508 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
509 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 8;
512 *attrib++ = AGL_FULLSCREEN;
514 *attrib++ = AGL_STEREO;
515 #ifdef AGL_SAMPLE_BUFFERS_ARB
516 #ifdef AGL_SAMPLES_ARB
519 *attrib++ = AGL_SAMPLE_BUFFERS_ARB;
521 *attrib++ = AGL_SAMPLES_ARB;
527 *attrib++ = AGL_NONE;
530 qboolean VID_InitMode(viddef_mode_t *mode)
532 const EventTypeSpec winEvents[] =
534 { kEventClassWindow, kEventWindowClosed },
535 { kEventClassWindow, kEventWindowCollapsing },
536 { kEventClassWindow, kEventWindowExpanded },
538 OSStatus carbonError;
540 CFStringRef windowTitle;
541 AGLPixelFormat pixelFormat;
542 GLint attributes [32];
545 if (!GL_OpenLibrary())
547 Con_Printf("Unable to load GL driver\n");
551 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
552 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
553 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
554 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
555 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
556 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
557 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
558 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
559 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
560 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
561 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
564 Con_Printf("AGL functions not found\n");
565 ReleaseWindow(window);
569 qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
570 qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
571 qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
572 if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
573 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
575 // Ignore the events from the previous window
576 AsyncEvent_Quitting = false;
577 AsyncEvent_Collapsed = false;
579 // Create the window, a bit towards the center of the screen
580 windowBounds.left = 100;
581 windowBounds.top = 100;
582 windowBounds.right = mode->width + 100;
583 windowBounds.bottom = mode->height + 100;
584 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
585 if (carbonError != noErr || window == NULL)
587 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
591 // Set the window title
592 windowTitle = CFSTR("DarkPlaces AGL");
593 SetWindowTitleWithCFString(window, windowTitle);
595 // Install the callback function for the window events we can't get
596 // through ReceiveNextEvent (i.e. close, collapse, and expand)
597 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
598 GetEventTypeCount(winEvents), winEvents, window, NULL);
600 // Create the desired attribute list
601 VID_BuildAGLAttrib(attributes, mode->bitsperpixel == 32, mode->fullscreen, mode->stereobuffer, mode->samples);
603 if (!mode->fullscreen)
606 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
607 error = qaglGetError();
608 if (error != AGL_NO_ERROR)
610 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
611 (char *)qaglErrorString(error));
612 ReleaseWindow(window);
616 else // Output is fullScreen
618 CGDirectDisplayID mainDisplay;
619 CFDictionaryRef refDisplayMode;
622 // Get the mainDisplay and set resolution to current
623 mainDisplay = CGMainDisplayID();
624 CGDisplayCapture(mainDisplay);
626 // TOCHECK: not sure whether or not it's necessary to change the resolution
627 // "by hand", or if aglSetFullscreen does the job anyway
628 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty(mainDisplay, mode->bitsperpixel, mode->width, mode->height, mode->refreshrate, kCGDisplayModeIsSafeForHardware, NULL);
629 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
630 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
632 // Set pixel format with built attribs
633 // Note: specifying a device is *required* for AGL_FullScreen
634 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
635 error = qaglGetError();
636 if (error != AGL_NO_ERROR)
638 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
639 (char *)qaglErrorString(error));
640 ReleaseWindow(window);
645 // Create a context using the pform
646 context = qaglCreateContext(pixelFormat, NULL);
647 error = qaglGetError();
648 if (error != AGL_NO_ERROR)
650 Con_Printf("qaglCreateContext FAILED: %s\n",
651 (char *)qaglErrorString(error));
654 // Make the context the current one ('enable' it)
655 qaglSetCurrentContext(context);
656 error = qaglGetError();
657 if (error != AGL_NO_ERROR)
659 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
660 (char *)qaglErrorString(error));
661 ReleaseWindow(window);
666 qaglDestroyPixelFormat(pixelFormat);
668 // Attempt fullscreen if requested
669 if (mode->fullscreen)
671 qaglSetFullScreen (context, mode->width, mode->height, mode->refreshrate, 0);
672 error = qaglGetError();
673 if (error != AGL_NO_ERROR)
675 Con_Printf("qaglSetFullScreen FAILED: %s\n",
676 (char *)qaglErrorString(error));
682 // Set Window as Drawable
683 qaglSetDrawable(context, GetWindowPort(window));
684 error = qaglGetError();
685 if (error != AGL_NO_ERROR)
687 Con_Printf("qaglSetDrawable FAILED: %s\n",
688 (char *)qaglErrorString(error));
689 ReleaseWindow(window);
694 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
695 Sys_Error("glGetString not found in %s", gl_driver);
697 gl_platformextensions = "";
700 multithreadedgl = false;
701 vid_isfullscreen = mode->fullscreen;
702 vid_usingmouse = false;
703 vid_usinghidecursor = false;
705 vid_activewindow = true;
709 SelectWindow(window);
715 static void Handle_KeyMod(UInt32 keymod)
717 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
720 { shiftKey, K_SHIFT },
721 { alphaLock, K_CAPSLOCK },
722 { optionKey, K_ALT },
723 { controlKey, K_CTRL },
724 { kEventKeyModifierNumLockMask, K_NUMLOCK },
725 { kEventKeyModifierFnMask, K_AUX2 }
727 static UInt32 prev_keymod = 0;
731 modChanges = prev_keymod ^ keymod;
735 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
737 UInt32 keybit = keymod_events[i].keybit;
739 if ((modChanges & keybit) != 0)
740 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
743 prev_keymod = keymod;
746 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
748 unsigned int keycode = 0;
793 keycode = K_SCROLLOCK;
799 keycode = K_BACKSPACE;
814 keycode = K_KP_EQUALS;
817 keycode = K_KP_DIVIDE;
820 keycode = K_KP_MULTIPLY;
844 keycode = K_KP_MINUS;
847 keycode = K_CAPSLOCK;
875 keycode = K_KP_ENTER;
881 keycode = K_KP_PERIOD;
886 case kUpArrowCharCode:
889 case kLeftArrowCharCode:
890 keycode = K_LEFTARROW;
892 case kDownArrowCharCode:
893 keycode = K_DOWNARROW;
895 case kRightArrowCharCode:
896 keycode = K_RIGHTARROW;
900 // characters 0 and 191 are sent by the mouse buttons (?!)
903 if ('A' <= charcode && charcode <= 'Z')
905 keycode = charcode + ('a' - 'A'); // lowercase it
908 else if (charcode >= 32)
914 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
919 Key_Event(keycode, ascii, keypressed);
922 void Sys_SendKeyEvents(void)
925 EventTargetRef theTarget;
927 // Start by processing the asynchronous events we received since the previous frame
928 VID_ProcessPendingAsyncEvents();
930 theTarget = GetEventDispatcherTarget();
931 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
933 UInt32 eventClass = GetEventClass(theEvent);
934 UInt32 eventKind = GetEventKind(theEvent);
938 case kEventClassMouse:
940 EventMouseButton theButton;
945 case kEventMouseDown:
947 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
951 case kEventMouseButtonPrimary:
954 case kEventMouseButtonSecondary:
957 case kEventMouseButtonTertiary:
961 Key_Event(key, '\0', eventKind == kEventMouseDown);
964 // Note: These two events are mutual exclusives
965 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
966 case kEventMouseMoved:
967 case kEventMouseDragged:
972 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
973 GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);
977 in_mouse_x += deltaPos.x;
978 in_mouse_y += deltaPos.y;
981 in_windowmouse_x = windowPos.x;
982 in_windowmouse_y = windowPos.y;
986 case kEventMouseWheelMoved:
989 unsigned int wheelEvent;
991 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
993 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
994 Key_Event(wheelEvent, 0, true);
995 Key_Event(wheelEvent, 0, false);
1000 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1005 case kEventClassKeyboard:
1012 case kEventRawKeyDown:
1013 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1014 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1015 Handle_Key(charcode, keycode, true);
1018 case kEventRawKeyRepeat:
1021 case kEventRawKeyUp:
1022 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1023 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1024 Handle_Key(charcode, keycode, false);
1027 case kEventRawKeyModifiersChanged:
1030 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
1031 Handle_KeyMod(keymod);
1035 case kEventHotKeyPressed:
1038 case kEventHotKeyReleased:
1041 case kEventMouseWheelMoved:
1045 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1051 case kEventClassTextInput:
1052 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
1055 case kEventClassApplication:
1058 case kEventAppActivated :
1059 VID_AppFocusChanged(true);
1061 case kEventAppDeactivated:
1062 VID_AppFocusChanged(false);
1067 case kEventAppActiveWindowChanged:
1070 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1075 case kEventClassAppleEvent:
1078 case kEventAppleEvent :
1081 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1086 case kEventClassWindow:
1089 case kEventWindowUpdate :
1092 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1097 case kEventClassControl:
1101 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1102 eventClass >> 24, (eventClass >> 16) & 0xFF,
1103 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1108 SendEventToEventTarget (theEvent, theTarget);
1109 ReleaseEvent(theEvent);
1117 static bool GetDictionaryBoolean(CFDictionaryRef d, const void *key)
1119 CFBooleanRef ref = (CFBooleanRef) CFDictionaryGetValue(d, key);
1121 return CFBooleanGetValue(ref);
1125 long GetDictionaryLong(CFDictionaryRef d, const void *key)
1128 CFNumberRef ref = (CFNumberRef) CFDictionaryGetValue(d, key);
1130 CFNumberGetValue(ref, kCFNumberLongType, &value);
1134 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1136 CGDirectDisplayID mainDisplay = CGMainDisplayID();
1137 CFArrayRef vidmodes = CGDisplayAvailableModes(mainDisplay);
1138 CFDictionaryRef thismode;
1139 unsigned int n = CFArrayGetCount(vidmodes);
1144 for(i = 0; i < n; ++i)
1146 thismode = (CFDictionaryRef) CFArrayGetValueAtIndex(vidmodes, i);
1147 if(!GetDictionaryBoolean(thismode, kCGDisplayModeIsSafeForHardware))
1152 modes[k].width = GetDictionaryLong(thismode, kCGDisplayWidth);
1153 modes[k].height = GetDictionaryLong(thismode, kCGDisplayHeight);
1154 modes[k].bpp = GetDictionaryLong(thismode, kCGDisplayBitsPerPixel);
1155 modes[k].refreshrate = GetDictionaryLong(thismode, kCGDisplayRefreshRate);
1156 modes[k].pixelheight_num = 1;
1157 modes[k].pixelheight_denom = 1; // OS X doesn't expose this either