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 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 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
111 if (!mouse_avail || !window)
112 fullscreengrab = relative = hidecursor = false;
116 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
117 VID_SetMouse(false, false, false); // ungrab first!
123 SelectWindow(window);
125 // Put the mouse cursor at the center of the window
126 GetWindowBounds (window, kWindowContentRgn, &winBounds);
127 winCenter.x = (winBounds.left + winBounds.right) / 2;
128 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
129 CGWarpMouseCursorPosition(winCenter);
131 // Lock the mouse pointer at its current position
132 CGAssociateMouseAndMouseCursorPosition(false);
134 // Save the status of mouse acceleration
135 originalMouseSpeed = -1.0; // in case of error
136 if(apple_mouse_noaccel.integer)
138 io_connect_t mouseDev = IN_GetIOHandle();
141 if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
143 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
144 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
146 Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
147 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
152 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
153 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
155 IOServiceClose(mouseDev);
159 Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
160 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
164 vid_usingmouse = true;
165 vid_usingnoaccel = !!apple_mouse_noaccel.integer;
172 if(originalMouseSpeed != -1.0)
174 io_connect_t mouseDev = IN_GetIOHandle();
177 Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
178 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
179 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
180 IOServiceClose(mouseDev);
183 Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
186 CGAssociateMouseAndMouseCursorPosition(true);
188 vid_usingmouse = false;
192 if (vid_usinghidecursor != hidecursor)
194 vid_usinghidecursor = hidecursor;
196 CGDisplayHideCursor(CGMainDisplayID());
198 CGDisplayShowCursor(CGMainDisplayID());
202 #define GAMMA_TABLE_SIZE 256
203 void VID_Finish (void)
205 qboolean vid_usevsync;
207 // handle changes of the vsync option
208 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
209 if (vid_usingvsync != vid_usevsync)
211 GLint sync = (vid_usevsync ? 1 : 0);
213 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
215 vid_usingvsync = vid_usevsync;
216 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
219 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
222 if (r_render.integer)
225 if (r_speeds.integer || gl_finish.integer)
227 qglFinish();CHECKGLERROR
229 qaglSwapBuffers(context);
231 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
233 if (apple_multithreadedgl.integer)
235 if (!multithreadedgl)
237 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
239 CGLContextObj ctx = qCGLGetCurrentContext();
240 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
242 multithreadedgl = true;
245 Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
246 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
251 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
252 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
260 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
262 CGLContextObj ctx = qCGLGetCurrentContext();
263 qCGLDisable(ctx, kCGLCEMPEngine);
264 multithreadedgl = false;
270 int VID_SetGamma(unsigned short *ramps, int rampsize)
272 CGGammaValue table_red [GAMMA_TABLE_SIZE];
273 CGGammaValue table_green [GAMMA_TABLE_SIZE];
274 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
277 // Convert the unsigned short table into 3 float tables
278 for (i = 0; i < rampsize; i++)
279 table_red[i] = (float)ramps[i] / 65535.0f;
280 for (i = 0; i < rampsize; i++)
281 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
282 for (i = 0; i < rampsize; i++)
283 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
285 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
287 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
294 int VID_GetGamma(unsigned short *ramps, int rampsize)
296 CGGammaValue table_red [GAMMA_TABLE_SIZE];
297 CGGammaValue table_green [GAMMA_TABLE_SIZE];
298 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
299 CGTableCount actualsize = 0;
302 // Get the gamma ramps from the system
303 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
305 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
308 if (actualsize != (unsigned int)rampsize)
310 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
314 // Convert the 3 float tables into 1 unsigned short table
315 for (i = 0; i < rampsize; i++)
316 ramps[i] = table_red[i] * 65535.0f;
317 for (i = 0; i < rampsize; i++)
318 ramps[i + rampsize] = table_green[i] * 65535.0f;
319 for (i = 0; i < rampsize; i++)
320 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
325 void signal_handler(int sig)
327 printf("Received signal %d, exiting...\n", sig);
328 VID_RestoreSystemGamma();
334 signal(SIGHUP, signal_handler);
335 signal(SIGINT, signal_handler);
336 signal(SIGQUIT, signal_handler);
337 signal(SIGILL, signal_handler);
338 signal(SIGTRAP, signal_handler);
339 signal(SIGIOT, signal_handler);
340 signal(SIGBUS, signal_handler);
341 signal(SIGFPE, signal_handler);
342 signal(SIGSEGV, signal_handler);
343 signal(SIGTERM, signal_handler);
348 InitSig(); // trap evil signals
349 Cvar_RegisterVariable(&apple_multithreadedgl);
350 Cvar_RegisterVariable(&apple_mouse_noaccel);
351 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
352 if (COM_CheckParm ("-nomouse"))
356 static void *prjobj = NULL;
357 static void *cglobj = NULL;
359 static void GL_CloseLibrary(void)
370 gl_platformextensions = "";
373 static int GL_OpenLibrary(void)
375 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
376 const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
378 Con_Printf("Loading OpenGL driver %s\n", name);
380 if (!(prjobj = dlopen(name, RTLD_LAZY)))
382 Con_Printf("Unable to open symbol list for %s\n", name);
385 strlcpy(gl_driver, name, sizeof(gl_driver));
387 Con_Printf("Loading OpenGL driver %s\n", name2);
388 if (!(cglobj = dlopen(name2, RTLD_LAZY)))
389 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
394 void *GL_GetProcAddress(const char *name)
396 return dlsym(prjobj, name);
399 static void *CGL_GetProcAddress(const char *name)
403 return dlsym(cglobj, name);
406 void VID_Shutdown(void)
408 if (context == NULL && window == NULL)
411 VID_SetMouse(false, false, false);
412 VID_RestoreSystemGamma();
416 qaglDestroyContext(context);
420 if (vid_isfullscreen)
421 CGReleaseAllDisplays();
425 DisposeWindow(window);
430 vid_isfullscreen = false;
436 // Since the event handler can be called at any time, we store the events for later processing
437 static qboolean AsyncEvent_Quitting = false;
438 static qboolean AsyncEvent_Collapsed = false;
439 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
441 OSStatus err = noErr;
443 switch (GetEventKind (event))
445 case kEventWindowClosed:
446 AsyncEvent_Quitting = true;
450 case kEventWindowCollapsing:
451 AsyncEvent_Collapsed = true;
454 // Undocked / restored (end)
455 case kEventWindowExpanded:
456 AsyncEvent_Collapsed = false;
460 err = eventNotHandledErr;
467 static void VID_AppFocusChanged(qboolean windowIsActive)
469 if (vid_activewindow != windowIsActive)
471 vid_activewindow = windowIsActive;
472 if (!vid_activewindow)
473 VID_RestoreSystemGamma();
476 if (sound_active != windowIsActive)
478 sound_active = windowIsActive;
486 static void VID_ProcessPendingAsyncEvents (void)
488 // Collapsed / expanded
489 if (AsyncEvent_Collapsed != vid_hidden)
491 vid_hidden = !vid_hidden;
492 VID_AppFocusChanged(!vid_hidden);
496 if (AsyncEvent_Quitting)
500 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer, int samples)
502 *attrib++ = AGL_RGBA;
503 *attrib++ = AGL_RED_SIZE;*attrib++ = stencil ? 8 : 5;
504 *attrib++ = AGL_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
505 *attrib++ = AGL_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
506 *attrib++ = AGL_DOUBLEBUFFER;
507 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
509 // if stencil is enabled, ask for alpha too
512 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
513 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 8;
516 *attrib++ = AGL_FULLSCREEN;
518 *attrib++ = AGL_STEREO;
519 #ifdef AGL_SAMPLE_BUFFERS_ARB
520 #ifdef AGL_SAMPLES_ARB
523 *attrib++ = AGL_SAMPLE_BUFFERS_ARB;
525 *attrib++ = AGL_SAMPLES_ARB;
531 *attrib++ = AGL_NONE;
534 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
536 const EventTypeSpec winEvents[] =
538 { kEventClassWindow, kEventWindowClosed },
539 { kEventClassWindow, kEventWindowCollapsing },
540 { kEventClassWindow, kEventWindowExpanded },
542 OSStatus carbonError;
544 CFStringRef windowTitle;
545 AGLPixelFormat pixelFormat;
546 GLint attributes [32];
549 if (!GL_OpenLibrary())
551 Con_Printf("Unable to load GL driver\n");
555 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
556 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
557 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
558 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
559 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
560 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
561 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
562 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
563 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
564 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
565 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
568 Con_Printf("AGL functions not found\n");
569 ReleaseWindow(window);
573 qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
574 qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
575 qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
576 if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
577 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
579 // Ignore the events from the previous window
580 AsyncEvent_Quitting = false;
581 AsyncEvent_Collapsed = false;
583 // Create the window, a bit towards the center of the screen
584 windowBounds.left = 100;
585 windowBounds.top = 100;
586 windowBounds.right = width + 100;
587 windowBounds.bottom = height + 100;
588 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
589 if (carbonError != noErr || window == NULL)
591 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
595 // Set the window title
596 windowTitle = CFSTR("DarkPlaces AGL");
597 SetWindowTitleWithCFString(window, windowTitle);
599 // Install the callback function for the window events we can't get
600 // through ReceiveNextEvent (i.e. close, collapse, and expand)
601 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
602 GetEventTypeCount(winEvents), winEvents, window, NULL);
604 // Create the desired attribute list
605 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer, samples);
610 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
611 error = qaglGetError();
612 if (error != AGL_NO_ERROR)
614 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
615 (char *)qaglErrorString(error));
616 ReleaseWindow(window);
620 else // Output is fullScreen
622 CGDirectDisplayID mainDisplay;
623 CFDictionaryRef refDisplayMode;
626 // Get the mainDisplay and set resolution to current
627 mainDisplay = CGMainDisplayID();
628 CGDisplayCapture(mainDisplay);
630 // TOCHECK: not sure whether or not it's necessary to change the resolution
631 // "by hand", or if aglSetFullscreen does the job anyway
632 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
633 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
634 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
636 // Set pixel format with built attribs
637 // Note: specifying a device is *required* for AGL_FullScreen
638 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
639 error = qaglGetError();
640 if (error != AGL_NO_ERROR)
642 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
643 (char *)qaglErrorString(error));
644 ReleaseWindow(window);
649 // Create a context using the pform
650 context = qaglCreateContext(pixelFormat, NULL);
651 error = qaglGetError();
652 if (error != AGL_NO_ERROR)
654 Con_Printf("qaglCreateContext FAILED: %s\n",
655 (char *)qaglErrorString(error));
658 // Make the context the current one ('enable' it)
659 qaglSetCurrentContext(context);
660 error = qaglGetError();
661 if (error != AGL_NO_ERROR)
663 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
664 (char *)qaglErrorString(error));
665 ReleaseWindow(window);
670 qaglDestroyPixelFormat(pixelFormat);
672 // Attempt fullscreen if requested
675 qaglSetFullScreen (context, width, height, refreshrate, 0);
676 error = qaglGetError();
677 if (error != AGL_NO_ERROR)
679 Con_Printf("qaglSetFullScreen FAILED: %s\n",
680 (char *)qaglErrorString(error));
686 // Set Window as Drawable
687 qaglSetDrawable(context, GetWindowPort(window));
688 error = qaglGetError();
689 if (error != AGL_NO_ERROR)
691 Con_Printf("qaglSetDrawable FAILED: %s\n",
692 (char *)qaglErrorString(error));
693 ReleaseWindow(window);
701 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
702 Sys_Error("glGetString not found in %s", gl_driver);
704 gl_platformextensions = "";
706 gl_videosyncavailable = true;
708 multithreadedgl = false;
709 vid_isfullscreen = fullscreen;
710 vid_usingmouse = false;
711 vid_usinghidecursor = false;
713 vid_activewindow = true;
717 SelectWindow(window);
723 static void Handle_KeyMod(UInt32 keymod)
725 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
728 { shiftKey, K_SHIFT },
729 { alphaLock, K_CAPSLOCK },
730 { optionKey, K_ALT },
731 { controlKey, K_CTRL },
732 { kEventKeyModifierNumLockMask, K_NUMLOCK },
733 { kEventKeyModifierFnMask, K_AUX2 }
735 static UInt32 prev_keymod = 0;
739 modChanges = prev_keymod ^ keymod;
743 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
745 UInt32 keybit = keymod_events[i].keybit;
747 if ((modChanges & keybit) != 0)
748 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
751 prev_keymod = keymod;
754 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
756 unsigned int keycode = 0;
801 keycode = K_SCROLLOCK;
807 keycode = K_BACKSPACE;
822 keycode = K_KP_EQUALS;
825 keycode = K_KP_DIVIDE;
828 keycode = K_KP_MULTIPLY;
852 keycode = K_KP_MINUS;
855 keycode = K_CAPSLOCK;
883 keycode = K_KP_ENTER;
889 keycode = K_KP_PERIOD;
894 case kUpArrowCharCode:
897 case kLeftArrowCharCode:
898 keycode = K_LEFTARROW;
900 case kDownArrowCharCode:
901 keycode = K_DOWNARROW;
903 case kRightArrowCharCode:
904 keycode = K_RIGHTARROW;
908 // characters 0 and 191 are sent by the mouse buttons (?!)
911 if ('A' <= charcode && charcode <= 'Z')
913 keycode = charcode + ('a' - 'A'); // lowercase it
916 else if (charcode >= 32)
922 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
927 Key_Event(keycode, ascii, keypressed);
930 void Sys_SendKeyEvents(void)
933 EventTargetRef theTarget;
935 // Start by processing the asynchronous events we received since the previous frame
936 VID_ProcessPendingAsyncEvents();
938 theTarget = GetEventDispatcherTarget();
939 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
941 UInt32 eventClass = GetEventClass(theEvent);
942 UInt32 eventKind = GetEventKind(theEvent);
946 case kEventClassMouse:
948 EventMouseButton theButton;
953 case kEventMouseDown:
955 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
959 case kEventMouseButtonPrimary:
962 case kEventMouseButtonSecondary:
965 case kEventMouseButtonTertiary:
969 Key_Event(key, '\0', eventKind == kEventMouseDown);
972 // Note: These two events are mutual exclusives
973 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
974 case kEventMouseMoved:
975 case kEventMouseDragged:
980 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
981 GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);
985 in_mouse_x += deltaPos.x;
986 in_mouse_y += deltaPos.y;
989 in_windowmouse_x = windowPos.x;
990 in_windowmouse_y = windowPos.y;
994 case kEventMouseWheelMoved:
997 unsigned int wheelEvent;
999 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
1001 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
1002 Key_Event(wheelEvent, 0, true);
1003 Key_Event(wheelEvent, 0, false);
1008 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1013 case kEventClassKeyboard:
1020 case kEventRawKeyDown:
1021 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1022 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1023 Handle_Key(charcode, keycode, true);
1026 case kEventRawKeyRepeat:
1029 case kEventRawKeyUp:
1030 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1031 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1032 Handle_Key(charcode, keycode, false);
1035 case kEventRawKeyModifiersChanged:
1038 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
1039 Handle_KeyMod(keymod);
1043 case kEventHotKeyPressed:
1046 case kEventHotKeyReleased:
1049 case kEventMouseWheelMoved:
1053 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1059 case kEventClassTextInput:
1060 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
1063 case kEventClassApplication:
1066 case kEventAppActivated :
1067 VID_AppFocusChanged(true);
1069 case kEventAppDeactivated:
1070 VID_AppFocusChanged(false);
1075 case kEventAppActiveWindowChanged:
1078 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1083 case kEventClassAppleEvent:
1086 case kEventAppleEvent :
1089 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1094 case kEventClassWindow:
1097 case kEventWindowUpdate :
1100 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1105 case kEventClassControl:
1109 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1110 eventClass >> 24, (eventClass >> 16) & 0xFF,
1111 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1116 SendEventToEventTarget (theEvent, theTarget);
1117 ReleaseEvent(theEvent);