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;
65 static qboolean vid_isfullscreen = false;
66 static qboolean vid_usingvsync = false;
68 static qboolean sound_active = true;
70 static int scr_width, scr_height;
72 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)"};
73 static cvar_t apple_mouse_noaccel = {CVAR_SAVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
75 static AGLContext context;
76 static WindowRef window;
78 static double originalMouseSpeed = -1.0;
80 io_connect_t IN_GetIOHandle()
82 io_connect_t iohandle = MACH_PORT_NULL;
84 io_service_t iohidsystem = MACH_PORT_NULL;
85 mach_port_t masterport;
87 status = IOMasterPort(MACH_PORT_NULL, &masterport);
88 if(status != KERN_SUCCESS)
91 iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
95 status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
96 IOObjectRelease(iohidsystem);
101 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
105 *height = scr_height;
108 void VID_GrabMouse(qboolean grab)
112 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
113 VID_GrabMouse(false); // ungrab first!
114 if (!vid_usingmouse && mouse_avail && window)
119 SelectWindow(window);
120 CGDisplayHideCursor(CGMainDisplayID());
122 // Put the mouse cursor at the center of the window
123 GetWindowBounds (window, kWindowContentRgn, &winBounds);
124 winCenter.x = (winBounds.left + winBounds.right) / 2;
125 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
126 CGWarpMouseCursorPosition(winCenter);
128 // Lock the mouse pointer at its current position
129 CGAssociateMouseAndMouseCursorPosition(false);
131 // Save the status of mouse acceleration
132 originalMouseSpeed = -1.0; // in case of error
133 if(apple_mouse_noaccel.integer)
135 io_connect_t mouseDev = IN_GetIOHandle();
138 if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
140 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
141 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
143 Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
144 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
149 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
150 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
152 IOServiceClose(mouseDev);
156 Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
157 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
161 vid_usingmouse = true;
162 vid_usingnoaccel = !!apple_mouse_noaccel.integer;
169 if(originalMouseSpeed != -1.0)
171 io_connect_t mouseDev = IN_GetIOHandle();
174 Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
175 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
176 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
177 IOServiceClose(mouseDev);
180 Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
183 CGAssociateMouseAndMouseCursorPosition(true);
184 CGDisplayShowCursor(CGMainDisplayID());
186 vid_usingmouse = false;
191 #define GAMMA_TABLE_SIZE 256
192 void VID_Finish (void)
194 qboolean vid_usevsync;
196 // handle changes of the vsync option
197 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
198 if (vid_usingvsync != vid_usevsync)
200 GLint sync = (vid_usevsync ? 1 : 0);
202 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
204 vid_usingvsync = vid_usevsync;
205 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
208 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
211 if (r_render.integer)
214 if (r_speeds.integer || gl_finish.integer)
216 qglFinish();CHECKGLERROR
218 qaglSwapBuffers(context);
220 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
222 if (apple_multithreadedgl.integer)
224 if (!multithreadedgl)
226 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
228 CGLContextObj ctx = qCGLGetCurrentContext();
229 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
231 multithreadedgl = true;
234 Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
235 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
240 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
241 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
249 if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
251 CGLContextObj ctx = qCGLGetCurrentContext();
252 qCGLDisable(ctx, kCGLCEMPEngine);
253 multithreadedgl = false;
259 int VID_SetGamma(unsigned short *ramps, int rampsize)
261 CGGammaValue table_red [GAMMA_TABLE_SIZE];
262 CGGammaValue table_green [GAMMA_TABLE_SIZE];
263 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
266 // Convert the unsigned short table into 3 float tables
267 for (i = 0; i < rampsize; i++)
268 table_red[i] = (float)ramps[i] / 65535.0f;
269 for (i = 0; i < rampsize; i++)
270 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
271 for (i = 0; i < rampsize; i++)
272 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
274 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
276 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
283 int VID_GetGamma(unsigned short *ramps, int rampsize)
285 CGGammaValue table_red [GAMMA_TABLE_SIZE];
286 CGGammaValue table_green [GAMMA_TABLE_SIZE];
287 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
288 CGTableCount actualsize = 0;
291 // Get the gamma ramps from the system
292 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
294 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
297 if (actualsize != (unsigned int)rampsize)
299 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
303 // Convert the 3 float tables into 1 unsigned short table
304 for (i = 0; i < rampsize; i++)
305 ramps[i] = table_red[i] * 65535.0f;
306 for (i = 0; i < rampsize; i++)
307 ramps[i + rampsize] = table_green[i] * 65535.0f;
308 for (i = 0; i < rampsize; i++)
309 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
314 void signal_handler(int sig)
316 printf("Received signal %d, exiting...\n", sig);
317 VID_RestoreSystemGamma();
323 signal(SIGHUP, signal_handler);
324 signal(SIGINT, signal_handler);
325 signal(SIGQUIT, signal_handler);
326 signal(SIGILL, signal_handler);
327 signal(SIGTRAP, signal_handler);
328 signal(SIGIOT, signal_handler);
329 signal(SIGBUS, signal_handler);
330 signal(SIGFPE, signal_handler);
331 signal(SIGSEGV, signal_handler);
332 signal(SIGTERM, signal_handler);
337 InitSig(); // trap evil signals
338 Cvar_RegisterVariable(&apple_multithreadedgl);
339 Cvar_RegisterVariable(&apple_mouse_noaccel);
340 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
341 if (COM_CheckParm ("-nomouse"))
345 static void *prjobj = NULL;
346 static void *cglobj = NULL;
348 static void GL_CloseLibrary(void)
359 gl_platformextensions = "";
362 static int GL_OpenLibrary(void)
364 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
365 const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
367 Con_Printf("Loading OpenGL driver %s\n", name);
369 if (!(prjobj = dlopen(name, RTLD_LAZY)))
371 Con_Printf("Unable to open symbol list for %s\n", name);
374 strlcpy(gl_driver, name, sizeof(gl_driver));
376 Con_Printf("Loading OpenGL driver %s\n", name2);
377 if (!(cglobj = dlopen(name2, RTLD_LAZY)))
378 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
383 void *GL_GetProcAddress(const char *name)
385 return dlsym(prjobj, name);
388 static void *CGL_GetProcAddress(const char *name)
392 return dlsym(cglobj, name);
395 void VID_Shutdown(void)
397 if (context == NULL && window == NULL)
400 VID_GrabMouse(false);
401 VID_RestoreSystemGamma();
405 qaglDestroyContext(context);
409 if (vid_isfullscreen)
410 CGReleaseAllDisplays();
414 DisposeWindow(window);
419 vid_isfullscreen = false;
425 // Since the event handler can be called at any time, we store the events for later processing
426 static qboolean AsyncEvent_Quitting = false;
427 static qboolean AsyncEvent_Collapsed = false;
428 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
430 OSStatus err = noErr;
432 switch (GetEventKind (event))
434 case kEventWindowClosed:
435 AsyncEvent_Quitting = true;
439 case kEventWindowCollapsing:
440 AsyncEvent_Collapsed = true;
443 // Undocked / restored (end)
444 case kEventWindowExpanded:
445 AsyncEvent_Collapsed = false;
449 err = eventNotHandledErr;
456 static void VID_AppFocusChanged(qboolean windowIsActive)
458 if (vid_activewindow != windowIsActive)
460 vid_activewindow = windowIsActive;
461 if (!vid_activewindow)
462 VID_RestoreSystemGamma();
465 if (sound_active != windowIsActive)
467 sound_active = windowIsActive;
475 static void VID_ProcessPendingAsyncEvents (void)
477 // Collapsed / expanded
478 if (AsyncEvent_Collapsed != vid_hidden)
480 vid_hidden = !vid_hidden;
481 VID_AppFocusChanged(!vid_hidden);
485 if (AsyncEvent_Quitting)
489 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer, int samples)
491 *attrib++ = AGL_RGBA;
492 *attrib++ = AGL_RED_SIZE;*attrib++ = stencil ? 8 : 5;
493 *attrib++ = AGL_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
494 *attrib++ = AGL_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
495 *attrib++ = AGL_DOUBLEBUFFER;
496 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
498 // if stencil is enabled, ask for alpha too
501 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
502 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 8;
505 *attrib++ = AGL_FULLSCREEN;
507 *attrib++ = AGL_STEREO;
508 #ifdef AGL_SAMPLE_BUFFERS_ARB
509 #ifdef AGL_SAMPLES_ARB
512 *attrib++ = AGL_SAMPLE_BUFFERS_ARB;
514 *attrib++ = AGL_SAMPLES_ARB;
520 *attrib++ = AGL_NONE;
523 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
525 const EventTypeSpec winEvents[] =
527 { kEventClassWindow, kEventWindowClosed },
528 { kEventClassWindow, kEventWindowCollapsing },
529 { kEventClassWindow, kEventWindowExpanded },
531 OSStatus carbonError;
533 CFStringRef windowTitle;
534 AGLPixelFormat pixelFormat;
535 GLint attributes [32];
538 if (!GL_OpenLibrary())
540 Con_Printf("Unable to load GL driver\n");
544 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
545 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
546 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
547 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
548 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
549 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
550 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
551 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
552 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
553 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
554 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
557 Con_Printf("AGL functions not found\n");
558 ReleaseWindow(window);
562 qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
563 qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
564 qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
565 if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
566 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
568 // Ignore the events from the previous window
569 AsyncEvent_Quitting = false;
570 AsyncEvent_Collapsed = false;
572 // Create the window, a bit towards the center of the screen
573 windowBounds.left = 100;
574 windowBounds.top = 100;
575 windowBounds.right = width + 100;
576 windowBounds.bottom = height + 100;
577 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
578 if (carbonError != noErr || window == NULL)
580 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
584 // Set the window title
585 windowTitle = CFSTR("DarkPlaces AGL");
586 SetWindowTitleWithCFString(window, windowTitle);
588 // Install the callback function for the window events we can't get
589 // through ReceiveNextEvent (i.e. close, collapse, and expand)
590 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
591 GetEventTypeCount(winEvents), winEvents, window, NULL);
593 // Create the desired attribute list
594 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer, samples);
599 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
600 error = qaglGetError();
601 if (error != AGL_NO_ERROR)
603 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
604 (char *)qaglErrorString(error));
605 ReleaseWindow(window);
609 else // Output is fullScreen
611 CGDirectDisplayID mainDisplay;
612 CFDictionaryRef refDisplayMode;
615 // Get the mainDisplay and set resolution to current
616 mainDisplay = CGMainDisplayID();
617 CGDisplayCapture(mainDisplay);
619 // TOCHECK: not sure whether or not it's necessary to change the resolution
620 // "by hand", or if aglSetFullscreen does the job anyway
621 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
622 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
623 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
625 // Set pixel format with built attribs
626 // Note: specifying a device is *required* for AGL_FullScreen
627 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
628 error = qaglGetError();
629 if (error != AGL_NO_ERROR)
631 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
632 (char *)qaglErrorString(error));
633 ReleaseWindow(window);
638 // Create a context using the pform
639 context = qaglCreateContext(pixelFormat, NULL);
640 error = qaglGetError();
641 if (error != AGL_NO_ERROR)
643 Con_Printf("qaglCreateContext FAILED: %s\n",
644 (char *)qaglErrorString(error));
647 // Make the context the current one ('enable' it)
648 qaglSetCurrentContext(context);
649 error = qaglGetError();
650 if (error != AGL_NO_ERROR)
652 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
653 (char *)qaglErrorString(error));
654 ReleaseWindow(window);
659 qaglDestroyPixelFormat(pixelFormat);
661 // Attempt fullscreen if requested
664 qaglSetFullScreen (context, width, height, refreshrate, 0);
665 error = qaglGetError();
666 if (error != AGL_NO_ERROR)
668 Con_Printf("qaglSetFullScreen FAILED: %s\n",
669 (char *)qaglErrorString(error));
675 // Set Window as Drawable
676 qaglSetDrawable(context, GetWindowPort(window));
677 error = qaglGetError();
678 if (error != AGL_NO_ERROR)
680 Con_Printf("qaglSetDrawable FAILED: %s\n",
681 (char *)qaglErrorString(error));
682 ReleaseWindow(window);
690 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
691 Sys_Error("glGetString not found in %s", gl_driver);
693 gl_platformextensions = "";
695 gl_videosyncavailable = true;
697 multithreadedgl = false;
698 vid_isfullscreen = fullscreen;
699 vid_usingmouse = false;
701 vid_activewindow = true;
705 SelectWindow(window);
711 static void Handle_KeyMod(UInt32 keymod)
713 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
716 { shiftKey, K_SHIFT },
717 { alphaLock, K_CAPSLOCK },
718 { optionKey, K_ALT },
719 { controlKey, K_CTRL },
720 { kEventKeyModifierNumLockMask, K_NUMLOCK },
721 { kEventKeyModifierFnMask, K_AUX2 }
723 static UInt32 prev_keymod = 0;
727 modChanges = prev_keymod ^ keymod;
731 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
733 UInt32 keybit = keymod_events[i].keybit;
735 if ((modChanges & keybit) != 0)
736 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
739 prev_keymod = keymod;
742 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
744 unsigned int keycode = 0;
789 keycode = K_SCROLLOCK;
795 keycode = K_BACKSPACE;
810 keycode = K_KP_EQUALS;
813 keycode = K_KP_DIVIDE;
816 keycode = K_KP_MULTIPLY;
840 keycode = K_KP_MINUS;
843 keycode = K_CAPSLOCK;
871 keycode = K_KP_ENTER;
877 keycode = K_KP_PERIOD;
882 case kUpArrowCharCode:
885 case kLeftArrowCharCode:
886 keycode = K_LEFTARROW;
888 case kDownArrowCharCode:
889 keycode = K_DOWNARROW;
891 case kRightArrowCharCode:
892 keycode = K_RIGHTARROW;
896 // characters 0 and 191 are sent by the mouse buttons (?!)
899 if ('A' <= charcode && charcode <= 'Z')
901 keycode = charcode + ('a' - 'A'); // lowercase it
904 else if (charcode >= 32)
910 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
915 Key_Event(keycode, ascii, keypressed);
918 void Sys_SendKeyEvents(void)
921 EventTargetRef theTarget;
923 // Start by processing the asynchronous events we received since the previous frame
924 VID_ProcessPendingAsyncEvents();
926 theTarget = GetEventDispatcherTarget();
927 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
929 UInt32 eventClass = GetEventClass(theEvent);
930 UInt32 eventKind = GetEventKind(theEvent);
934 case kEventClassMouse:
936 EventMouseButton theButton;
941 case kEventMouseDown:
943 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
947 case kEventMouseButtonPrimary:
950 case kEventMouseButtonSecondary:
953 case kEventMouseButtonTertiary:
957 Key_Event(key, '\0', eventKind == kEventMouseDown);
960 // Note: These two events are mutual exclusives
961 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
962 case kEventMouseMoved:
963 case kEventMouseDragged:
968 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
969 GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);
973 in_mouse_x += deltaPos.x;
974 in_mouse_y += deltaPos.y;
977 in_windowmouse_x = windowPos.x;
978 in_windowmouse_y = windowPos.y;
982 case kEventMouseWheelMoved:
985 unsigned int wheelEvent;
987 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
989 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
990 Key_Event(wheelEvent, 0, true);
991 Key_Event(wheelEvent, 0, false);
996 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1001 case kEventClassKeyboard:
1008 case kEventRawKeyDown:
1009 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1010 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1011 Handle_Key(charcode, keycode, true);
1014 case kEventRawKeyRepeat:
1017 case kEventRawKeyUp:
1018 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1019 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1020 Handle_Key(charcode, keycode, false);
1023 case kEventRawKeyModifiersChanged:
1026 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
1027 Handle_KeyMod(keymod);
1031 case kEventHotKeyPressed:
1034 case kEventHotKeyReleased:
1037 case kEventMouseWheelMoved:
1041 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1047 case kEventClassTextInput:
1048 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
1051 case kEventClassApplication:
1054 case kEventAppActivated :
1055 VID_AppFocusChanged(true);
1057 case kEventAppDeactivated:
1058 VID_AppFocusChanged(false);
1063 case kEventAppActiveWindowChanged:
1066 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1071 case kEventClassAppleEvent:
1074 case kEventAppleEvent :
1077 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1082 case kEventClassWindow:
1085 case kEventWindowUpdate :
1088 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1093 case kEventClassControl:
1097 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1098 eventClass >> 24, (eventClass >> 16) & 0xFF,
1099 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1104 SendEventToEventTarget (theEvent, theTarget);
1105 ReleaseEvent(theEvent);