2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
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)?
32 #include <X11/keysym.h>
33 #include <X11/cursorfont.h>
36 #include <X11/extensions/XShm.h>
37 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
38 #include <X11/extensions/xf86dga.h>
40 #include <X11/extensions/xf86vmode.h>
47 #include "darkplaces.xpm"
49 // Tell startup code that we have a client
50 int cl_available = true;
52 // note: if we used the XRandR extension we could support refresh rates
53 qboolean vid_supportrefreshrate = false;
56 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
57 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
58 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
59 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
60 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
61 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
63 //GLX_ARB_get_proc_address
64 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
66 static dllfunction_t getprocaddressfuncs[] =
68 {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
72 //GLX_SGI_swap_control
73 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
75 static dllfunction_t swapcontrolfuncs[] =
77 {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
81 static Display *vidx11_display = NULL;
82 static int vidx11_screen;
83 static Window win, root;
84 static GLXContext ctx = NULL;
86 Atom wm_delete_window_atom;
87 Atom net_wm_state_atom;
88 Atom net_wm_state_hidden_atom;
89 Atom net_wm_state_fullscreen_atom;
93 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
94 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
95 PointerMotionMask | ButtonMotionMask)
96 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
97 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
101 static qboolean mouse_avail = true;
102 static qboolean vid_usingmousegrab = false;
103 static qboolean vid_usingmouse = false;
104 static qboolean vid_usinghidecursor = false;
105 static qboolean vid_usingvsync = false;
106 static qboolean vid_usevsync = false;
107 static qboolean vid_x11_hardwaregammasupported = false;
108 static qboolean vid_x11_dgasupported = false;
109 static int vid_x11_gammarampsize = 0;
111 #if !defined(__APPLE__) && !defined(SUNOS)
112 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "0", "make use of DGA mouse input"};
113 static qboolean vid_usingdgamouse = false;
115 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"};
117 qboolean vidmode_ext = false;
119 static int win_x, win_y;
121 static XF86VidModeModeInfo init_vidmode, game_vidmode;
122 static qboolean vid_isfullscreen = false;
123 static qboolean vid_isvidmodefullscreen = false;
124 static qboolean vid_isnetwmfullscreen = false;
125 static qboolean vid_isoverrideredirect = false;
127 static Visual *vidx11_visual;
128 static Colormap vidx11_colormap;
130 /*-----------------------------------------------------------------------*/
133 long keysym2ucs(KeySym keysym);
134 void DP_Xutf8LookupString(XKeyEvent * ev,
136 KeySym * keysym_return,
137 Status * status_return)
143 int nbytes = sizeof(buffer);
145 rc = XLookupString(ev, buffer, nbytes, &keysym, NULL);
148 codepoint = buffer[0] & 0xFF;
150 codepoint = keysym2ucs(keysym);
154 if (keysym == None) {
155 *status_return = XLookupNone;
157 *status_return = XLookupKeySym;
158 *keysym_return = keysym;
166 if (keysym != None) {
167 *keysym_return = keysym;
168 *status_return = XLookupBoth;
170 *status_return = XLookupChars;
173 static int XLateKey(XKeyEvent *ev, Uchar *ascii)
177 KeySym keysym, shifted;
180 keysym = XLookupKeysym (ev, 0);
181 DP_Xutf8LookupString(ev, ascii, &shifted, &status);
185 case XK_KP_Page_Up: key = K_KP_PGUP; break;
186 case XK_Page_Up: key = K_PGUP; break;
188 case XK_KP_Page_Down: key = K_KP_PGDN; break;
189 case XK_Page_Down: key = K_PGDN; break;
191 case XK_KP_Home: key = K_KP_HOME; break;
192 case XK_Home: key = K_HOME; break;
194 case XK_KP_End: key = K_KP_END; break;
195 case XK_End: key = K_END; break;
197 case XK_KP_Left: key = K_KP_LEFTARROW; break;
198 case XK_Left: key = K_LEFTARROW; break;
200 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
201 case XK_Right: key = K_RIGHTARROW; break;
203 case XK_KP_Down: key = K_KP_DOWNARROW; break;
204 case XK_Down: key = K_DOWNARROW; break;
206 case XK_KP_Up: key = K_KP_UPARROW; break;
207 case XK_Up: key = K_UPARROW; break;
209 case XK_Escape: key = K_ESCAPE; break;
211 case XK_KP_Enter: key = K_KP_ENTER; break;
212 case XK_Return: key = K_ENTER; break;
214 case XK_Tab: key = K_TAB; break;
216 case XK_F1: key = K_F1; break;
218 case XK_F2: key = K_F2; break;
220 case XK_F3: key = K_F3; break;
222 case XK_F4: key = K_F4; break;
224 case XK_F5: key = K_F5; break;
226 case XK_F6: key = K_F6; break;
228 case XK_F7: key = K_F7; break;
230 case XK_F8: key = K_F8; break;
232 case XK_F9: key = K_F9; break;
234 case XK_F10: key = K_F10; break;
236 case XK_F11: key = K_F11; break;
238 case XK_F12: key = K_F12; break;
240 case XK_BackSpace: key = K_BACKSPACE; break;
242 case XK_KP_Delete: key = K_KP_DEL; break;
243 case XK_Delete: key = K_DEL; break;
245 case XK_Pause: key = K_PAUSE; break;
248 case XK_Shift_R: key = K_SHIFT; break;
252 case XK_Control_R: key = K_CTRL; break;
256 case XK_ISO_Level3_Shift:
258 case XK_Meta_R: key = K_ALT; break;
260 case XK_KP_Begin: key = K_KP_5; break;
262 case XK_Insert:key = K_INS; break;
263 case XK_KP_Insert: key = K_KP_INS; break;
265 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
266 case XK_KP_Add: key = K_KP_PLUS; break;
267 case XK_KP_Subtract: key = K_KP_MINUS; break;
268 case XK_KP_Divide: key = K_KP_SLASH; break;
270 case XK_section: key = '~'; break;
276 if (keysym >= 'A' && keysym <= 'Z')
277 key = keysym - 'A' + 'a';
287 static Cursor CreateNullCursor(Display *display, Window root)
295 cursormask = XCreatePixmap(display, root, 1, 1, 1);
296 xgc.function = GXclear;
297 gc = XCreateGC(display, cursormask, GCFunction, &xgc);
298 XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
299 dummycolour.pixel = 0;
301 dummycolour.flags = 04;
302 cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
303 XFreePixmap(display,cursormask);
308 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
310 static int originalmouseparms_num;
311 static int originalmouseparms_denom;
312 static int originalmouseparms_threshold;
313 static qboolean restore_spi;
315 #if !defined(__APPLE__) && !defined(SUNOS)
316 qboolean usedgamouse;
319 if (!vidx11_display || !win)
323 fullscreengrab = true;
326 fullscreengrab = relative = hidecursor = false;
328 #if !defined(__APPLE__) && !defined(SUNOS)
329 usedgamouse = relative && vid_dgamouse.integer;
330 if (!vid_x11_dgasupported)
332 if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
333 VID_SetMouse(false, false, false); // ungrab first!
336 if (vid_usingmousegrab != fullscreengrab)
338 vid_usingmousegrab = fullscreengrab;
339 cl_ignoremousemoves = 2;
342 XGrabPointer(vidx11_display, win, True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
343 if (vid_grabkeyboard.integer || vid_isoverrideredirect)
344 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
348 XUngrabPointer(vidx11_display, CurrentTime);
349 XUngrabKeyboard(vidx11_display, CurrentTime);
357 XWindowAttributes attribs_1;
358 XSetWindowAttributes attribs_2;
360 XGetWindowAttributes(vidx11_display, win, &attribs_1);
361 attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
362 XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
364 #if !defined(__APPLE__) && !defined(SUNOS)
365 vid_usingdgamouse = usedgamouse;
368 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
369 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
373 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
375 // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only)
376 #if !defined(__APPLE__) && !defined(SUNOS)
377 if (!COM_CheckParm ("-noforcemparms") && !usedgamouse)
379 if (!COM_CheckParm ("-noforcemparms"))
382 XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold);
383 XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment
389 cl_ignoremousemoves = 2;
390 vid_usingmouse = true;
397 #if !defined(__APPLE__) && !defined(SUNOS)
398 if (vid_usingdgamouse)
399 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
400 vid_usingdgamouse = false;
402 cl_ignoremousemoves = 2;
405 XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold);
408 vid_usingmouse = false;
412 if (vid_usinghidecursor != hidecursor)
414 vid_usinghidecursor = hidecursor;
416 XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
418 XUndefineCursor(vidx11_display, win);
422 static keynum_t buttonremap[18] =
444 static void HandleEvents(void)
449 qboolean dowarp = false;
454 while (XPending(vidx11_display))
456 XNextEvent(vidx11_display, &event);
462 key = XLateKey (&event.xkey, &unicode);
463 Key_Event(key, unicode, true);
468 key = XLateKey (&event.xkey, &unicode);
469 Key_Event(key, unicode, false);
476 #if !defined(__APPLE__) && !defined(SUNOS)
477 if (vid_usingdgamouse)
479 in_mouse_x += event.xmotion.x_root;
480 in_mouse_y += event.xmotion.y_root;
485 if (!event.xmotion.send_event)
487 in_mouse_x += event.xmotion.x - in_windowmouse_x;
488 in_mouse_y += event.xmotion.y - in_windowmouse_y;
489 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
490 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)
495 in_windowmouse_x = event.xmotion.x;
496 in_windowmouse_y = event.xmotion.y;
500 // mouse button pressed
501 if (event.xbutton.button <= 18)
502 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
504 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
508 // mouse button released
509 if (event.xbutton.button <= 18)
510 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
512 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
517 win_x = event.xcreatewindow.x;
518 win_y = event.xcreatewindow.y;
521 case ConfigureNotify:
522 // window changed size/location
523 win_x = event.xconfigure.x;
524 win_y = event.xconfigure.y;
525 if(vid_resizable.integer < 2 || vid_isnetwmfullscreen)
527 vid.width = event.xconfigure.width;
528 vid.height = event.xconfigure.height;
529 if(vid_isnetwmfullscreen)
530 Con_Printf("NetWM fullscreen: actually using resolution %dx%d\n", vid.width, vid.height);
532 Con_DPrintf("Updating to ConfigureNotify resolution %dx%d\n", vid.width, vid.height);
536 // window has been destroyed
540 // window manager messages
541 if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
545 if (vid_isoverrideredirect)
549 VID_RestoreSystemGamma();
551 if(vid_isvidmodefullscreen)
553 // set our video mode
554 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &game_vidmode);
556 // Move the viewport to top left
557 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
560 if(vid_isnetwmfullscreen)
562 // make sure it's fullscreen
564 event.type = ClientMessage;
565 event.xclient.serial = 0;
566 event.xclient.send_event = True;
567 event.xclient.message_type = net_wm_state_atom;
568 event.xclient.window = win;
569 event.xclient.format = 32;
570 event.xclient.data.l[0] = 1;
571 event.xclient.data.l[1] = net_wm_state_fullscreen_atom;
572 event.xclient.data.l[2] = 0;
573 event.xclient.data.l[3] = 1;
574 event.xclient.data.l[4] = 0;
575 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
582 if (vid_isoverrideredirect)
584 // window iconified/rolledup/whatever
586 VID_RestoreSystemGamma();
588 if(vid_isvidmodefullscreen)
589 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
593 if (vid_isoverrideredirect)
595 // window is now the input focus
596 vid_activewindow = true;
599 if (vid_isoverrideredirect)
602 if(vid_isnetwmfullscreen && event.xfocus.mode == NotifyNormal)
604 // iconify netwm fullscreen window when it loses focus
605 // when the user selects it in the taskbar, the window manager will map it again and send MapNotify
607 event.type = ClientMessage;
608 event.xclient.serial = 0;
609 event.xclient.send_event = True;
610 event.xclient.message_type = net_wm_state_atom;
611 event.xclient.window = win;
612 event.xclient.format = 32;
613 event.xclient.data.l[0] = 1;
614 event.xclient.data.l[1] = net_wm_state_hidden_atom;
615 event.xclient.data.l[2] = 0;
616 event.xclient.data.l[3] = 1;
617 event.xclient.data.l[4] = 0;
618 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
621 // window is no longer the input focus
622 vid_activewindow = false;
623 VID_RestoreSystemGamma();
627 // mouse entered window
637 /* move the mouse to the window center again */
638 // we'll catch the warp motion by its send_event flag, updating the
639 // stored mouse position without adding any delta motion
641 event.type = MotionNotify;
642 event.xmotion.display = vidx11_display;
643 event.xmotion.window = win;
644 event.xmotion.x = vid.width / 2;
645 event.xmotion.y = vid.height / 2;
646 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
647 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
651 static void *prjobj = NULL;
653 static void GL_CloseLibrary(void)
659 qglXGetProcAddressARB = NULL;
662 gl_platformextensions = "";
665 static int GL_OpenLibrary(const char *name)
667 Con_Printf("Loading OpenGL driver %s\n", name);
669 if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
671 Con_Printf("Unable to open symbol list for %s\n", name);
674 strlcpy(gl_driver, name, sizeof(gl_driver));
678 void *GL_GetProcAddress(const char *name)
681 if (qglXGetProcAddressARB != NULL)
682 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
684 p = (void *) dlsym(prjobj, name);
688 void VID_Shutdown(void)
690 if (!ctx || !vidx11_display)
693 VID_SetMouse(false, false, false);
694 VID_RestoreSystemGamma();
696 // FIXME: glXDestroyContext here?
697 if (vid_isvidmodefullscreen)
698 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
700 XDestroyWindow(vidx11_display, win);
701 XCloseDisplay(vidx11_display);
704 vid_isfullscreen = false;
705 vid_isnetwmfullscreen = false;
706 vid_isvidmodefullscreen = false;
707 vid_isoverrideredirect = false;
708 vidx11_display = NULL;
716 void signal_handler(int sig)
718 Con_Printf("Received signal %d, exiting...\n", sig);
719 VID_RestoreSystemGamma();
725 signal(SIGHUP, signal_handler);
726 signal(SIGINT, signal_handler);
727 signal(SIGQUIT, signal_handler);
728 signal(SIGILL, signal_handler);
729 signal(SIGTRAP, signal_handler);
730 signal(SIGIOT, signal_handler);
731 signal(SIGBUS, signal_handler);
732 signal(SIGFPE, signal_handler);
733 signal(SIGSEGV, signal_handler);
734 signal(SIGTERM, signal_handler);
737 void VID_Finish (void)
739 vid_usevsync = vid_vsync.integer && !cls.timedemo && qglXSwapIntervalSGI;
740 if (vid_usingvsync != vid_usevsync)
742 vid_usingvsync = vid_usevsync;
743 if (qglXSwapIntervalSGI (vid_usevsync))
744 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");
750 if (r_speeds.integer == 2 || gl_finish.integer)
752 qglFinish();CHECKGLERROR
754 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
757 if (vid_x11_hardwaregammasupported)
758 VID_UpdateGamma(false, vid_x11_gammarampsize);
761 int VID_SetGamma(unsigned short *ramps, int rampsize)
763 return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
766 int VID_GetGamma(unsigned short *ramps, int rampsize)
768 return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
773 #if !defined(__APPLE__) && !defined(SUNOS)
774 Cvar_RegisterVariable (&vid_dgamouse);
776 Cvar_RegisterVariable (&vid_netwmfullscreen);
777 InitSig(); // trap evil signals
778 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
779 if (COM_CheckParm ("-nomouse"))
783 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
785 *attrib++ = GLX_RGBA;
786 *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
787 *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
788 *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
789 *attrib++ = GLX_DOUBLEBUFFER;
790 *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
791 // if stencil is enabled, ask for alpha too
794 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
795 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
798 *attrib++ = GLX_STEREO;
801 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
803 *attrib++ = GLX_SAMPLES_ARB;
809 qboolean VID_InitMode(viddef_mode_t *mode)
813 XSetWindowAttributes attr;
814 XClassHint *clshints;
818 XVisualInfo *visinfo;
819 int MajorVersion, MinorVersion;
820 const char *drivername;
825 vid_isfullscreen = false;
826 vid_isnetwmfullscreen = false;
827 vid_isvidmodefullscreen = false;
828 vid_isoverrideredirect = false;
830 #if defined(__APPLE__) && defined(__MACH__)
831 drivername = "/usr/X11R6/lib/libGL.1.dylib";
833 drivername = "libGL.so.1";
835 // 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
836 // 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
837 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
838 i = COM_CheckParm("-gl_driver");
839 if (i && i < com_argc - 1)
840 drivername = com_argv[i + 1];
841 if (!GL_OpenLibrary(drivername))
843 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
847 if (!(vidx11_display = XOpenDisplay(NULL)))
849 Con_Print("Couldn't open the X display\n");
853 // LordHavoc: making the close button on a window do the right thing
854 // seems to involve this mess, sigh...
855 wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
856 net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
857 net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
858 net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
859 net_wm_icon = XInternAtom(vidx11_display, "_NET_WM_ICON", false);
860 cardinal = XInternAtom(vidx11_display, "CARDINAL", false);
862 // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
863 XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
865 vidx11_screen = DefaultScreen(vidx11_display);
866 root = RootWindow(vidx11_display, vidx11_screen);
868 // Get video mode list
869 MajorVersion = MinorVersion = 0;
870 if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
874 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
878 if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
879 || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
880 || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
881 || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
882 || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
883 || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
885 Con_Printf("glX functions not found in %s\n", gl_driver);
889 VID_BuildGLXAttrib(attrib, mode->bitsperpixel == 32, mode->stereobuffer, mode->samples);
890 visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
893 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
897 if (mode->fullscreen)
899 if(vid_netwmfullscreen.integer)
901 // TODO detect WM support
902 vid_isnetwmfullscreen = true;
903 vid_isfullscreen = true;
904 // width and height will be filled in later
905 Con_DPrintf("Using NetWM fullscreen mode\n");
908 if(!vid_isfullscreen && vidmode_ext)
910 int best_fit, best_dist, dist, x, y;
912 // Are we going fullscreen? If so, let's change video mode
913 XF86VidModeModeLine *current_vidmode;
914 XF86VidModeModeInfo **vidmodes;
917 // This nice hack comes from the SDL source code
918 current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
919 XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
921 XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
925 for (i = 0; i < num_vidmodes; i++)
927 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
930 x = mode->width - vidmodes[i]->hdisplay;
931 y = mode->height - vidmodes[i]->vdisplay;
932 dist = (x * x) + (y * y);
933 if (best_fit == -1 || dist < best_dist)
942 // LordHavoc: changed from ActualWidth/ActualHeight =,
943 // to width/height =, so the window will take the full area of
945 mode->width = vidmodes[best_fit]->hdisplay;
946 mode->height = vidmodes[best_fit]->vdisplay;
948 // change to the mode
949 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
950 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
951 vid_isvidmodefullscreen = true;
952 vid_isfullscreen = true;
954 // Move the viewport to top left
955 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
956 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
962 if(!vid_isfullscreen)
964 // sorry, no FS available
965 // use the full desktop resolution
966 vid_isfullscreen = true;
967 // width and height will be filled in later
968 mode->width = DisplayWidth(vidx11_display, vidx11_screen);
969 mode->height = DisplayHeight(vidx11_display, vidx11_screen);
970 Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
974 // LordHavoc: save the visual for use in gamma ramp settings later
975 vidx11_visual = visinfo->visual;
977 /* window attributes */
978 attr.background_pixel = 0;
979 attr.border_pixel = 0;
980 // LordHavoc: save the colormap for later, too
981 vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
982 attr.event_mask = X_MASK;
984 if (mode->fullscreen)
986 if(vid_isnetwmfullscreen)
988 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
989 attr.backing_store = NotUseful;
990 attr.save_under = False;
994 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
995 attr.override_redirect = True;
996 attr.backing_store = NotUseful;
997 attr.save_under = False;
998 vid_isoverrideredirect = true; // so it knows to grab
1003 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1006 win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
1008 data = loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1011 // use _NET_WM_ICON too
1012 static long netwm_icon[MAX_NETWM_ICON];
1018 if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1020 netwm_icon[pos++] = image_width;
1021 netwm_icon[pos++] = image_height;
1022 for(i = 0; i < image_height; ++i)
1023 for(j = 0; j < image_width; ++j)
1024 netwm_icon[pos++] = BuffLittleLong(&data[(i*image_width+j)*4]);
1028 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1032 data = loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1034 XChangeProperty(vidx11_display, win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1037 // fallthrough for old window managers
1038 xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1041 idata = XPM_DecodeString(xpm);
1043 idata = ENGINE_ICON;
1045 wmhints = XAllocWMHints();
1046 if(XpmCreatePixmapFromData(vidx11_display, win,
1048 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1049 wmhints->flags |= IconPixmapHint | IconMaskHint;
1054 clshints = XAllocClassHint();
1055 clshints->res_name = strdup(gamename);
1056 clshints->res_class = strdup("DarkPlaces");
1058 szhints = XAllocSizeHints();
1059 if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1061 szhints->min_width = szhints->max_width = mode->width;
1062 szhints->min_height = szhints->max_height = mode->height;
1063 szhints->flags |= PMinSize | PMaxSize;
1066 XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1067 // strdup() allocates using malloc(), should be freed with free()
1068 free(clshints->res_name);
1069 free(clshints->res_class);
1074 //XStoreName(vidx11_display, win, gamename);
1075 XMapWindow(vidx11_display, win);
1077 XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1079 if (vid_isoverrideredirect)
1081 XMoveWindow(vidx11_display, win, 0, 0);
1082 XRaiseWindow(vidx11_display, win);
1083 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1084 XFlush(vidx11_display);
1087 if(vid_isvidmodefullscreen)
1089 // Move the viewport to top left
1090 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1093 //XSync(vidx11_display, False);
1095 ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
1096 XFree(visinfo); // glXChooseVisual man page says to use XFree to free visinfo
1099 Con_Printf ("glXCreateContext failed\n");
1103 if (!qglXMakeCurrent(vidx11_display, win, ctx))
1105 Con_Printf ("glXMakeCurrent failed\n");
1109 XSync(vidx11_display, False);
1111 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1113 Con_Printf ("glGetString not found in %s\n", gl_driver);
1117 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1118 gl_platform = "GLX";
1119 gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
1121 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1122 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1123 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1124 GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
1125 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
1126 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
1127 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
1128 GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
1130 vid_usingmousegrab = false;
1131 vid_usingmouse = false;
1132 vid_usinghidecursor = false;
1133 vid_usingvsync = false;
1135 vid_activewindow = true;
1136 vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1137 #if !defined(__APPLE__) && !defined(SUNOS)
1138 vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1139 if (!vid_x11_dgasupported)
1140 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1147 void Sys_SendKeyEvents(void)
1149 static qboolean sound_active = true;
1151 // enable/disable sound on focus gain/loss
1152 if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1157 sound_active = true;
1165 sound_active = false;
1176 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1182 XF86VidModeModeInfo **vidmodes;
1185 XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1187 for (i = 0; i < num_vidmodes; i++)
1191 // we don't get bpp info, so let's just assume all of 8, 15, 16, 24, 32 work
1192 for(bpp = 8; bpp <= 32; bpp = ((bpp == 8) ? 15 : (bpp & 0xF8) + 8))
1196 modes[k].width = vidmodes[i]->hdisplay;
1197 modes[k].height = vidmodes[i]->vdisplay;
1199 if(vidmodes[i]->dotclock && vidmodes[i]->htotal && vidmodes[i]->vtotal)
1200 modes[k].refreshrate = vidmodes[i]->dotclock / vidmodes[i]->htotal / vidmodes[i]->vtotal;
1202 modes[k].refreshrate = 60;
1203 modes[k].pixelheight_num = 1;
1204 modes[k].pixelheight_denom = 1; // xvidmode does not provide this
1208 // manpage of XF86VidModeGetAllModeLines says it should be freed by the caller
1212 return 0; // FIXME implement this