]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_glx.c
unicode character input handling in the GLX client
[divverent/darkplaces.git] / vid_glx.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19
20 #include <signal.h>
21
22 #include <dlfcn.h>
23
24 #include <X11/Xlib.h>
25 #include <X11/Xutil.h>
26 #include <X11/Xatom.h>
27 #include <X11/XKBlib.h> // TODO possibly ifdef this out on non-supporting systems... Solaris (as always)?
28 #include <GL/glx.h>
29
30 #include "quakedef.h"
31
32 #include <X11/keysym.h>
33 #include <X11/cursorfont.h>
34 #include <X11/xpm.h>
35
36 #include <X11/extensions/XShm.h>
37 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
38 #include <X11/extensions/xf86dga.h>
39 #endif
40 #include <X11/extensions/xf86vmode.h>
41
42 // get the Uchar type
43 #include "utf8lib.h"
44
45 #include "nexuiz.xpm"
46 #include "darkplaces.xpm"
47
48 // Tell startup code that we have a client
49 int cl_available = true;
50
51 // note: if we used the XRandR extension we could support refresh rates
52 qboolean vid_supportrefreshrate = false;
53
54 //GLX prototypes
55 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
56 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
57 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
58 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
59 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
60 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
61
62 //GLX_ARB_get_proc_address
63 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
64
65 static dllfunction_t getprocaddressfuncs[] =
66 {
67         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
68         {NULL, NULL}
69 };
70
71 //GLX_SGI_swap_control
72 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
73
74 static dllfunction_t swapcontrolfuncs[] =
75 {
76         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
77         {NULL, NULL}
78 };
79
80 static Display *vidx11_display = NULL;
81 static int vidx11_screen;
82 static Window win, root;
83 static GLXContext ctx = NULL;
84
85 Atom wm_delete_window_atom;
86 Atom net_wm_state_atom;
87 Atom net_wm_state_hidden_atom;
88 Atom net_wm_state_fullscreen_atom;
89
90 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
91 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
92                     PointerMotionMask | ButtonMotionMask)
93 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
94                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
95                 LeaveWindowMask)
96
97
98 static qboolean mouse_avail = true;
99 static qboolean vid_usingmousegrab = false;
100 static qboolean vid_usingmouse = false;
101 static qboolean vid_usinghidecursor = false;
102 static qboolean vid_usingvsync = false;
103 static qboolean vid_usevsync = false;
104 static qboolean vid_x11_hardwaregammasupported = false;
105 static qboolean vid_x11_dgasupported = false;
106 static int vid_x11_gammarampsize = 0;
107
108 #if !defined(__APPLE__) && !defined(SUNOS)
109 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "0", "make use of DGA mouse input"};
110 static qboolean vid_usingdgamouse = false;
111 #endif
112 cvar_t vid_netwmfullscreen = {CVAR_SAVE, "vid_netwmfullscreen", "0", "make use _NET_WM_STATE_FULLSCREEN; turn this off if fullscreen does not work for you"};
113
114 qboolean vidmode_ext = false;
115
116 static int win_x, win_y;
117
118 static XF86VidModeModeInfo init_vidmode, game_vidmode;
119 static qboolean vid_isfullscreen = false;
120 static qboolean vid_isvidmodefullscreen = false;
121 static qboolean vid_isnetwmfullscreen = false;
122 static qboolean vid_isoverrideredirect = false;
123
124 static Visual *vidx11_visual;
125 static Colormap vidx11_colormap;
126
127 /*-----------------------------------------------------------------------*/
128 //
129
130 long keysym2ucs(KeySym keysym);
131 int DP_Xutf8LookupString(XKeyEvent * ev,
132                          Uchar *uch,
133                          KeySym * keysym_return,
134                          Status * status_return)
135 {
136         int rc;
137         KeySym keysym;
138         int codepoint;
139         int len;
140         char buffer[64];
141         int nbytes = sizeof(buffer);
142
143         rc = XLookupString(ev, buffer, nbytes, &keysym, NULL);
144
145         if (rc > 0) {
146                 codepoint = buffer[0] & 0xFF;
147         } else {
148                 codepoint = keysym2ucs(keysym);
149         }
150
151         if (codepoint < 0) {
152                 if (keysym == None) {
153                         *status_return = XLookupNone;
154                 } else {
155                         *status_return = XLookupKeySym;
156                         *keysym_return = keysym;
157                 }
158                 return 0;
159         }
160
161         *uch = codepoint;
162
163         if (keysym != None) {
164                 *keysym_return = keysym;
165                 *status_return = XLookupBoth;
166         } else {
167                 *status_return = XLookupChars;
168         }
169         return len;
170 }
171 static int XLateKey(XKeyEvent *ev, Uchar *ascii)
172 {
173         int key = 0;
174         //char buf[64];
175         KeySym keysym, shifted;
176         Status status;
177
178         keysym = XLookupKeysym (ev, 0);
179         DP_Xutf8LookupString(ev, ascii, &shifted, &status);
180
181         switch(keysym)
182         {
183                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
184                 case XK_Page_Up:         key = K_PGUP; break;
185
186                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
187                 case XK_Page_Down:       key = K_PGDN; break;
188
189                 case XK_KP_Home: key = K_KP_HOME; break;
190                 case XK_Home:    key = K_HOME; break;
191
192                 case XK_KP_End:  key = K_KP_END; break;
193                 case XK_End:     key = K_END; break;
194
195                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
196                 case XK_Left:    key = K_LEFTARROW; break;
197
198                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
199                 case XK_Right:  key = K_RIGHTARROW;             break;
200
201                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
202                 case XK_Down:    key = K_DOWNARROW; break;
203
204                 case XK_KP_Up:   key = K_KP_UPARROW; break;
205                 case XK_Up:              key = K_UPARROW;        break;
206
207                 case XK_Escape: key = K_ESCAPE;         break;
208
209                 case XK_KP_Enter: key = K_KP_ENTER;     break;
210                 case XK_Return: key = K_ENTER;           break;
211
212                 case XK_Tab:            key = K_TAB;                     break;
213
214                 case XK_F1:              key = K_F1;                            break;
215
216                 case XK_F2:              key = K_F2;                            break;
217
218                 case XK_F3:              key = K_F3;                            break;
219
220                 case XK_F4:              key = K_F4;                            break;
221
222                 case XK_F5:              key = K_F5;                            break;
223
224                 case XK_F6:              key = K_F6;                            break;
225
226                 case XK_F7:              key = K_F7;                            break;
227
228                 case XK_F8:              key = K_F8;                            break;
229
230                 case XK_F9:              key = K_F9;                            break;
231
232                 case XK_F10:            key = K_F10;                     break;
233
234                 case XK_F11:            key = K_F11;                     break;
235
236                 case XK_F12:            key = K_F12;                     break;
237
238                 case XK_BackSpace: key = K_BACKSPACE; break;
239
240                 case XK_KP_Delete: key = K_KP_DEL; break;
241                 case XK_Delete: key = K_DEL; break;
242
243                 case XK_Pause:  key = K_PAUSE;           break;
244
245                 case XK_Shift_L:
246                 case XK_Shift_R:        key = K_SHIFT;          break;
247
248                 case XK_Execute:
249                 case XK_Control_L:
250                 case XK_Control_R:      key = K_CTRL;            break;
251
252                 case XK_Alt_L:
253                 case XK_Meta_L:
254                 case XK_ISO_Level3_Shift:
255                 case XK_Alt_R:
256                 case XK_Meta_R: key = K_ALT;                    break;
257
258                 case XK_KP_Begin: key = K_KP_5; break;
259
260                 case XK_Insert:key = K_INS; break;
261                 case XK_KP_Insert: key = K_KP_INS; break;
262
263                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
264                 case XK_KP_Add:  key = K_KP_PLUS; break;
265                 case XK_KP_Subtract: key = K_KP_MINUS; break;
266                 case XK_KP_Divide: key = K_KP_SLASH; break;
267
268                 case XK_section:        key = '~'; break;
269
270                 default:
271                         if (keysym < 32)
272                                 break;
273
274                         if (keysym >= 'A' && keysym <= 'Z')
275                                 key = keysym - 'A' + 'a';
276                         else
277                                 key = keysym;
278
279                         break;
280         }
281
282         return key;
283 }
284
285 static Cursor CreateNullCursor(Display *display, Window root)
286 {
287         Pixmap cursormask;
288         XGCValues xgc;
289         GC gc;
290         XColor dummycolour;
291         Cursor cursor;
292
293         cursormask = XCreatePixmap(display, root, 1, 1, 1);
294         xgc.function = GXclear;
295         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
296         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
297         dummycolour.pixel = 0;
298         dummycolour.red = 0;
299         dummycolour.flags = 04;
300         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
301         XFreePixmap(display,cursormask);
302         XFreeGC(display,gc);
303         return cursor;
304 }
305
306 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
307 {
308         static int originalmouseparms_num;
309         static int originalmouseparms_denom;
310         static int originalmouseparms_threshold;
311         static qboolean restore_spi;
312
313 #if !defined(__APPLE__) && !defined(SUNOS)
314         qboolean usedgamouse;
315 #endif
316
317         if (!vidx11_display || !win)
318                 return;
319
320         if (relative)
321                 fullscreengrab = true;
322
323         if (!mouse_avail)
324                 fullscreengrab = relative = hidecursor = false;
325
326 #if !defined(__APPLE__) && !defined(SUNOS)
327         usedgamouse = relative && vid_dgamouse.integer;
328         if (!vid_x11_dgasupported)
329                 usedgamouse = false;
330         if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
331                 VID_SetMouse(false, false, false); // ungrab first!
332 #endif
333
334         if (vid_usingmousegrab != fullscreengrab)
335         {
336                 vid_usingmousegrab = fullscreengrab;
337                 cl_ignoremousemoves = 2;
338                 if (fullscreengrab)
339                 {
340                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
341                         if (vid_grabkeyboard.integer || vid_isoverrideredirect)
342                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
343                 }
344                 else
345                 {
346                         XUngrabPointer(vidx11_display, CurrentTime);
347                         XUngrabKeyboard(vidx11_display, CurrentTime);
348                 }
349         }
350
351         if (relative)
352         {
353                 if (!vid_usingmouse)
354                 {
355                         XWindowAttributes attribs_1;
356                         XSetWindowAttributes attribs_2;
357
358                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
359                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
360                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
361
362 #if !defined(__APPLE__) && !defined(SUNOS)
363                         vid_usingdgamouse = usedgamouse;
364                         if (usedgamouse)
365                         {
366                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
367                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
368                         }
369                         else
370 #endif
371                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
372
373 // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only)
374 #if !defined(__APPLE__) && !defined(SUNOS)
375                         if (!COM_CheckParm ("-noforcemparms") && !usedgamouse)
376 #else
377                         if (!COM_CheckParm ("-noforcemparms"))
378 #endif
379                         {
380                                 XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold);
381                                 XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment
382                                 restore_spi = true;
383                         }
384                         else
385                                 restore_spi = false;
386
387                         cl_ignoremousemoves = 2;
388                         vid_usingmouse = true;
389                 }
390         }
391         else
392         {
393                 if (vid_usingmouse)
394                 {
395 #if !defined(__APPLE__) && !defined(SUNOS)
396                         if (vid_usingdgamouse)
397                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
398                         vid_usingdgamouse = false;
399 #endif
400                         cl_ignoremousemoves = 2;
401
402                         if (restore_spi)
403                                 XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold);
404                         restore_spi = false;
405
406                         vid_usingmouse = false;
407                 }
408         }
409
410         if (vid_usinghidecursor != hidecursor)
411         {
412                 vid_usinghidecursor = hidecursor;
413                 if (hidecursor)
414                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
415                 else
416                         XUndefineCursor(vidx11_display, win);
417         }
418 }
419
420 static keynum_t buttonremap[18] =
421 {
422         K_MOUSE1,
423         K_MOUSE3,
424         K_MOUSE2,
425         K_MWHEELUP,
426         K_MWHEELDOWN,
427         K_MOUSE4,
428         K_MOUSE5,
429         K_MOUSE6,
430         K_MOUSE7,
431         K_MOUSE8,
432         K_MOUSE9,
433         K_MOUSE10,
434         K_MOUSE11,
435         K_MOUSE12,
436         K_MOUSE13,
437         K_MOUSE14,
438         K_MOUSE15,
439         K_MOUSE16,
440 };
441
442 static void HandleEvents(void)
443 {
444         XEvent event;
445         int key;
446         Uchar unicode;
447         qboolean dowarp = false;
448
449         if (!vidx11_display)
450                 return;
451
452         while (XPending(vidx11_display))
453         {
454                 XNextEvent(vidx11_display, &event);
455
456                 switch (event.type)
457                 {
458                 case KeyPress:
459                         // key pressed
460                         key = XLateKey (&event.xkey, &unicode);
461                         Key_Event(key, unicode, true);
462                         break;
463
464                 case KeyRelease:
465                         // key released
466                         key = XLateKey (&event.xkey, &unicode);
467                         Key_Event(key, unicode, false);
468                         break;
469
470                 case MotionNotify:
471                         // mouse moved
472                         if (vid_usingmouse)
473                         {
474 #if !defined(__APPLE__) && !defined(SUNOS)
475                                 if (vid_usingdgamouse)
476                                 {
477                                         in_mouse_x += event.xmotion.x_root;
478                                         in_mouse_y += event.xmotion.y_root;
479                                 }
480                                 else
481 #endif
482                                 {
483                                         if (!event.xmotion.send_event)
484                                         {
485                                                 in_mouse_x += event.xmotion.x - in_windowmouse_x;
486                                                 in_mouse_y += event.xmotion.y - in_windowmouse_y;
487                                                 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
488                                                 if (vid_stick_mouse.integer || abs(vid.width/2 - event.xmotion.x) > vid.width / 4 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4)
489                                                         dowarp = true;
490                                         }
491                                 }
492                         }
493                         in_windowmouse_x = event.xmotion.x;
494                         in_windowmouse_y = event.xmotion.y;
495                         break;
496
497                 case ButtonPress:
498                         // mouse button pressed
499                         if (event.xbutton.button <= 18)
500                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
501                         else
502                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
503                         break;
504
505                 case ButtonRelease:
506                         // mouse button released
507                         if (event.xbutton.button <= 18)
508                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
509                         else
510                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
511                         break;
512
513                 case CreateNotify:
514                         // window created
515                         win_x = event.xcreatewindow.x;
516                         win_y = event.xcreatewindow.y;
517                         break;
518
519                 case ConfigureNotify:
520                         // window changed size/location
521                         win_x = event.xconfigure.x;
522                         win_y = event.xconfigure.y;
523                         if(vid_resizable.integer < 2 || vid_isnetwmfullscreen)
524                         {
525                                 vid.width = event.xconfigure.width;
526                                 vid.height = event.xconfigure.height;
527                                 if(vid_isnetwmfullscreen)
528                                         Con_Printf("NetWM fullscreen: actually using resolution %dx%d\n", vid.width, vid.height);
529                                 else
530                                         Con_DPrintf("Updating to ConfigureNotify resolution %dx%d\n", vid.width, vid.height);
531                         }
532                         break;
533                 case DestroyNotify:
534                         // window has been destroyed
535                         Sys_Quit(0);
536                         break;
537                 case ClientMessage:
538                         // window manager messages
539                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
540                                 Sys_Quit(0);
541                         break;
542                 case MapNotify:
543                         if (vid_isoverrideredirect)
544                                 break;
545                         // window restored
546                         vid_hidden = false;
547                         VID_RestoreSystemGamma();
548
549                         if(vid_isvidmodefullscreen)
550                         {
551                                 // set our video mode
552                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &game_vidmode);
553
554                                 // Move the viewport to top left
555                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
556                         }
557
558                         if(vid_isnetwmfullscreen)
559                         {
560                                 // make sure it's fullscreen
561                                 XEvent event;
562                                 event.type = ClientMessage;
563                                 event.xclient.serial = 0;
564                                 event.xclient.send_event = True;
565                                 event.xclient.message_type = net_wm_state_atom;
566                                 event.xclient.window = win;
567                                 event.xclient.format = 32;
568                                 event.xclient.data.l[0] = 1;
569                                 event.xclient.data.l[1] = net_wm_state_fullscreen_atom;
570                                 event.xclient.data.l[2] = 0;
571                                 event.xclient.data.l[3] = 1;
572                                 event.xclient.data.l[4] = 0;
573                                 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
574                         }
575
576                         dowarp = true;
577
578                         break;
579                 case UnmapNotify:
580                         if (vid_isoverrideredirect)
581                                 break;
582                         // window iconified/rolledup/whatever
583                         vid_hidden = true;
584                         VID_RestoreSystemGamma();
585
586                         if(vid_isvidmodefullscreen)
587                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
588
589                         break;
590                 case FocusIn:
591                         if (vid_isoverrideredirect)
592                                 break;
593                         // window is now the input focus
594                         vid_activewindow = true;
595                         break;
596                 case FocusOut:
597                         if (vid_isoverrideredirect)
598                                 break;
599
600                         if(vid_isnetwmfullscreen && event.xfocus.mode == NotifyNormal)
601                         {
602                                 // iconify netwm fullscreen window when it loses focus
603                                 // when the user selects it in the taskbar, the window manager will map it again and send MapNotify
604                                 XEvent event;
605                                 event.type = ClientMessage;
606                                 event.xclient.serial = 0;
607                                 event.xclient.send_event = True;
608                                 event.xclient.message_type = net_wm_state_atom;
609                                 event.xclient.window = win;
610                                 event.xclient.format = 32;
611                                 event.xclient.data.l[0] = 1;
612                                 event.xclient.data.l[1] = net_wm_state_hidden_atom;
613                                 event.xclient.data.l[2] = 0;
614                                 event.xclient.data.l[3] = 1;
615                                 event.xclient.data.l[4] = 0;
616                                 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
617                         }
618
619                         // window is no longer the input focus
620                         vid_activewindow = false;
621                         VID_RestoreSystemGamma();
622
623                         break;
624                 case EnterNotify:
625                         // mouse entered window
626                         break;
627                 case LeaveNotify:
628                         // mouse left window
629                         break;
630                 }
631         }
632
633         if (dowarp)
634         {
635                 /* move the mouse to the window center again */
636                 // we'll catch the warp motion by its send_event flag, updating the
637                 // stored mouse position without adding any delta motion
638                 XEvent event;
639                 event.type = MotionNotify;
640                 event.xmotion.display = vidx11_display;
641                 event.xmotion.window = win;
642                 event.xmotion.x = vid.width / 2;
643                 event.xmotion.y = vid.height / 2;
644                 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
645                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
646         }
647 }
648
649 static void *prjobj = NULL;
650
651 static void GL_CloseLibrary(void)
652 {
653         if (prjobj)
654                 dlclose(prjobj);
655         prjobj = NULL;
656         gl_driver[0] = 0;
657         qglXGetProcAddressARB = NULL;
658         gl_extensions = "";
659         gl_platform = "";
660         gl_platformextensions = "";
661 }
662
663 static int GL_OpenLibrary(const char *name)
664 {
665         Con_Printf("Loading OpenGL driver %s\n", name);
666         GL_CloseLibrary();
667         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
668         {
669                 Con_Printf("Unable to open symbol list for %s\n", name);
670                 return false;
671         }
672         strlcpy(gl_driver, name, sizeof(gl_driver));
673         return true;
674 }
675
676 void *GL_GetProcAddress(const char *name)
677 {
678         void *p = NULL;
679         if (qglXGetProcAddressARB != NULL)
680                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
681         if (p == NULL)
682                 p = (void *) dlsym(prjobj, name);
683         return p;
684 }
685
686 void VID_Shutdown(void)
687 {
688         if (!ctx || !vidx11_display)
689                 return;
690
691         VID_SetMouse(false, false, false);
692         VID_RestoreSystemGamma();
693
694         // FIXME: glXDestroyContext here?
695         if (vid_isvidmodefullscreen)
696                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
697         if (win)
698                 XDestroyWindow(vidx11_display, win);
699         XCloseDisplay(vidx11_display);
700
701         vid_hidden = true;
702         vid_isfullscreen = false;
703         vid_isnetwmfullscreen = false;
704         vid_isvidmodefullscreen = false;
705         vid_isoverrideredirect = false;
706         vidx11_display = NULL;
707         win = 0;
708         ctx = NULL;
709
710         GL_CloseLibrary();
711         Key_ClearStates ();
712 }
713
714 void signal_handler(int sig)
715 {
716         Con_Printf("Received signal %d, exiting...\n", sig);
717         VID_RestoreSystemGamma();
718         Sys_Quit(1);
719 }
720
721 void InitSig(void)
722 {
723         signal(SIGHUP, signal_handler);
724         signal(SIGINT, signal_handler);
725         signal(SIGQUIT, signal_handler);
726         signal(SIGILL, signal_handler);
727         signal(SIGTRAP, signal_handler);
728         signal(SIGIOT, signal_handler);
729         signal(SIGBUS, signal_handler);
730         signal(SIGFPE, signal_handler);
731         signal(SIGSEGV, signal_handler);
732         signal(SIGTERM, signal_handler);
733 }
734
735 void VID_Finish (void)
736 {
737         vid_usevsync = vid_vsync.integer && !cls.timedemo && qglXSwapIntervalSGI;
738         if (vid_usingvsync != vid_usevsync)
739         {
740                 vid_usingvsync = vid_usevsync;
741                 if (qglXSwapIntervalSGI (vid_usevsync))
742                         Con_Print("glXSwapIntervalSGI didn't accept the vid_vsync change, it will take effect on next vid_restart (GLX_SGI_swap_control does not allow turning off vsync)\n");
743         }
744
745         if (!vid_hidden)
746         {
747                 CHECKGLERROR
748                 if (r_speeds.integer == 2 || gl_finish.integer)
749                 {
750                         qglFinish();CHECKGLERROR
751                 }
752                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
753         }
754
755         if (vid_x11_hardwaregammasupported)
756                 VID_UpdateGamma(false, vid_x11_gammarampsize);
757 }
758
759 int VID_SetGamma(unsigned short *ramps, int rampsize)
760 {
761         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
762 }
763
764 int VID_GetGamma(unsigned short *ramps, int rampsize)
765 {
766         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
767 }
768
769 void VID_Init(void)
770 {
771 #if !defined(__APPLE__) && !defined(SUNOS)
772         Cvar_RegisterVariable (&vid_dgamouse);
773 #endif
774         Cvar_RegisterVariable (&vid_netwmfullscreen);
775         InitSig(); // trap evil signals
776 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
777         if (COM_CheckParm ("-nomouse"))
778                 mouse_avail = false;
779 }
780
781 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
782 {
783         *attrib++ = GLX_RGBA;
784         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
785         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
786         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
787         *attrib++ = GLX_DOUBLEBUFFER;
788         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
789         // if stencil is enabled, ask for alpha too
790         if (stencil)
791         {
792                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
793                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
794         }
795         if (stereobuffer)
796                 *attrib++ = GLX_STEREO;
797         if (samples > 1)
798         {
799                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
800                 *attrib++ = 1;
801                 *attrib++ = GLX_SAMPLES_ARB;
802                 *attrib++ = samples;
803         }
804         *attrib++ = None;
805 }
806
807 qboolean VID_InitMode(viddef_mode_t *mode)
808 {
809         int i;
810         int attrib[32];
811         XSetWindowAttributes attr;
812         XClassHint *clshints;
813         XWMHints *wmhints;
814         XSizeHints *szhints;
815         unsigned long mask;
816         XVisualInfo *visinfo;
817         int MajorVersion, MinorVersion;
818         const char *drivername;
819
820         vid_isfullscreen = false;
821         vid_isnetwmfullscreen = false;
822         vid_isvidmodefullscreen = false;
823         vid_isoverrideredirect = false;
824
825 #if defined(__APPLE__) && defined(__MACH__)
826         drivername = "/usr/X11R6/lib/libGL.1.dylib";
827 #else
828         drivername = "libGL.so.1";
829 #endif
830 // COMMANDLINEOPTION: Linux GLX: -gl_driver <drivername> selects a GL driver library, default is libGL.so.1, useful only for using fxmesa or similar, if you don't know what this is for, you don't need it
831 // COMMANDLINEOPTION: BSD GLX: -gl_driver <drivername> selects a GL driver library, default is libGL.so.1, useful only for using fxmesa or similar, if you don't know what this is for, you don't need it
832 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
833         i = COM_CheckParm("-gl_driver");
834         if (i && i < com_argc - 1)
835                 drivername = com_argv[i + 1];
836         if (!GL_OpenLibrary(drivername))
837         {
838                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
839                 return false;
840         }
841
842         if (!(vidx11_display = XOpenDisplay(NULL)))
843         {
844                 Con_Print("Couldn't open the X display\n");
845                 return false;
846         }
847
848         // LordHavoc: making the close button on a window do the right thing
849         // seems to involve this mess, sigh...
850         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
851         net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
852         net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
853         net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
854
855         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
856         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
857
858         vidx11_screen = DefaultScreen(vidx11_display);
859         root = RootWindow(vidx11_display, vidx11_screen);
860
861         // Get video mode list
862         MajorVersion = MinorVersion = 0;
863         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
864                 vidmode_ext = false;
865         else
866         {
867                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
868                 vidmode_ext = true;
869         }
870
871         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
872          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
873          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
874          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
875          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
876          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
877         {
878                 Con_Printf("glX functions not found in %s\n", gl_driver);
879                 return false;
880         }
881
882         VID_BuildGLXAttrib(attrib, mode->bitsperpixel == 32, mode->stereobuffer, mode->samples);
883         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
884         if (!visinfo)
885         {
886                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
887                 return false;
888         }
889
890         if (mode->fullscreen)
891         {
892                 if(vid_netwmfullscreen.integer)
893                 {
894                         // TODO detect WM support
895                         vid_isnetwmfullscreen = true;
896                         vid_isfullscreen = true;
897                         // width and height will be filled in later
898                         Con_DPrintf("Using NetWM fullscreen mode\n");
899                 }
900
901                 if(!vid_isfullscreen && vidmode_ext)
902                 {
903                         int best_fit, best_dist, dist, x, y;
904
905                         // Are we going fullscreen?  If so, let's change video mode
906                         XF86VidModeModeLine *current_vidmode;
907                         XF86VidModeModeInfo **vidmodes;
908                         int num_vidmodes;
909
910                         // This nice hack comes from the SDL source code
911                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
912                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
913
914                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
915                         best_dist = 0;
916                         best_fit = -1;
917
918                         for (i = 0; i < num_vidmodes; i++)
919                         {
920                                 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
921                                         continue;
922
923                                 x = mode->width - vidmodes[i]->hdisplay;
924                                 y = mode->height - vidmodes[i]->vdisplay;
925                                 dist = (x * x) + (y * y);
926                                 if (best_fit == -1 || dist < best_dist)
927                                 {
928                                         best_dist = dist;
929                                         best_fit = i;
930                                 }
931                         }
932
933                         if (best_fit != -1)
934                         {
935                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
936                                 // to width/height =, so the window will take the full area of
937                                 // the mode chosen
938                                 mode->width = vidmodes[best_fit]->hdisplay;
939                                 mode->height = vidmodes[best_fit]->vdisplay;
940
941                                 // change to the mode
942                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
943                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
944                                 vid_isvidmodefullscreen = true;
945                                 vid_isfullscreen = true;
946
947                                 // Move the viewport to top left
948                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
949                                 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
950                         }
951
952                         free(vidmodes);
953                 }
954
955                 if(!vid_isfullscreen)
956                 {
957                         // sorry, no FS available
958                         // use the full desktop resolution
959                         vid_isfullscreen = true;
960                         // width and height will be filled in later
961                         mode->width = DisplayWidth(vidx11_display, vidx11_screen);
962                         mode->height = DisplayHeight(vidx11_display, vidx11_screen);
963                         Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
964                 }
965         }
966
967         // LordHavoc: save the visual for use in gamma ramp settings later
968         vidx11_visual = visinfo->visual;
969
970         /* window attributes */
971         attr.background_pixel = 0;
972         attr.border_pixel = 0;
973         // LordHavoc: save the colormap for later, too
974         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
975         attr.event_mask = X_MASK;
976
977         if (mode->fullscreen)
978         {
979                 if(vid_isnetwmfullscreen)
980                 {
981                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
982                         attr.backing_store = NotUseful;
983                         attr.save_under = False;
984                 }
985                 else
986                 {
987                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
988                         attr.override_redirect = True;
989                         attr.backing_store = NotUseful;
990                         attr.save_under = False;
991                         vid_isoverrideredirect = true; // so it knows to grab
992                 }
993         }
994         else
995         {
996                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
997         }
998
999         win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
1000
1001         wmhints = XAllocWMHints();
1002         if(XpmCreatePixmapFromData(vidx11_display, win,
1003                 (gamemode == GAME_NEXUIZ) ? nexuiz_xpm : darkplaces_xpm,
1004                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1005                 wmhints->flags |= IconPixmapHint | IconMaskHint;
1006
1007         clshints = XAllocClassHint();
1008         clshints->res_name = strdup(gamename);
1009         clshints->res_class = strdup("DarkPlaces");
1010
1011         szhints = XAllocSizeHints();
1012         if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1013         {
1014                 szhints->min_width = szhints->max_width = mode->width;
1015                 szhints->min_height = szhints->max_height = mode->height;
1016                 szhints->flags |= PMinSize | PMaxSize;
1017         }
1018
1019         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1020         XFree(clshints);
1021         XFree(wmhints);
1022         XFree(szhints);
1023
1024         //XStoreName(vidx11_display, win, gamename);
1025         XMapWindow(vidx11_display, win);
1026
1027         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1028
1029         if (vid_isoverrideredirect)
1030         {
1031                 XMoveWindow(vidx11_display, win, 0, 0);
1032                 XRaiseWindow(vidx11_display, win);
1033                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1034                 XFlush(vidx11_display);
1035         }
1036
1037         if(vid_isvidmodefullscreen)
1038         {
1039                 // Move the viewport to top left
1040                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1041         }
1042
1043         //XSync(vidx11_display, False);
1044
1045         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
1046         if (!ctx)
1047         {
1048                 Con_Printf ("glXCreateContext failed\n");
1049                 return false;
1050         }
1051
1052         if (!qglXMakeCurrent(vidx11_display, win, ctx))
1053         {
1054                 Con_Printf ("glXMakeCurrent failed\n");
1055                 return false;
1056         }
1057
1058         XSync(vidx11_display, False);
1059
1060         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1061         {
1062                 Con_Printf ("glGetString not found in %s\n", gl_driver);
1063                 return false;
1064         }
1065
1066         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1067         gl_platform = "GLX";
1068         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
1069
1070 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1071 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1072 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1073         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
1074 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
1075 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
1076 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
1077         GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
1078
1079         vid_usingmousegrab = false;
1080         vid_usingmouse = false;
1081         vid_usinghidecursor = false;
1082         vid_usingvsync = false;
1083         vid_hidden = false;
1084         vid_activewindow = true;
1085         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1086 #if !defined(__APPLE__) && !defined(SUNOS)
1087         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1088         if (!vid_x11_dgasupported)
1089                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1090 #endif
1091
1092         GL_Init();
1093         return true;
1094 }
1095
1096 void Sys_SendKeyEvents(void)
1097 {
1098         static qboolean sound_active = true;
1099
1100         // enable/disable sound on focus gain/loss
1101         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1102         {
1103                 if (!sound_active)
1104                 {
1105                         S_UnblockSound ();
1106                         sound_active = true;
1107                 }
1108         }
1109         else
1110         {
1111                 if (sound_active)
1112                 {
1113                         S_BlockSound ();
1114                         sound_active = false;
1115                 }
1116         }
1117
1118         HandleEvents();
1119 }
1120
1121 void IN_Move (void)
1122 {
1123 }
1124
1125 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1126 {
1127         if(vidmode_ext)
1128         {
1129                 int i, bpp;
1130                 size_t k;
1131                 XF86VidModeModeInfo **vidmodes;
1132                 int num_vidmodes;
1133
1134                 XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1135                 k = 0;
1136                 for (i = 0; i < num_vidmodes; i++)
1137                 {
1138                         if(k >= maxcount)
1139                                 break;
1140                         // we don't get bpp info, so let's just assume all of 8, 15, 16, 24, 32 work
1141                         for(bpp = 8; bpp <= 32; bpp = ((bpp == 8) ? 15 : (bpp & 0xF8) + 8))
1142                         {
1143                                 if(k >= maxcount)
1144                                         break;
1145                                 modes[k].width = vidmodes[i]->hdisplay;
1146                                 modes[k].height = vidmodes[i]->vdisplay;
1147                                 modes[k].bpp = 8;
1148                                 if(vidmodes[i]->dotclock && vidmodes[i]->htotal && vidmodes[i]->vtotal)
1149                                         modes[k].refreshrate = vidmodes[i]->dotclock / vidmodes[i]->htotal / vidmodes[i]->vtotal;
1150                                 else
1151                                         modes[k].refreshrate = 60;
1152                                 modes[k].pixelheight_num = 1;
1153                                 modes[k].pixelheight_denom = 1; // xvidmode does not provide this
1154                                 ++k;
1155                         }
1156                 }
1157                 return k;
1158         }
1159         return 0; // FIXME implement this
1160 }