fix all the () problems, and make gcc warn for them
[divverent/darkplaces.git] / vid_agl.c
1 /*
2         vid_agl.c
3
4         Mac OS X OpenGL and input module, using Carbon and AGL
5
6         Copyright (C) 2005-2006  Mathieu Olivier
7
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.
12
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.
17
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
21 */
22
23
24 #include <dlfcn.h>
25 #include <signal.h>
26 #include <AGL/agl.h>
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>
32 #include "quakedef.h"
33 #include "vid_agl_mackeys.h" // this is SDL/src/video/maccommon/SDL_mackeys.h
34
35 #ifndef kCGLCEMPEngine
36 #define kCGLCEMPEngine 313
37 #endif
38
39 // Tell startup code that we have a client
40 int cl_available = true;
41
42 qboolean vid_supportrefreshrate = true;
43
44 // AGL prototypes
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);
59
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;
65
66 static qboolean vid_isfullscreen = false;
67 static qboolean vid_usingvsync = false;
68
69 static qboolean sound_active = true;
70
71 static int scr_width, scr_height;
72
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"};
75
76 static AGLContext context;
77 static WindowRef window;
78
79 static double originalMouseSpeed = -1.0;
80
81 io_connect_t IN_GetIOHandle(void)
82 {
83         io_connect_t iohandle = MACH_PORT_NULL;
84         kern_return_t status;
85         io_service_t iohidsystem = MACH_PORT_NULL;
86         mach_port_t masterport;
87
88         status = IOMasterPort(MACH_PORT_NULL, &masterport);
89         if(status != KERN_SUCCESS)
90                 return 0;
91
92         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
93         if(!iohidsystem)
94                 return 0;
95
96         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
97         IOObjectRelease(iohidsystem);
98
99         return iohandle;
100 }
101
102 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
103 {
104         *x = *y = 0;
105         *width = scr_width;
106         *height = scr_height;
107 }
108
109 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
110 {
111         if (!mouse_avail || !window)
112                 relative = hidecursor = false;
113
114         if (relative)
115         {
116                 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
117                         VID_SetMouse(false, false, false); // ungrab first!
118                 if (!vid_usingmouse)
119                 {
120                         Rect winBounds;
121                         CGPoint winCenter;
122
123                         SelectWindow(window);
124
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);
130
131                         // Lock the mouse pointer at its current position
132                         CGAssociateMouseAndMouseCursorPosition(false);
133
134                         // Save the status of mouse acceleration
135                         originalMouseSpeed = -1.0; // in case of error
136                         if(apple_mouse_noaccel.integer)
137                         {
138                                 io_connect_t mouseDev = IN_GetIOHandle();
139                                 if(mouseDev != 0)
140                                 {
141                                         if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
142                                         {
143                                                 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
144                                                 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
145                                                 {
146                                                         Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
147                                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
148                                                 }
149                                         }
150                                         else
151                                         {
152                                                 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
153                                                 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
154                                         }
155                                         IOServiceClose(mouseDev);
156                                 }
157                                 else
158                                 {
159                                         Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
160                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
161                                 }
162                         }
163
164                         vid_usingmouse = true;
165                         vid_usingnoaccel = !!apple_mouse_noaccel.integer;
166                 }
167         }
168         else
169         {
170                 if (vid_usingmouse)
171                 {
172                         if(originalMouseSpeed != -1.0)
173                         {
174                                 io_connect_t mouseDev = IN_GetIOHandle();
175                                 if(mouseDev != 0)
176                                 {
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);
181                                 }
182                                 else
183                                         Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
184                         }
185
186                         CGAssociateMouseAndMouseCursorPosition(true);
187
188                         vid_usingmouse = false;
189                 }
190         }
191
192         if (vid_usinghidecursor != hidecursor)
193         {
194                 vid_usinghidecursor = hidecursor;
195                 if (hidecursor)
196                         CGDisplayHideCursor(CGMainDisplayID());
197                 else
198                         CGDisplayShowCursor(CGMainDisplayID());
199         }
200 }
201
202 #define GAMMA_TABLE_SIZE 256
203 void VID_Finish (void)
204 {
205         qboolean vid_usevsync;
206
207         // handle changes of the vsync option
208         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
209         if (vid_usingvsync != vid_usevsync)
210         {
211                 GLint sync = (vid_usevsync ? 1 : 0);
212
213                 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
214                 {
215                         vid_usingvsync = vid_usevsync;
216                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
217                 }
218                 else
219                         Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
220         }
221
222         if (r_render.integer)
223         {
224                 CHECKGLERROR
225                 if (r_speeds.integer == 2 || gl_finish.integer)
226                 {
227                         qglFinish();CHECKGLERROR
228                 }
229                 qaglSwapBuffers(context);
230         }
231         VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
232
233         if (apple_multithreadedgl.integer)
234         {
235                 if (!multithreadedgl)
236                 {
237                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
238                         {
239                                 CGLContextObj ctx = qCGLGetCurrentContext();
240                                 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
241                                 if(e == kCGLNoError)
242                                         multithreadedgl = true;
243                                 else
244                                 {
245                                         Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
246                                         Cvar_SetValueQuick(&apple_multithreadedgl, 0);
247                                 }
248                         }
249                         else
250                         {
251                                 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n");
252                                 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
253                         }
254                 }
255         }
256         else
257         {
258                 if (multithreadedgl)
259                 {
260                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
261                         {
262                                 CGLContextObj ctx = qCGLGetCurrentContext();
263                                 qCGLDisable(ctx, kCGLCEMPEngine);
264                                 multithreadedgl = false;
265                         }
266                 }
267         }
268 }
269
270 int VID_SetGamma(unsigned short *ramps, int rampsize)
271 {
272         CGGammaValue table_red [GAMMA_TABLE_SIZE];
273         CGGammaValue table_green [GAMMA_TABLE_SIZE];
274         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
275         int i;
276
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;
284
285         if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
286         {
287                 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
288                 return false;
289         }
290
291         return true;
292 }
293
294 int VID_GetGamma(unsigned short *ramps, int rampsize)
295 {
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;
300         int i;
301
302         // Get the gamma ramps from the system
303         if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
304         {
305                 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
306                 return false;
307         }
308         if (actualsize != (unsigned int)rampsize)
309         {
310                 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
311                 return false;
312         }
313
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;
321
322         return true;
323 }
324
325 void signal_handler(int sig)
326 {
327         printf("Received signal %d, exiting...\n", sig);
328         VID_RestoreSystemGamma();
329         Sys_Quit(1);
330 }
331
332 void InitSig(void)
333 {
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);
344 }
345
346 void VID_Init(void)
347 {
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"))
353                 mouse_avail = false;
354 }
355
356 static void *prjobj = NULL;
357 static void *cglobj = NULL;
358
359 static void GL_CloseLibrary(void)
360 {
361         if (cglobj)
362                 dlclose(cglobj);
363         cglobj = NULL;
364         if (prjobj)
365                 dlclose(prjobj);
366         prjobj = NULL;
367         gl_driver[0] = 0;
368         gl_extensions = "";
369         gl_platform = "";
370         gl_platformextensions = "";
371 }
372
373 static int GL_OpenLibrary(void)
374 {
375         const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
376         const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
377
378         Con_Printf("Loading OpenGL driver %s\n", name);
379         GL_CloseLibrary();
380         if (!(prjobj = dlopen(name, RTLD_LAZY)))
381         {
382                 Con_Printf("Unable to open symbol list for %s\n", name);
383                 return false;
384         }
385         strlcpy(gl_driver, name, sizeof(gl_driver));
386
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);
390
391         return true;
392 }
393
394 void *GL_GetProcAddress(const char *name)
395 {
396         return dlsym(prjobj, name);
397 }
398
399 static void *CGL_GetProcAddress(const char *name)
400 {
401         if(!cglobj)
402                 return NULL;
403         return dlsym(cglobj, name);
404 }
405
406 void VID_Shutdown(void)
407 {
408         if (context == NULL && window == NULL)
409                 return;
410
411         VID_SetMouse(false, false, false);
412         VID_RestoreSystemGamma();
413
414         if (context != NULL)
415         {
416                 qaglDestroyContext(context);
417                 context = NULL;
418         }
419
420         if (vid_isfullscreen)
421                 CGReleaseAllDisplays();
422
423         if (window != NULL)
424         {
425                 DisposeWindow(window);
426                 window = NULL;
427         }
428
429         vid_hidden = true;
430         vid_isfullscreen = false;
431
432         GL_CloseLibrary();
433         Key_ClearStates ();
434 }
435
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)
440 {
441         OSStatus err = noErr;
442
443         switch (GetEventKind (event))
444         {
445                 case kEventWindowClosed:
446                         AsyncEvent_Quitting = true;
447                         break;
448
449                 // Docked (start)
450                 case kEventWindowCollapsing:
451                         AsyncEvent_Collapsed = true;
452                         break;
453
454                 // Undocked / restored (end)
455                 case kEventWindowExpanded:
456                         AsyncEvent_Collapsed = false;
457                         break;
458
459                 default:
460                         err = eventNotHandledErr;
461                         break;
462         }
463
464         return err;
465 }
466
467 static void VID_AppFocusChanged(qboolean windowIsActive)
468 {
469         if (vid_activewindow != windowIsActive)
470         {
471                 vid_activewindow = windowIsActive;
472                 if (!vid_activewindow)
473                         VID_RestoreSystemGamma();
474         }
475
476         if (windowIsActive || !snd_mutewhenidle.integer)
477         {
478                 if (!sound_active)
479                 {
480                         S_UnblockSound ();
481                         sound_active = true;
482                 }
483         }
484         else
485         {
486                 if (sound_active)
487                 {
488                         S_BlockSound ();
489                         sound_active = false;
490                 }
491         }
492 }
493
494 static void VID_ProcessPendingAsyncEvents (void)
495 {
496         // Collapsed / expanded
497         if (AsyncEvent_Collapsed != vid_hidden)
498         {
499                 vid_hidden = !vid_hidden;
500                 VID_AppFocusChanged(!vid_hidden);
501         }
502
503         // Closed
504         if (AsyncEvent_Quitting)
505                 Sys_Quit(0);
506 }
507
508 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer, int samples)
509 {
510         *attrib++ = AGL_RGBA;
511         *attrib++ = AGL_RED_SIZE;*attrib++ = stencil ? 8 : 5;
512         *attrib++ = AGL_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
513         *attrib++ = AGL_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
514         *attrib++ = AGL_DOUBLEBUFFER;
515         *attrib++ = AGL_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
516
517         // if stencil is enabled, ask for alpha too
518         if (stencil)
519         {
520                 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
521                 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 8;
522         }
523         if (fullscreen)
524                 *attrib++ = AGL_FULLSCREEN;
525         if (stereobuffer)
526                 *attrib++ = AGL_STEREO;
527 #ifdef AGL_SAMPLE_BUFFERS_ARB
528 #ifdef AGL_SAMPLES_ARB
529         if (samples > 1)
530         {
531                 *attrib++ = AGL_SAMPLE_BUFFERS_ARB;
532                 *attrib++ = 1;
533                 *attrib++ = AGL_SAMPLES_ARB;
534                 *attrib++ = samples;
535         }
536 #endif
537 #endif
538
539         *attrib++ = AGL_NONE;
540 }
541
542 int VID_InitMode(int fullscreen, int *width, int *height, int bpp, int refreshrate, int stereobuffer, int samples)
543 {
544     const EventTypeSpec winEvents[] =
545         {
546                 { kEventClassWindow, kEventWindowClosed },
547                 { kEventClassWindow, kEventWindowCollapsing },
548                 { kEventClassWindow, kEventWindowExpanded },
549         };
550         OSStatus carbonError;
551         Rect windowBounds;
552         CFStringRef windowTitle;
553         AGLPixelFormat pixelFormat;
554         GLint attributes [32];
555         GLenum error;
556
557         if (!GL_OpenLibrary())
558         {
559                 Con_Printf("Unable to load GL driver\n");
560                 return false;
561         }
562
563         if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
564          || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
565          || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
566          || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
567          || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
568          || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
569          || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
570          || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
571          || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
572          || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
573          || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
574         )
575         {
576                 Con_Printf("AGL functions not found\n");
577                 ReleaseWindow(window);
578                 return false;
579         }
580
581         qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
582         qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
583         qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
584         if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
585                 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
586
587         // Ignore the events from the previous window
588         AsyncEvent_Quitting = false;
589         AsyncEvent_Collapsed = false;
590
591         // Create the window, a bit towards the center of the screen
592         windowBounds.left = 100;
593         windowBounds.top = 100;
594         windowBounds.right = *width + 100;
595         windowBounds.bottom = *height + 100;
596         carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
597         if (carbonError != noErr || window == NULL)
598         {
599                 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
600                 return false;
601         }
602
603         // Set the window title
604         windowTitle = CFSTR("DarkPlaces AGL");
605         SetWindowTitleWithCFString(window, windowTitle);
606
607         // Install the callback function for the window events we can't get
608         // through ReceiveNextEvent (i.e. close, collapse, and expand)
609         InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
610                                                            GetEventTypeCount(winEvents), winEvents, window, NULL);
611
612         // Create the desired attribute list
613         VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer, samples);
614
615         if (!fullscreen)
616         {
617                 // Output to Window
618                 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
619                 error = qaglGetError();
620                 if (error != AGL_NO_ERROR)
621                 {
622                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
623                                         (char *)qaglErrorString(error));
624                         ReleaseWindow(window);
625                         return false;
626                 }
627         }
628         else  // Output is fullScreen
629         {
630                 CGDirectDisplayID mainDisplay;
631                 CFDictionaryRef refDisplayMode;
632                 GDHandle gdhDisplay;
633
634                 // Get the mainDisplay and set resolution to current
635                 mainDisplay = CGMainDisplayID();
636                 CGDisplayCapture(mainDisplay);
637
638                 // TOCHECK: not sure whether or not it's necessary to change the resolution
639                 // "by hand", or if aglSetFullscreen does the job anyway
640                 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty(mainDisplay, bpp, *width, *height, refreshrate, kCGDisplayModeIsSafeForHardware, NULL);
641                 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
642                 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
643
644                 // Set pixel format with built attribs
645                 // Note: specifying a device is *required* for AGL_FullScreen
646                 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
647                 error = qaglGetError();
648                 if (error != AGL_NO_ERROR)
649                 {
650                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
651                                                 (char *)qaglErrorString(error));
652                         ReleaseWindow(window);
653                         return false;
654                 }
655         }
656
657         // Create a context using the pform
658         context = qaglCreateContext(pixelFormat, NULL);
659         error = qaglGetError();
660         if (error != AGL_NO_ERROR)
661         {
662                 Con_Printf("qaglCreateContext FAILED: %s\n",
663                                         (char *)qaglErrorString(error));
664         }
665
666         // Make the context the current one ('enable' it)
667         qaglSetCurrentContext(context);
668         error = qaglGetError();
669         if (error != AGL_NO_ERROR)
670         {
671                 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
672                                         (char *)qaglErrorString(error));
673                 ReleaseWindow(window);
674                 return false;
675         }
676
677         // Discard pform
678         qaglDestroyPixelFormat(pixelFormat);
679
680         // Attempt fullscreen if requested
681         if (fullscreen)
682         {
683                 qaglSetFullScreen (context, *width, *height, refreshrate, 0);
684                 error = qaglGetError();
685                 if (error != AGL_NO_ERROR)
686                 {
687                         Con_Printf("qaglSetFullScreen FAILED: %s\n",
688                                                 (char *)qaglErrorString(error));
689                         return false;
690                 }
691         }
692         else
693         {
694                 // Set Window as Drawable
695                 qaglSetDrawable(context, GetWindowPort(window));
696                 error = qaglGetError();
697                 if (error != AGL_NO_ERROR)
698                 {
699                         Con_Printf("qaglSetDrawable FAILED: %s\n",
700                                                 (char *)qaglErrorString(error));
701                         ReleaseWindow(window);
702                         return false;
703                 }
704         }
705
706         scr_width = *width;
707         scr_height = *height;
708
709         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
710                 Sys_Error("glGetString not found in %s", gl_driver);
711
712         gl_platformextensions = "";
713         gl_platform = "AGL";
714         gl_videosyncavailable = true;
715
716         multithreadedgl = false;
717         vid_isfullscreen = fullscreen;
718         vid_usingmouse = false;
719         vid_usinghidecursor = false;
720         vid_hidden = false;
721         vid_activewindow = true;
722         sound_active = true;
723         GL_Init();
724
725         SelectWindow(window);
726         ShowWindow(window);
727
728         return true;
729 }
730
731 static void Handle_KeyMod(UInt32 keymod)
732 {
733         const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
734         {
735                 { cmdKey,                                               K_AUX1 },
736                 { shiftKey,                                             K_SHIFT },
737                 { alphaLock,                                    K_CAPSLOCK },
738                 { optionKey,                                    K_ALT },
739                 { controlKey,                                   K_CTRL },
740                 { kEventKeyModifierNumLockMask, K_NUMLOCK },
741                 { kEventKeyModifierFnMask,              K_AUX2 }
742         };
743         static UInt32 prev_keymod = 0;
744         unsigned int i;
745         UInt32 modChanges;
746
747         modChanges = prev_keymod ^ keymod;
748         if (modChanges == 0)
749                 return;
750
751         for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
752         {
753                 UInt32 keybit = keymod_events[i].keybit;
754
755                 if ((modChanges & keybit) != 0)
756                         Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
757         }
758
759         prev_keymod = keymod;
760 }
761
762 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
763 {
764         unsigned int keycode = 0;
765         char ascii = '\0';
766
767         switch (mackeycode)
768         {
769                 case MK_ESCAPE:
770                         keycode = K_ESCAPE;
771                         break;
772                 case MK_F1:
773                         keycode = K_F1;
774                         break;
775                 case MK_F2:
776                         keycode = K_F2;
777                         break;
778                 case MK_F3:
779                         keycode = K_F3;
780                         break;
781                 case MK_F4:
782                         keycode = K_F4;
783                         break;
784                 case MK_F5:
785                         keycode = K_F5;
786                         break;
787                 case MK_F6:
788                         keycode = K_F6;
789                         break;
790                 case MK_F7:
791                         keycode = K_F7;
792                         break;
793                 case MK_F8:
794                         keycode = K_F8;
795                         break;
796                 case MK_F9:
797                         keycode = K_F9;
798                         break;
799                 case MK_F10:
800                         keycode = K_F10;
801                         break;
802                 case MK_F11:
803                         keycode = K_F11;
804                         break;
805                 case MK_F12:
806                         keycode = K_F12;
807                         break;
808                 case MK_SCROLLOCK:
809                         keycode = K_SCROLLOCK;
810                         break;
811                 case MK_PAUSE:
812                         keycode = K_PAUSE;
813                         break;
814                 case MK_BACKSPACE:
815                         keycode = K_BACKSPACE;
816                         break;
817                 case MK_INSERT:
818                         keycode = K_INS;
819                         break;
820                 case MK_HOME:
821                         keycode = K_HOME;
822                         break;
823                 case MK_PAGEUP:
824                         keycode = K_PGUP;
825                         break;
826                 case MK_NUMLOCK:
827                         keycode = K_NUMLOCK;
828                         break;
829                 case MK_KP_EQUALS:
830                         keycode = K_KP_EQUALS;
831                         break;
832                 case MK_KP_DIVIDE:
833                         keycode = K_KP_DIVIDE;
834                         break;
835                 case MK_KP_MULTIPLY:
836                         keycode = K_KP_MULTIPLY;
837                         break;
838                 case MK_TAB:
839                         keycode = K_TAB;
840                         break;
841                 case MK_DELETE:
842                         keycode = K_DEL;
843                         break;
844                 case MK_END:
845                         keycode = K_END;
846                         break;
847                 case MK_PAGEDOWN:
848                         keycode = K_PGDN;
849                         break;
850                 case MK_KP7:
851                         keycode = K_KP_7;
852                         break;
853                 case MK_KP8:
854                         keycode = K_KP_8;
855                         break;
856                 case MK_KP9:
857                         keycode = K_KP_9;
858                         break;
859                 case MK_KP_MINUS:
860                         keycode = K_KP_MINUS;
861                         break;
862                 case MK_CAPSLOCK:
863                         keycode = K_CAPSLOCK;
864                         break;
865                 case MK_RETURN:
866                         keycode = K_ENTER;
867                         break;
868                 case MK_KP4:
869                         keycode = K_KP_4;
870                         break;
871                 case MK_KP5:
872                         keycode = K_KP_5;
873                         break;
874                 case MK_KP6:
875                         keycode = K_KP_6;
876                         break;
877                 case MK_KP_PLUS:
878                         keycode = K_KP_PLUS;
879                         break;
880                 case MK_KP1:
881                         keycode = K_KP_1;
882                         break;
883                 case MK_KP2:
884                         keycode = K_KP_2;
885                         break;
886                 case MK_KP3:
887                         keycode = K_KP_3;
888                         break;
889                 case MK_KP_ENTER:
890                 case MK_IBOOK_ENTER:
891                         keycode = K_KP_ENTER;
892                         break;
893                 case MK_KP0:
894                         keycode = K_KP_0;
895                         break;
896                 case MK_KP_PERIOD:
897                         keycode = K_KP_PERIOD;
898                         break;
899                 default:
900                         switch(charcode)
901                         {
902                                 case kUpArrowCharCode:
903                                         keycode = K_UPARROW;
904                                         break;
905                                 case kLeftArrowCharCode:
906                                         keycode = K_LEFTARROW;
907                                         break;
908                                 case kDownArrowCharCode:
909                                         keycode = K_DOWNARROW;
910                                         break;
911                                 case kRightArrowCharCode:
912                                         keycode = K_RIGHTARROW;
913                                         break;
914                                 case 0:
915                                 case 191:
916                                         // characters 0 and 191 are sent by the mouse buttons (?!)
917                                         break;
918                                 default:
919                                         if ('A' <= charcode && charcode <= 'Z')
920                                         {
921                                                 keycode = charcode + ('a' - 'A');  // lowercase it
922                                                 ascii = charcode;
923                                         }
924                                         else if (charcode >= 32)
925                                         {
926                                                 keycode = charcode;
927                                                 ascii = charcode;
928                                         }
929                                         else
930                                                 Con_DPrintf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
931                         }
932         }
933
934         if (keycode != 0)
935                 Key_Event(keycode, ascii, keypressed);
936 }
937
938 void Sys_SendKeyEvents(void)
939 {
940         EventRef theEvent;
941         EventTargetRef theTarget;
942
943         // Start by processing the asynchronous events we received since the previous frame
944         VID_ProcessPendingAsyncEvents();
945
946         theTarget = GetEventDispatcherTarget();
947         while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
948         {
949                 UInt32 eventClass = GetEventClass(theEvent);
950                 UInt32 eventKind = GetEventKind(theEvent);
951
952                 switch (eventClass)
953                 {
954                         case kEventClassMouse:
955                         {
956                                 EventMouseButton theButton;
957                                 int key;
958
959                                 switch (eventKind)
960                                 {
961                                         case kEventMouseDown:
962                                         case kEventMouseUp:
963                                                 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
964                                                 switch (theButton)
965                                                 {
966                                                         default:
967                                                         case kEventMouseButtonPrimary:
968                                                                 key = K_MOUSE1;
969                                                                 break;
970                                                         case kEventMouseButtonSecondary:
971                                                                 key = K_MOUSE2;
972                                                                 break;
973                                                         case kEventMouseButtonTertiary:
974                                                                 key = K_MOUSE3;
975                                                                 break;
976                                                 }
977                                                 Key_Event(key, '\0', eventKind == kEventMouseDown);
978                                                 break;
979
980                                         // Note: These two events are mutual exclusives
981                                         // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
982                                         case kEventMouseMoved:
983                                         case kEventMouseDragged:
984                                         {
985                                                 HIPoint deltaPos;
986                                                 HIPoint windowPos;
987
988                                                 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
989                                                 GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);
990
991                                                 if (vid_usingmouse)
992                                                 {
993                                                         in_mouse_x += deltaPos.x;
994                                                         in_mouse_y += deltaPos.y;
995                                                 }
996
997                                                 in_windowmouse_x = windowPos.x;
998                                                 in_windowmouse_y = windowPos.y;
999                                                 break;
1000                                         }
1001
1002                                         case kEventMouseWheelMoved:
1003                                         {
1004                                                 SInt32 delta;
1005                                                 unsigned int wheelEvent;
1006
1007                                                 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
1008
1009                                                 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
1010                                                 Key_Event(wheelEvent, 0, true);
1011                                                 Key_Event(wheelEvent, 0, false);
1012                                                 break;
1013                                         }
1014
1015                                         default:
1016                                                 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1017                                                 break;
1018                                 }
1019                         }
1020
1021                         case kEventClassKeyboard:
1022                         {
1023                                 char charcode;
1024                                 UInt32 keycode;
1025
1026                                 switch (eventKind)
1027                                 {
1028                                         case kEventRawKeyDown:
1029                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1030                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1031                                                 Handle_Key(charcode, keycode, true);
1032                                                 break;
1033
1034                                         case kEventRawKeyRepeat:
1035                                                 break;
1036
1037                                         case kEventRawKeyUp:
1038                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
1039                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
1040                                                 Handle_Key(charcode, keycode, false);
1041                                                 break;
1042
1043                                         case kEventRawKeyModifiersChanged:
1044                                         {
1045                                                 UInt32 keymod = 0;
1046                                                 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
1047                                                 Handle_KeyMod(keymod);
1048                                                 break;
1049                                         }
1050
1051                                         case kEventHotKeyPressed:
1052                                                 break;
1053
1054                                         case kEventHotKeyReleased:
1055                                                 break;
1056
1057                                         case kEventMouseWheelMoved:
1058                                                 break;
1059
1060                                         default:
1061                                                 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1062                                                 break;
1063                                 }
1064                                 break;
1065                         }
1066
1067                         case kEventClassTextInput:
1068                                 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
1069                                 break;
1070
1071                         case kEventClassApplication:
1072                                 switch (eventKind)
1073                                 {
1074                                         case kEventAppActivated :
1075                                                 VID_AppFocusChanged(true);
1076                                                 break;
1077                                         case kEventAppDeactivated:
1078                                                 VID_AppFocusChanged(false);
1079                                                 break;
1080                                         case kEventAppQuit:
1081                                                 Sys_Quit(0);
1082                                                 break;
1083                                         case kEventAppActiveWindowChanged:
1084                                                 break;
1085                                         default:
1086                                                 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1087                                                 break;
1088                                 }
1089                                 break;
1090
1091                         case kEventClassAppleEvent:
1092                                 switch (eventKind)
1093                                 {
1094                                         case kEventAppleEvent :
1095                                                 break;
1096                                         default:
1097                                                 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1098                                                 break;
1099                                 }
1100                                 break;
1101
1102                         case kEventClassWindow:
1103                                 switch (eventKind)
1104                                 {
1105                                         case kEventWindowUpdate :
1106                                                 break;
1107                                         default:
1108                                                 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1109                                                 break;
1110                                 }
1111                                 break;
1112
1113                         case kEventClassControl:
1114                                 break;
1115
1116                         default:
1117                                 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1118                                                         eventClass >> 24, (eventClass >> 16) & 0xFF,
1119                                                         (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1120                                                         eventKind);*/
1121                                 break;
1122                 }
1123
1124                 SendEventToEventTarget (theEvent, theTarget);
1125                 ReleaseEvent(theEvent);
1126         }
1127 }
1128
1129 void IN_Move (void)
1130 {
1131 }
1132
1133 static bool GetDictionaryBoolean(CFDictionaryRef d, const void *key)
1134 {
1135     CFBooleanRef ref = (CFBooleanRef) CFDictionaryGetValue(d, key);
1136     if(ref)
1137         return CFBooleanGetValue(ref);
1138     return false;
1139 }
1140
1141 long GetDictionaryLong(CFDictionaryRef d, const void *key)
1142 {
1143         long value = 0;
1144     CFNumberRef ref = (CFNumberRef) CFDictionaryGetValue(d, key);
1145     if(ref)
1146         CFNumberGetValue(ref, kCFNumberLongType, &value);
1147     return value;
1148 }
1149
1150 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1151 {
1152         CGDirectDisplayID mainDisplay = CGMainDisplayID();
1153         CFArrayRef vidmodes = CGDisplayAvailableModes(mainDisplay);
1154         CFDictionaryRef thismode;
1155         unsigned int n = CFArrayGetCount(vidmodes);
1156         unsigned int i;
1157         size_t k;
1158
1159         k = 0;
1160         for(i = 0; i < n; ++i)
1161         {
1162                 thismode = (CFDictionaryRef) CFArrayGetValueAtIndex(vidmodes, i);
1163                 if(!GetDictionaryBoolean(thismode, kCGDisplayModeIsSafeForHardware))
1164                         continue;
1165
1166                 if(k >= maxcount)
1167                         break;
1168                 modes[k].width = GetDictionaryLong(thismode, kCGDisplayWidth);
1169                 modes[k].height = GetDictionaryLong(thismode, kCGDisplayHeight);
1170                 modes[k].bpp = GetDictionaryLong(thismode, kCGDisplayBitsPerPixel);
1171                 modes[k].refreshrate = GetDictionaryLong(thismode, kCGDisplayRefreshRate);
1172                 modes[k].pixelheight_num = 1;
1173                 modes[k].pixelheight_denom = 1; // OS X doesn't expose this either
1174                 ++k;
1175         }
1176         return k;
1177 }