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