changed PF_WARNING to not do a return
[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 <Carbon/Carbon.h>
28 #include "quakedef.h"
29
30
31 // Tell startup code that we have a client
32 int cl_available = true;
33
34 qboolean vid_supportrefreshrate = true;
35
36 // AGL prototypes
37 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
38 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
39 GLboolean (*qaglDestroyContext) (AGLContext ctx);
40 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
41 const GLubyte* (*qaglErrorString) (GLenum code);
42 GLenum (*qaglGetError) (void);
43 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
44 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
45 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
46 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
47 void (*qaglSwapBuffers) (AGLContext ctx);
48
49 static qboolean mouse_avail = true;
50 static qboolean vid_usingmouse = false;
51 static float mouse_x, mouse_y;
52
53 static qboolean vid_isfullscreen = false;
54 static qboolean vid_usingvsync = false;
55
56 static qboolean sound_active = true;
57
58 static int scr_width, scr_height;
59
60 static AGLContext context;
61 static WindowRef window;
62
63
64 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
65 {
66         *x = *y = 0;
67         *width = scr_width;
68         *height = scr_height;
69 }
70
71 static void IN_Activate( qboolean grab )
72 {
73         if (grab)
74         {
75                 if (!vid_usingmouse && mouse_avail && window)
76                 {
77                         Rect winBounds;
78                         CGPoint winCenter;
79
80                         SelectWindow(window);
81                         CGDisplayHideCursor(CGMainDisplayID());
82
83                         // Put the mouse cursor at the center of the window
84                         GetWindowBounds (window, kWindowContentRgn, &winBounds);
85                         winCenter.x = (winBounds.left + winBounds.right) / 2;
86                         winCenter.y = (winBounds.top + winBounds.bottom) / 2;
87                         CGWarpMouseCursorPosition(winCenter);
88
89                         // Lock the mouse pointer at its current position
90                         CGAssociateMouseAndMouseCursorPosition(false);
91
92                         mouse_x = mouse_y = 0;
93                         vid_usingmouse = true;
94                 }
95         }
96         else
97         {
98                 if (vid_usingmouse)
99                 {
100                         CGAssociateMouseAndMouseCursorPosition(true);
101                         CGDisplayShowCursor(CGMainDisplayID());
102
103                         vid_usingmouse = false;
104                 }
105         }
106 }
107
108 #define GAMMA_TABLE_SIZE 256
109 void VID_Finish (qboolean allowmousegrab)
110 {
111         qboolean vid_usemouse;
112         qboolean vid_usevsync;
113
114         // handle the mouse state when windowed if that's changed
115         vid_usemouse = false;
116         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
117                 vid_usemouse = true;
118         if (!vid_activewindow)
119                 vid_usemouse = false;
120         if (vid_isfullscreen)
121                 vid_usemouse = true;
122         IN_Activate(vid_usemouse);
123
124         // handle changes of the vsync option
125         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
126         if (vid_usingvsync != vid_usevsync)
127         {
128                 GLint sync = (vid_usevsync ? 1 : 0);
129
130                 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
131                 {
132                         vid_usingvsync = vid_usevsync;
133                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
134                 }
135                 else
136                         Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
137         }
138
139         if (r_render.integer)
140         {
141                 CHECKGLERROR
142                 if (r_speeds.integer || gl_finish.integer)
143                 {
144                         qglFinish();CHECKGLERROR
145                 }
146                 qaglSwapBuffers(context);
147         }
148         VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
149 }
150
151 int VID_SetGamma(unsigned short *ramps, int rampsize)
152 {
153         CGGammaValue table_red [GAMMA_TABLE_SIZE];
154         CGGammaValue table_green [GAMMA_TABLE_SIZE];
155         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
156         int i;
157
158         // Convert the unsigned short table into 3 float tables
159         for (i = 0; i < rampsize; i++)
160                 table_red[i] = (float)ramps[i] / 65535.0f;
161         for (i = 0; i < rampsize; i++)
162                 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
163         for (i = 0; i < rampsize; i++)
164                 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
165
166         if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
167         {
168                 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
169                 return false;
170         }
171
172         return true;
173 }
174
175 int VID_GetGamma(unsigned short *ramps, int rampsize)
176 {
177         CGGammaValue table_red [GAMMA_TABLE_SIZE];
178         CGGammaValue table_green [GAMMA_TABLE_SIZE];
179         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
180         CGTableCount actualsize = 0;
181         int i;
182
183         // Get the gamma ramps from the system
184         if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
185         {
186                 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
187                 return false;
188         }
189         if (actualsize != (unsigned int)rampsize)
190         {
191                 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
192                 return false;
193         }
194
195         // Convert the 3 float tables into 1 unsigned short table
196         for (i = 0; i < rampsize; i++)
197                 ramps[i] = table_red[i] * 65535.0f;
198         for (i = 0; i < rampsize; i++)
199                 ramps[i + rampsize] = table_green[i] * 65535.0f;
200         for (i = 0; i < rampsize; i++)
201                 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
202
203         return true;
204 }
205
206 void signal_handler(int sig)
207 {
208         printf("Received signal %d, exiting...\n", sig);
209         VID_RestoreSystemGamma();
210         Sys_Quit();
211         exit(0);
212 }
213
214 void InitSig(void)
215 {
216         signal(SIGHUP, signal_handler);
217         signal(SIGINT, signal_handler);
218         signal(SIGQUIT, signal_handler);
219         signal(SIGILL, signal_handler);
220         signal(SIGTRAP, signal_handler);
221         signal(SIGIOT, signal_handler);
222         signal(SIGBUS, signal_handler);
223         signal(SIGFPE, signal_handler);
224         signal(SIGSEGV, signal_handler);
225         signal(SIGTERM, signal_handler);
226 }
227
228 void VID_Init(void)
229 {
230         InitSig(); // trap evil signals
231 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
232         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
233                 mouse_avail = false;
234 }
235
236 static void *prjobj = NULL;
237
238 static void GL_CloseLibrary(void)
239 {
240         if (prjobj)
241                 dlclose(prjobj);
242         prjobj = NULL;
243         gl_driver[0] = 0;
244         gl_extensions = "";
245         gl_platform = "";
246         gl_platformextensions = "";
247 }
248
249 static int GL_OpenLibrary(void)
250 {
251         const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
252
253         Con_Printf("Loading OpenGL driver %s\n", name);
254         GL_CloseLibrary();
255         if (!(prjobj = dlopen(name, RTLD_LAZY)))
256         {
257                 Con_Printf("Unable to open symbol list for %s\n", name);
258                 return false;
259         }
260         strcpy(gl_driver, name);
261         return true;
262 }
263
264 void *GL_GetProcAddress(const char *name)
265 {
266         return dlsym(prjobj, name);
267 }
268
269 void VID_Shutdown(void)
270 {
271         if (context == NULL && window == NULL)
272                 return;
273
274         IN_Activate(false);
275         VID_RestoreSystemGamma();
276
277         if (context != NULL)
278         {
279                 qaglDestroyContext(context);
280                 context = NULL;
281         }
282
283         if (vid_isfullscreen)
284                 CGReleaseAllDisplays();
285
286         if (window != NULL)
287         {
288                 DisposeWindow(window);
289                 window = NULL;
290         }
291
292         vid_hidden = true;
293         vid_isfullscreen = false;
294
295         GL_CloseLibrary();
296         Key_ClearStates ();
297 }
298
299 // Since the event handler can be called at any time, we store the events for later processing
300 static qboolean AsyncEvent_Quitting = false;
301 static qboolean AsyncEvent_Collapsed = false;
302 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
303 {
304         OSStatus err = noErr;
305
306         switch (GetEventKind (event))
307         {
308                 case kEventWindowClosed:
309                         AsyncEvent_Quitting = true;
310                         break;
311
312                 // Docked (start)
313                 case kEventWindowCollapsing:
314                         AsyncEvent_Collapsed = true;
315                         break;
316
317                 // Undocked / restored (end)
318                 case kEventWindowExpanded:
319                         AsyncEvent_Collapsed = false;
320                         break;
321
322                 default:
323                         err = eventNotHandledErr;
324                         break;
325         }
326
327         return err;
328 }
329
330 static void VID_AppFocusChanged(qboolean windowIsActive)
331 {
332         if (vid_activewindow != windowIsActive)
333         {
334                 vid_activewindow = windowIsActive;
335                 if (!vid_activewindow)
336                         VID_RestoreSystemGamma();
337         }
338
339         if (sound_active != windowIsActive)
340         {
341                 sound_active = windowIsActive;
342                 if (sound_active)
343                         S_UnblockSound ();
344                 else
345                         S_BlockSound ();
346         }
347 }
348
349 static void VID_ProcessPendingAsyncEvents (void)
350 {
351         // Collapsed / expanded
352         if (AsyncEvent_Collapsed != vid_hidden)
353         {
354                 vid_hidden = !vid_hidden;
355                 VID_AppFocusChanged(!vid_hidden);
356         }
357
358         // Closed
359         if (AsyncEvent_Quitting)
360                 Sys_Quit();
361 }
362
363 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen)
364 {
365         *attrib++ = AGL_RGBA;
366         *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
367         *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
368         *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
369         *attrib++ = AGL_DOUBLEBUFFER;
370         *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
371
372         // if stencil is enabled, ask for alpha too
373         if (stencil)
374         {
375                 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
376                 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
377         }
378         if (fullscreen)
379                 *attrib++ = AGL_FULLSCREEN;
380         *attrib++ = AGL_NONE;
381 }
382
383 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
384 {
385     const EventTypeSpec winEvents[] =
386         {
387                 { kEventClassWindow, kEventWindowClosed },
388                 { kEventClassWindow, kEventWindowCollapsing },
389                 { kEventClassWindow, kEventWindowExpanded },
390         };
391         OSStatus carbonError;
392         Rect windowBounds;
393         CFStringRef windowTitle;
394         AGLPixelFormat pixelFormat;
395         GLint attributes [32];
396         GLenum error;
397
398         if (!GL_OpenLibrary())
399         {
400                 Con_Printf("Unable to load GL driver\n");
401                 return false;
402         }
403
404         if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
405          || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
406          || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
407          || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
408          || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
409          || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
410          || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
411          || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
412          || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
413          || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
414          || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
415         )
416         {
417                 Con_Printf("AGL functions not found\n");
418                 ReleaseWindow(window);
419                 return false;
420         }
421
422         // Ignore the events from the previous window
423         AsyncEvent_Quitting = false;
424         AsyncEvent_Collapsed = false;
425
426         // Create the window, a bit towards the center of the screen
427         windowBounds.left = 100;
428         windowBounds.top = 100;
429         windowBounds.right = width + 100;
430         windowBounds.bottom = height + 100;
431         carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
432         if (carbonError != noErr || window == NULL)
433         {
434                 Con_Printf("Unable to create window (error %d)\n", carbonError);
435                 return false;
436         }
437
438         // Set the window title
439         windowTitle = CFSTR("DarkPlaces AGL");
440         SetWindowTitleWithCFString(window, windowTitle);
441
442         // Install the callback function for the window events we can't get
443         // through ReceiveNextEvent (i.e. close, collapse, and expand)
444         InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
445                                                            GetEventTypeCount(winEvents), winEvents, window, NULL);
446
447         // Create the desired attribute list
448         VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
449
450         if (!fullscreen)
451         {
452                 // Output to Window
453                 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
454                 error = qaglGetError();
455                 if (error != AGL_NO_ERROR)
456                 {
457                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
458                                         (char *)qaglErrorString(error));
459                         ReleaseWindow(window);
460                         return false;
461                 }
462         }
463         else  // Output is fullScreen
464         {
465                 CGDirectDisplayID mainDisplay;
466                 CFDictionaryRef refDisplayMode;
467                 GDHandle gdhDisplay;
468
469                 // Get the mainDisplay and set resolution to current
470                 mainDisplay = CGMainDisplayID();
471                 CGDisplayCapture(mainDisplay);
472
473                 // TOCHECK: not sure whether or not it's necessary to change the resolution
474                 // "by hand", or if aglSetFullscreen does the job anyway
475                 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
476                 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
477                 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
478
479                 // Set pixel format with built attribs
480                 // Note: specifying a device is *required* for AGL_FullScreen
481                 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
482                 error = qaglGetError();
483                 if (error != AGL_NO_ERROR)
484                 {
485                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
486                                                 (char *)qaglErrorString(error));
487                         ReleaseWindow(window);
488                         return false;
489                 }
490         }
491
492         // Create a context using the pform
493         context = qaglCreateContext(pixelFormat, NULL);
494         error = qaglGetError();
495         if (error != AGL_NO_ERROR)
496         {
497                 Con_Printf("qaglCreateContext FAILED: %s\n",
498                                         (char *)qaglErrorString(error));
499         }
500
501         // Make the context the current one ('enable' it)
502         qaglSetCurrentContext(context);
503         error = qaglGetError();
504         if (error != AGL_NO_ERROR)
505         {
506                 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
507                                         (char *)qaglErrorString(error));
508                 ReleaseWindow(window);
509                 return false;
510         }
511
512         // Discard pform
513         qaglDestroyPixelFormat(pixelFormat);
514
515         // Attempt fullscreen if requested
516         if (fullscreen)
517         {
518                 qaglSetFullScreen (context, width, height, refreshrate, 0);
519                 error = qaglGetError();
520                 if (error != AGL_NO_ERROR)
521                 {
522                         Con_Printf("qaglSetFullScreen FAILED: %s\n",
523                                                 (char *)qaglErrorString(error));
524                         return false;
525                 }
526         }
527         else
528         {
529                 // Set Window as Drawable
530                 qaglSetDrawable(context, GetWindowPort(window));
531                 error = qaglGetError();
532                 if (error != AGL_NO_ERROR)
533                 {
534                         Con_Printf("qaglSetDrawable FAILED: %s\n",
535                                                 (char *)qaglErrorString(error));
536                         ReleaseWindow(window);
537                         return false;
538                 }
539         }
540
541         scr_width = width;
542         scr_height = height;
543
544         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
545                 Sys_Error("glGetString not found in %s", gl_driver);
546
547         gl_renderer = (const char *)qglGetString(GL_RENDERER);
548         gl_vendor = (const char *)qglGetString(GL_VENDOR);
549         gl_version = (const char *)qglGetString(GL_VERSION);
550         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
551         gl_platform = "AGL";
552         gl_videosyncavailable = true;
553
554         vid_isfullscreen = fullscreen;
555         vid_usingmouse = false;
556         vid_hidden = false;
557         vid_activewindow = true;
558         sound_active = true;
559         GL_Init();
560
561         SelectWindow(window);
562         ShowWindow(window);
563
564         return true;
565 }
566
567 static void Handle_KeyMod(UInt32 keymod)
568 {
569         const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
570         {
571                 { cmdKey,                                               K_AUX1 },
572                 { shiftKey,                                             K_SHIFT },
573                 { alphaLock,                                    K_CAPSLOCK },
574                 { optionKey,                                    K_ALT },
575                 { controlKey,                                   K_CTRL },
576                 { kEventKeyModifierNumLockMask, K_NUMLOCK },
577                 { kEventKeyModifierFnMask,              K_AUX2 }
578         };
579         static UInt32 prev_keymod = 0;
580         unsigned int i;
581         UInt32 modChanges;
582
583         modChanges = prev_keymod ^ keymod;
584         if (modChanges == 0)
585                 return;
586
587         for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
588         {
589                 UInt32 keybit = keymod_events[i].keybit;
590
591                 if ((modChanges & keybit) != 0)
592                         Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
593         }
594
595         prev_keymod = keymod;
596 }
597
598 static void Handle_Key(unsigned char charcode, qboolean keypressed)
599 {
600         unsigned int keycode = 0;
601         char ascii = '\0';
602
603         switch (charcode)
604         {
605                 case kHomeCharCode:
606                         keycode = K_HOME;
607                         break;
608                 case kEnterCharCode:
609                         keycode = K_KP_ENTER;
610                         break;
611                 case kEndCharCode:
612                         keycode = K_END;
613                         break;
614                 case kBackspaceCharCode:
615                         keycode = K_BACKSPACE;
616                         break;
617                 case kTabCharCode:
618                         keycode = K_TAB;
619                         break;
620                 case kPageUpCharCode:
621                         keycode = K_PGUP;
622                         break;
623                 case kPageDownCharCode:
624                         keycode = K_PGDN;
625                         break;
626                 case kReturnCharCode:
627                         keycode = K_ENTER;
628                         break;
629                 case kEscapeCharCode:
630                         keycode = K_ESCAPE;
631                         break;
632                 case kLeftArrowCharCode:
633                         keycode = K_LEFTARROW;
634                         break;
635                 case kRightArrowCharCode:
636                         keycode = K_RIGHTARROW;
637                         break;
638                 case kUpArrowCharCode:
639                         keycode = K_UPARROW;
640                         break;
641                 case kDownArrowCharCode :
642                         keycode = K_DOWNARROW;
643                         break;
644                 case kDeleteCharCode:
645                         keycode = K_DEL;
646                         break;
647                 case 0:
648                 case 191:
649                         // characters 0 and 191 are sent by the mouse buttons (?!)
650                         break;
651                 default:
652                         if ('A' <= charcode && charcode <= 'Z')
653                         {
654                                 keycode = charcode + ('a' - 'A');  // lowercase it
655                                 ascii = charcode;
656                         }
657                         else if (charcode >= 32)
658                         {
659                                 keycode = charcode;
660                                 ascii = charcode;
661                         }
662                         else
663                                 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
664         }
665
666         if (keycode != 0)
667                 Key_Event(keycode, ascii, keypressed);
668 }
669
670 void Sys_SendKeyEvents(void)
671 {
672         EventRef theEvent;
673         EventTargetRef theTarget;
674
675         // Start by processing the asynchronous events we received since the previous frame
676         VID_ProcessPendingAsyncEvents();
677
678         theTarget = GetEventDispatcherTarget();
679         while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
680         {
681                 UInt32 eventClass = GetEventClass(theEvent);
682                 UInt32 eventKind = GetEventKind(theEvent);
683
684                 switch (eventClass)
685                 {
686                         case kEventClassMouse:
687                         {
688                                 EventMouseButton theButton;
689                                 int key;
690
691                                 switch (eventKind)
692                                 {
693                                         case kEventMouseDown:
694                                         case kEventMouseUp:
695                                                 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
696                                                 switch (theButton)
697                                                 {
698                                                         default:
699                                                         case kEventMouseButtonPrimary:
700                                                                 key = K_MOUSE1;
701                                                                 break;
702                                                         case kEventMouseButtonSecondary:
703                                                                 key = K_MOUSE2;
704                                                                 break;
705                                                         case kEventMouseButtonTertiary:
706                                                                 key = K_MOUSE3;
707                                                                 break;
708                                                 }
709                                                 Key_Event(key, '\0', eventKind == kEventMouseDown);
710                                                 break;
711
712                                         // Note: These two events are mutual exclusives
713                                         // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
714                                         case kEventMouseMoved:
715                                         case kEventMouseDragged:
716                                         {
717                                                 HIPoint deltaPos;
718
719                                                 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
720
721                                                 mouse_x += deltaPos.x;
722                                                 mouse_y += deltaPos.y;
723                                                 break;
724                                         }
725
726                                         case kEventMouseWheelMoved:
727                                         {
728                                                 SInt32 delta;
729                                                 unsigned int wheelEvent;
730
731                                                 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
732
733                                                 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
734                                                 Key_Event(wheelEvent, 0, true);
735                                                 Key_Event(wheelEvent, 0, false);
736                                                 break;
737                                         }
738
739                                         default:
740                                                 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
741                                                 break;
742                                 }
743                         }
744
745                         case kEventClassKeyboard:
746                         {
747                                 char keycode;
748
749                                 switch (eventKind)
750                                 {
751                                         case kEventRawKeyDown:
752                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
753                                                 Handle_Key(keycode, true);
754                                                 break;
755
756                                         case kEventRawKeyRepeat:
757                                                 break;
758
759                                         case kEventRawKeyUp:
760                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
761                                                 Handle_Key(keycode, false);
762                                                 break;
763
764                                         case kEventRawKeyModifiersChanged:
765                                         {
766                                                 UInt32 keymod = 0;
767                                                 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
768                                                 Handle_KeyMod(keymod);
769                                                 break;
770                                         }
771
772                                         case kEventHotKeyPressed:
773                                                 break;
774
775                                         case kEventHotKeyReleased:
776                                                 break;
777
778                                         case kEventMouseWheelMoved:
779                                                 break;
780
781                                         default:
782                                                 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
783                                                 break;
784                                 }
785                                 break;
786                         }
787
788                         case kEventClassTextInput:
789                                 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
790                                 break;
791
792                         case kEventClassApplication:
793                                 switch (eventKind)
794                                 {
795                                         case kEventAppActivated :
796                                                 VID_AppFocusChanged(true);
797                                                 break;
798                                         case kEventAppDeactivated:
799                                                 VID_AppFocusChanged(false);
800                                                 break;
801                                         case kEventAppQuit:
802                                                 Sys_Quit();
803                                                 break;
804                                         case kEventAppActiveWindowChanged:
805                                                 break;
806                                         default:
807                                                 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
808                                                 break;
809                                 }
810                                 break;
811
812                         case kEventClassAppleEvent:
813                                 switch (eventKind)
814                                 {
815                                         case kEventAppleEvent :
816                                                 break;
817                                         default:
818                                                 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
819                                                 break;
820                                 }
821                                 break;
822
823                         case kEventClassWindow:
824                                 switch (eventKind)
825                                 {
826                                         case kEventWindowUpdate :
827                                                 break;
828                                         default:
829                                                 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
830                                                 break;
831                                 }
832                                 break;
833
834                         case kEventClassControl:
835                                 break;
836
837                         default:
838                                 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
839                                                         eventClass >> 24, (eventClass >> 16) & 0xFF,
840                                                         (eventClass >> 8) & 0xFF, eventClass & 0xFF,
841                                                         eventKind);*/
842                                 break;
843                 }
844
845                 SendEventToEventTarget (theEvent, theTarget);
846                 ReleaseEvent(theEvent);
847         }
848 }
849
850 void IN_Move (void)
851 {
852         if (mouse_avail)
853         {
854                 in_mouse_x = mouse_x;
855                 in_mouse_y = mouse_y;
856         }
857         mouse_x = 0;
858         mouse_y = 0;
859 }