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_usingnoaccel = false;
64 static float mouse_x, mouse_y;
66 static qboolean vid_isfullscreen = false;
67 static qboolean vid_usingvsync = false;
69 static qboolean sound_active = true;
71 static int scr_width, scr_height;
73 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)"};
74 static cvar_t apple_mouse_noaccel = {CVAR_SAVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
76 static AGLContext context;
77 static WindowRef window;
79 static double originalMouseSpeed = -1.0;
81 io_connect_t IN_GetIOHandle()
83 io_connect_t iohandle = MACH_PORT_NULL;
85 io_service_t iohidsystem = MACH_PORT_NULL;
86 mach_port_t masterport;
88 status = IOMasterPort(MACH_PORT_NULL, &masterport);
89 if(status != KERN_SUCCESS)
92 iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
96 status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
97 IOObjectRelease(iohidsystem);
102 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
106 *height = scr_height;
109 static void IN_Activate( qboolean grab )
113 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
114 IN_Activate(false); // ungrab first!
115 if (!vid_usingmouse && mouse_avail && window)
120 SelectWindow(window);
121 CGDisplayHideCursor(CGMainDisplayID());
123 // Put the mouse cursor at the center of the window
124 GetWindowBounds (window, kWindowContentRgn, &winBounds);
125 winCenter.x = (winBounds.left + winBounds.right) / 2;
126 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
127 CGWarpMouseCursorPosition(winCenter);
129 // Lock the mouse pointer at its current position
130 CGAssociateMouseAndMouseCursorPosition(false);
132 // Save the status of mouse acceleration
133 originalMouseSpeed = -1.0; // in case of error
134 if(apple_mouse_noaccel.integer)
136 io_connect_t mouseDev = IN_GetIOHandle();
139 if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
141 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
142 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
144 Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
145 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
150 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
151 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
153 IOServiceClose(mouseDev);
157 Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
158 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
162 mouse_x = mouse_y = 0;
163 vid_usingmouse = true;
164 vid_usingnoaccel = !!apple_mouse_noaccel.integer;
171 if(originalMouseSpeed != -1.0)
173 io_connect_t mouseDev = IN_GetIOHandle();
176 Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
177 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
178 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
179 IOServiceClose(mouseDev);
182 Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
185 CGAssociateMouseAndMouseCursorPosition(true);
186 CGDisplayShowCursor(CGMainDisplayID());
188 vid_usingmouse = false;
193 #define GAMMA_TABLE_SIZE 256
194 void VID_Finish (qboolean allowmousegrab)
196 qboolean vid_usemouse;
197 qboolean vid_usevsync;
199 // handle the mouse state when windowed if that's changed
200 vid_usemouse = false;
201 if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
203 if (!vid_activewindow)
204 vid_usemouse = false;
205 if (vid_isfullscreen)
207 IN_Activate(vid_usemouse);
209 // handle changes of the vsync option
210 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
211 if (vid_usingvsync != vid_usevsync)
213 GLint sync = (vid_usevsync ? 1 : 0);
215 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
217 vid_usingvsync = vid_usevsync;
218 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
221 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
224 if (r_render.integer)
227 if (r_speeds.integer || gl_finish.integer)
229 qglFinish();CHECKGLERROR
231 qaglSwapBuffers(context);
233 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
235 if (apple_multithreadedgl.integer)
237 if (!multithreadedgl)
239 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
241 CGLContextObj ctx = qCGLGetCurrentContext();
242 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
244 multithreadedgl = true;
247 Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
248 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
253 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
254 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
262 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
264 CGLContextObj ctx = qCGLGetCurrentContext();
265 qCGLDisable(ctx, kCGLCEMPEngine);
266 multithreadedgl = false;
272 int VID_SetGamma(unsigned short *ramps, int rampsize)
274 CGGammaValue table_red [GAMMA_TABLE_SIZE];
275 CGGammaValue table_green [GAMMA_TABLE_SIZE];
276 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
279 // Convert the unsigned short table into 3 float tables
280 for (i = 0; i < rampsize; i++)
281 table_red[i] = (float)ramps[i] / 65535.0f;
282 for (i = 0; i < rampsize; i++)
283 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
284 for (i = 0; i < rampsize; i++)
285 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
287 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
289 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
296 int VID_GetGamma(unsigned short *ramps, int rampsize)
298 CGGammaValue table_red [GAMMA_TABLE_SIZE];
299 CGGammaValue table_green [GAMMA_TABLE_SIZE];
300 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
301 CGTableCount actualsize = 0;
304 // Get the gamma ramps from the system
305 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
307 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
310 if (actualsize != (unsigned int)rampsize)
312 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
316 // Convert the 3 float tables into 1 unsigned short table
317 for (i = 0; i < rampsize; i++)
318 ramps[i] = table_red[i] * 65535.0f;
319 for (i = 0; i < rampsize; i++)
320 ramps[i + rampsize] = table_green[i] * 65535.0f;
321 for (i = 0; i < rampsize; i++)
322 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
327 void signal_handler(int sig)
329 printf("Received signal %d, exiting...\n", sig);
330 VID_RestoreSystemGamma();
336 signal(SIGHUP, signal_handler);
337 signal(SIGINT, signal_handler);
338 signal(SIGQUIT, signal_handler);
339 signal(SIGILL, signal_handler);
340 signal(SIGTRAP, signal_handler);
341 signal(SIGIOT, signal_handler);
342 signal(SIGBUS, signal_handler);
343 signal(SIGFPE, signal_handler);
344 signal(SIGSEGV, signal_handler);
345 signal(SIGTERM, signal_handler);
350 InitSig(); // trap evil signals
351 Cvar_RegisterVariable(&apple_multithreadedgl);
352 Cvar_RegisterVariable(&apple_mouse_noaccel);
353 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
354 if (COM_CheckParm ("-nomouse"))
358 static void *prjobj = NULL;
359 static void *cglobj = NULL;
361 static void GL_CloseLibrary(void)
372 gl_platformextensions = "";
375 static int GL_OpenLibrary(void)
377 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
378 const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
380 Con_Printf("Loading OpenGL driver %s\n", name);
382 if (!(prjobj = dlopen(name, RTLD_LAZY)))
384 Con_Printf("Unable to open symbol list for %s\n", name);
387 strlcpy(gl_driver, name, sizeof(gl_driver));
389 Con_Printf("Loading OpenGL driver %s\n", name2);
390 if (!(cglobj = dlopen(name2, RTLD_LAZY)))
391 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
396 void *GL_GetProcAddress(const char *name)
398 return dlsym(prjobj, name);
401 static void *CGL_GetProcAddress(const char *name)
405 return dlsym(cglobj, name);
408 void VID_Shutdown(void)
410 if (context == NULL && window == NULL)
414 VID_RestoreSystemGamma();
418 qaglDestroyContext(context);
422 if (vid_isfullscreen)
423 CGReleaseAllDisplays();
427 DisposeWindow(window);
432 vid_isfullscreen = false;
438 // Since the event handler can be called at any time, we store the events for later processing
439 static qboolean AsyncEvent_Quitting = false;
440 static qboolean AsyncEvent_Collapsed = false;
441 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
443 OSStatus err = noErr;
445 switch (GetEventKind (event))
447 case kEventWindowClosed:
448 AsyncEvent_Quitting = true;
452 case kEventWindowCollapsing:
453 AsyncEvent_Collapsed = true;
456 // Undocked / restored (end)
457 case kEventWindowExpanded:
458 AsyncEvent_Collapsed = false;
462 err = eventNotHandledErr;
469 static void VID_AppFocusChanged(qboolean windowIsActive)
471 if (vid_activewindow != windowIsActive)
473 vid_activewindow = windowIsActive;
474 if (!vid_activewindow)
475 VID_RestoreSystemGamma();
478 if (sound_active != windowIsActive)
480 sound_active = windowIsActive;
488 static void VID_ProcessPendingAsyncEvents (void)
490 // Collapsed / expanded
491 if (AsyncEvent_Collapsed != vid_hidden)
493 vid_hidden = !vid_hidden;
494 VID_AppFocusChanged(!vid_hidden);
498 if (AsyncEvent_Quitting)
502 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer)
504 *attrib++ = AGL_RGBA;
505 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
506 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
507 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
508 *attrib++ = AGL_DOUBLEBUFFER;
509 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
511 // if stencil is enabled, ask for alpha too
514 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
515 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
518 *attrib++ = AGL_FULLSCREEN;
520 *attrib++ = AGL_STEREO;
521 *attrib++ = AGL_NONE;
524 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
526 const EventTypeSpec winEvents[] =
528 { kEventClassWindow, kEventWindowClosed },
529 { kEventClassWindow, kEventWindowCollapsing },
530 { kEventClassWindow, kEventWindowExpanded },
532 OSStatus carbonError;
534 CFStringRef windowTitle;
535 AGLPixelFormat pixelFormat;
536 GLint attributes [32];
539 if (!GL_OpenLibrary())
541 Con_Printf("Unable to load GL driver\n");
545 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
546 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
547 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
548 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
549 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
550 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
551 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
552 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
553 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
554 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
555 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
558 Con_Printf("AGL functions not found\n");
559 ReleaseWindow(window);
563 qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
564 qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
565 qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
566 if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
567 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
569 // Ignore the events from the previous window
570 AsyncEvent_Quitting = false;
571 AsyncEvent_Collapsed = false;
573 // Create the window, a bit towards the center of the screen
574 windowBounds.left = 100;
575 windowBounds.top = 100;
576 windowBounds.right = width + 100;
577 windowBounds.bottom = height + 100;
578 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
579 if (carbonError != noErr || window == NULL)
581 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
585 // Set the window title
586 windowTitle = CFSTR("DarkPlaces AGL");
587 SetWindowTitleWithCFString(window, windowTitle);
589 // Install the callback function for the window events we can't get
590 // through ReceiveNextEvent (i.e. close, collapse, and expand)
591 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
592 GetEventTypeCount(winEvents), winEvents, window, NULL);
594 // Create the desired attribute list
595 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer);
600 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
601 error = qaglGetError();
602 if (error != AGL_NO_ERROR)
604 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
605 (char *)qaglErrorString(error));
606 ReleaseWindow(window);
610 else // Output is fullScreen
612 CGDirectDisplayID mainDisplay;
613 CFDictionaryRef refDisplayMode;
616 // Get the mainDisplay and set resolution to current
617 mainDisplay = CGMainDisplayID();
618 CGDisplayCapture(mainDisplay);
620 // TOCHECK: not sure whether or not it's necessary to change the resolution
621 // "by hand", or if aglSetFullscreen does the job anyway
622 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
623 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
624 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
626 // Set pixel format with built attribs
627 // Note: specifying a device is *required* for AGL_FullScreen
628 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
629 error = qaglGetError();
630 if (error != AGL_NO_ERROR)
632 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
633 (char *)qaglErrorString(error));
634 ReleaseWindow(window);
639 // Create a context using the pform
640 context = qaglCreateContext(pixelFormat, NULL);
641 error = qaglGetError();
642 if (error != AGL_NO_ERROR)
644 Con_Printf("qaglCreateContext FAILED: %s\n",
645 (char *)qaglErrorString(error));
648 // Make the context the current one ('enable' it)
649 qaglSetCurrentContext(context);
650 error = qaglGetError();
651 if (error != AGL_NO_ERROR)
653 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
654 (char *)qaglErrorString(error));
655 ReleaseWindow(window);
660 qaglDestroyPixelFormat(pixelFormat);
662 // Attempt fullscreen if requested
665 qaglSetFullScreen (context, width, height, refreshrate, 0);
666 error = qaglGetError();
667 if (error != AGL_NO_ERROR)
669 Con_Printf("qaglSetFullScreen FAILED: %s\n",
670 (char *)qaglErrorString(error));
676 // Set Window as Drawable
677 qaglSetDrawable(context, GetWindowPort(window));
678 error = qaglGetError();
679 if (error != AGL_NO_ERROR)
681 Con_Printf("qaglSetDrawable FAILED: %s\n",
682 (char *)qaglErrorString(error));
683 ReleaseWindow(window);
691 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
692 Sys_Error("glGetString not found in %s", gl_driver);
694 gl_renderer = (const char *)qglGetString(GL_RENDERER);
695 gl_vendor = (const char *)qglGetString(GL_VENDOR);
696 gl_version = (const char *)qglGetString(GL_VERSION);
697 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
699 gl_videosyncavailable = true;
701 Con_DPrintf("GL_VENDOR: %s\n", gl_vendor);
702 Con_DPrintf("GL_RENDERER: %s\n", gl_renderer);
703 Con_DPrintf("GL_VERSION: %s\n", gl_version);
704 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
705 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
707 multithreadedgl = false;
708 vid_isfullscreen = fullscreen;
709 vid_usingmouse = false;
711 vid_activewindow = true;
715 SelectWindow(window);
721 static void Handle_KeyMod(UInt32 keymod)
723 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
726 { shiftKey, K_SHIFT },
727 { alphaLock, K_CAPSLOCK },
728 { optionKey, K_ALT },
729 { controlKey, K_CTRL },
730 { kEventKeyModifierNumLockMask, K_NUMLOCK },
731 { kEventKeyModifierFnMask, K_AUX2 }
733 static UInt32 prev_keymod = 0;
737 modChanges = prev_keymod ^ keymod;
741 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
743 UInt32 keybit = keymod_events[i].keybit;
745 if ((modChanges & keybit) != 0)
746 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
749 prev_keymod = keymod;
752 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
754 unsigned int keycode = 0;
799 keycode = K_SCROLLOCK;
805 keycode = K_BACKSPACE;
820 keycode = K_KP_EQUALS;
823 keycode = K_KP_DIVIDE;
826 keycode = K_KP_MULTIPLY;
850 keycode = K_KP_MINUS;
853 keycode = K_CAPSLOCK;
881 keycode = K_KP_ENTER;
887 keycode = K_KP_PERIOD;
892 case kUpArrowCharCode:
895 case kLeftArrowCharCode:
896 keycode = K_LEFTARROW;
898 case kDownArrowCharCode:
899 keycode = K_DOWNARROW;
901 case kRightArrowCharCode:
902 keycode = K_RIGHTARROW;
906 // characters 0 and 191 are sent by the mouse buttons (?!)
909 if ('A' <= charcode && charcode <= 'Z')
911 keycode = charcode + ('a' - 'A'); // lowercase it
914 else if (charcode >= 32)
920 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
925 Key_Event(keycode, ascii, keypressed);
928 void Sys_SendKeyEvents(void)
931 EventTargetRef theTarget;
933 // Start by processing the asynchronous events we received since the previous frame
934 VID_ProcessPendingAsyncEvents();
936 theTarget = GetEventDispatcherTarget();
937 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
939 UInt32 eventClass = GetEventClass(theEvent);
940 UInt32 eventKind = GetEventKind(theEvent);
944 case kEventClassMouse:
946 EventMouseButton theButton;
951 case kEventMouseDown:
953 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
957 case kEventMouseButtonPrimary:
960 case kEventMouseButtonSecondary:
963 case kEventMouseButtonTertiary:
967 Key_Event(key, '\0', eventKind == kEventMouseDown);
970 // Note: These two events are mutual exclusives
971 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
972 case kEventMouseMoved:
973 case kEventMouseDragged:
977 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
979 mouse_x += deltaPos.x;
980 mouse_y += deltaPos.y;
984 case kEventMouseWheelMoved:
987 unsigned int wheelEvent;
989 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
991 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
992 Key_Event(wheelEvent, 0, true);
993 Key_Event(wheelEvent, 0, false);
998 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1003 case kEventClassKeyboard:
1010 case kEventRawKeyDown:
1011 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1012 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1013 Handle_Key(charcode, keycode, true);
1016 case kEventRawKeyRepeat:
1019 case kEventRawKeyUp:
1020 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1021 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1022 Handle_Key(charcode, keycode, false);
1025 case kEventRawKeyModifiersChanged:
1028 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
1029 Handle_KeyMod(keymod);
1033 case kEventHotKeyPressed:
1036 case kEventHotKeyReleased:
1039 case kEventMouseWheelMoved:
1043 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1049 case kEventClassTextInput:
1050 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
1053 case kEventClassApplication:
1056 case kEventAppActivated :
1057 VID_AppFocusChanged(true);
1059 case kEventAppDeactivated:
1060 VID_AppFocusChanged(false);
1065 case kEventAppActiveWindowChanged:
1068 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1073 case kEventClassAppleEvent:
1076 case kEventAppleEvent :
1079 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1084 case kEventClassWindow:
1087 case kEventWindowUpdate :
1090 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1095 case kEventClassControl:
1099 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1100 eventClass >> 24, (eventClass >> 16) & 0xFF,
1101 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1106 SendEventToEventTarget (theEvent, theTarget);
1107 ReleaseEvent(theEvent);
1115 in_mouse_x = mouse_x;
1116 in_mouse_y = mouse_y;