src/video/x11/SDL_x11video.c
author Ryan C. Gordon <icculus@icculus.org>
Wed, 22 Mar 2006 05:00:59 +0000
changeset 1575 3ba88cb7eb1b
parent 1558 b46bb79cc197
child 1609 c3b5d17277d4
permissions -rw-r--r--
Updated dynamic X11 code. See details in Bugzilla #170.
slouken@0
     1
/*
slouken@0
     2
    SDL - Simple DirectMedia Layer
slouken@1312
     3
    Copyright (C) 1997-2006 Sam Lantinga
slouken@0
     4
slouken@0
     5
    This library is free software; you can redistribute it and/or
slouken@1312
     6
    modify it under the terms of the GNU Lesser General Public
slouken@0
     7
    License as published by the Free Software Foundation; either
slouken@1312
     8
    version 2.1 of the License, or (at your option) any later version.
slouken@0
     9
slouken@0
    10
    This library is distributed in the hope that it will be useful,
slouken@0
    11
    but WITHOUT ANY WARRANTY; without even the implied warranty of
slouken@0
    12
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
slouken@1312
    13
    Lesser General Public License for more details.
slouken@0
    14
slouken@1312
    15
    You should have received a copy of the GNU Lesser General Public
slouken@1312
    16
    License along with this library; if not, write to the Free Software
slouken@1312
    17
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
slouken@0
    18
slouken@0
    19
    Sam Lantinga
slouken@252
    20
    slouken@libsdl.org
slouken@0
    21
*/
slouken@1402
    22
#include "SDL_config.h"
slouken@0
    23
slouken@0
    24
/* X11 based SDL video driver implementation.
slouken@0
    25
   Note:  This implementation does not currently need X11 thread locking,
slouken@0
    26
          since the event thread uses a separate X connection and any
slouken@0
    27
          additional locking necessary is handled internally.  However,
slouken@0
    28
          if full locking is neccessary, take a look at XInitThreads().
slouken@0
    29
*/
slouken@0
    30
slouken@0
    31
#include <unistd.h>
slouken@0
    32
#include <sys/ioctl.h>
slouken@0
    33
#ifdef MTRR_SUPPORT
slouken@0
    34
#include <asm/mtrr.h>
slouken@0
    35
#include <sys/fcntl.h>
slouken@0
    36
#endif
slouken@0
    37
slouken@1358
    38
#include "SDL_endian.h"
slouken@0
    39
#include "SDL_timer.h"
slouken@0
    40
#include "SDL_thread.h"
slouken@0
    41
#include "SDL_video.h"
slouken@0
    42
#include "SDL_mouse.h"
slouken@1361
    43
#include "../SDL_sysvideo.h"
slouken@1361
    44
#include "../SDL_pixels_c.h"
slouken@1361
    45
#include "../../events/SDL_events_c.h"
slouken@0
    46
#include "SDL_x11video.h"
slouken@0
    47
#include "SDL_x11wm_c.h"
slouken@0
    48
#include "SDL_x11mouse_c.h"
slouken@0
    49
#include "SDL_x11events_c.h"
slouken@0
    50
#include "SDL_x11modes_c.h"
slouken@0
    51
#include "SDL_x11image_c.h"
slouken@0
    52
#include "SDL_x11yuv_c.h"
slouken@0
    53
#include "SDL_x11gl_c.h"
slouken@0
    54
#include "SDL_x11gamma_c.h"
slouken@1361
    55
#include "../blank_cursor.h"
slouken@0
    56
slouken@0
    57
/* Initialization/Query functions */
slouken@0
    58
static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat);
slouken@0
    59
static SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
slouken@0
    60
static int X11_ToggleFullScreen(_THIS, int on);
slouken@0
    61
static void X11_UpdateMouse(_THIS);
slouken@0
    62
static int X11_SetColors(_THIS, int firstcolor, int ncolors,
slouken@0
    63
			 SDL_Color *colors);
slouken@0
    64
static int X11_SetGammaRamp(_THIS, Uint16 *ramp);
slouken@0
    65
static void X11_VideoQuit(_THIS);
slouken@0
    66
icculus@1168
    67
slouken@0
    68
/* X11 driver bootstrap functions */
slouken@0
    69
slouken@0
    70
static int X11_Available(void)
slouken@0
    71
{
icculus@1168
    72
	Display *display = NULL;
icculus@1168
    73
	if ( SDL_X11_LoadSymbols() ) {
icculus@1575
    74
		display = XOpenDisplay(NULL);
icculus@1168
    75
		if ( display != NULL ) {
icculus@1575
    76
			XCloseDisplay(display);
icculus@1168
    77
		}
icculus@1168
    78
		SDL_X11_UnloadSymbols();
slouken@0
    79
	}
slouken@0
    80
	return(display != NULL);
slouken@0
    81
}
slouken@0
    82
slouken@0
    83
static void X11_DeleteDevice(SDL_VideoDevice *device)
slouken@0
    84
{
slouken@0
    85
	if ( device ) {
slouken@0
    86
		if ( device->hidden ) {
slouken@1336
    87
			SDL_free(device->hidden);
slouken@0
    88
		}
slouken@0
    89
		if ( device->gl_data ) {
slouken@1336
    90
			SDL_free(device->gl_data);
slouken@0
    91
		}
slouken@1336
    92
		SDL_free(device);
icculus@1168
    93
		SDL_X11_UnloadSymbols();
slouken@0
    94
	}
slouken@0
    95
}
slouken@0
    96
slouken@0
    97
static SDL_VideoDevice *X11_CreateDevice(int devindex)
slouken@0
    98
{
icculus@1168
    99
	SDL_VideoDevice *device = NULL;
slouken@0
   100
icculus@1168
   101
	if ( SDL_X11_LoadSymbols() ) {
icculus@1168
   102
		/* Initialize all variables that we clean on shutdown */
slouken@1336
   103
		device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
icculus@1168
   104
		if ( device ) {
slouken@1336
   105
			SDL_memset(device, 0, (sizeof *device));
icculus@1168
   106
			device->hidden = (struct SDL_PrivateVideoData *)
slouken@1336
   107
					SDL_malloc((sizeof *device->hidden));
icculus@1168
   108
			device->gl_data = (struct SDL_PrivateGLData *)
slouken@1336
   109
					SDL_malloc((sizeof *device->gl_data));
icculus@1168
   110
		}
icculus@1168
   111
		if ( (device == NULL) || (device->hidden == NULL) ||
icculus@1168
   112
		                         (device->gl_data == NULL) ) {
icculus@1168
   113
			SDL_OutOfMemory();
icculus@1168
   114
			X11_DeleteDevice(device); /* calls SDL_X11_UnloadSymbols(). */
icculus@1168
   115
			return(0);
icculus@1168
   116
		}
slouken@1336
   117
		SDL_memset(device->hidden, 0, (sizeof *device->hidden));
slouken@1336
   118
		SDL_memset(device->gl_data, 0, (sizeof *device->gl_data));
icculus@1168
   119
icculus@1168
   120
		/* Set the driver flags */
icculus@1168
   121
		device->handles_any_size = 1;
icculus@1168
   122
icculus@1168
   123
		/* Set the function pointers */
icculus@1168
   124
		device->VideoInit = X11_VideoInit;
icculus@1168
   125
		device->ListModes = X11_ListModes;
icculus@1168
   126
		device->SetVideoMode = X11_SetVideoMode;
icculus@1168
   127
		device->ToggleFullScreen = X11_ToggleFullScreen;
icculus@1168
   128
		device->UpdateMouse = X11_UpdateMouse;
slouken@1361
   129
#if SDL_VIDEO_DRIVER_X11_XV
icculus@1168
   130
		device->CreateYUVOverlay = X11_CreateYUVOverlay;
icculus@1168
   131
#endif
icculus@1168
   132
		device->SetColors = X11_SetColors;
icculus@1168
   133
		device->UpdateRects = NULL;
icculus@1168
   134
		device->VideoQuit = X11_VideoQuit;
icculus@1168
   135
		device->AllocHWSurface = X11_AllocHWSurface;
icculus@1168
   136
		device->CheckHWBlit = NULL;
icculus@1168
   137
		device->FillHWRect = NULL;
icculus@1168
   138
		device->SetHWColorKey = NULL;
icculus@1168
   139
		device->SetHWAlpha = NULL;
icculus@1168
   140
		device->LockHWSurface = X11_LockHWSurface;
icculus@1168
   141
		device->UnlockHWSurface = X11_UnlockHWSurface;
icculus@1168
   142
		device->FlipHWSurface = X11_FlipHWSurface;
icculus@1168
   143
		device->FreeHWSurface = X11_FreeHWSurface;
icculus@1168
   144
		device->SetGamma = X11_SetVidModeGamma;
icculus@1168
   145
		device->GetGamma = X11_GetVidModeGamma;
icculus@1168
   146
		device->SetGammaRamp = X11_SetGammaRamp;
icculus@1168
   147
		device->GetGammaRamp = NULL;
slouken@1361
   148
#if SDL_VIDEO_OPENGL_GLX
icculus@1168
   149
		device->GL_LoadLibrary = X11_GL_LoadLibrary;
icculus@1168
   150
		device->GL_GetProcAddress = X11_GL_GetProcAddress;
icculus@1168
   151
		device->GL_GetAttribute = X11_GL_GetAttribute;
icculus@1168
   152
		device->GL_MakeCurrent = X11_GL_MakeCurrent;
icculus@1168
   153
		device->GL_SwapBuffers = X11_GL_SwapBuffers;
icculus@1168
   154
#endif
icculus@1168
   155
		device->SetCaption = X11_SetCaption;
icculus@1168
   156
		device->SetIcon = X11_SetIcon;
icculus@1168
   157
		device->IconifyWindow = X11_IconifyWindow;
icculus@1168
   158
		device->GrabInput = X11_GrabInput;
icculus@1168
   159
		device->GetWMInfo = X11_GetWMInfo;
icculus@1168
   160
		device->FreeWMCursor = X11_FreeWMCursor;
icculus@1168
   161
		device->CreateWMCursor = X11_CreateWMCursor;
icculus@1168
   162
		device->ShowWMCursor = X11_ShowWMCursor;
icculus@1168
   163
		device->WarpWMCursor = X11_WarpWMCursor;
icculus@1168
   164
		device->CheckMouseMode = X11_CheckMouseMode;
icculus@1168
   165
		device->InitOSKeymap = X11_InitOSKeymap;
icculus@1168
   166
		device->PumpEvents = X11_PumpEvents;
icculus@1168
   167
icculus@1168
   168
		device->free = X11_DeleteDevice;
slouken@0
   169
	}
slouken@0
   170
slouken@0
   171
	return device;
slouken@0
   172
}
slouken@0
   173
slouken@0
   174
VideoBootStrap X11_bootstrap = {
slouken@0
   175
	"x11", "X Window System",
slouken@0
   176
	X11_Available, X11_CreateDevice
slouken@0
   177
};
slouken@0
   178
slouken@0
   179
/* Normal X11 error handler routine */
slouken@0
   180
static int (*X_handler)(Display *, XErrorEvent *) = NULL;
slouken@0
   181
static int x_errhandler(Display *d, XErrorEvent *e)
slouken@0
   182
{
slouken@1361
   183
#if SDL_VIDEO_DRIVER_X11_VIDMODE
slouken@0
   184
	extern int vm_error;
slouken@0
   185
#endif
slouken@1361
   186
#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
slouken@0
   187
	extern int dga_error;
slouken@0
   188
#endif
slouken@0
   189
slouken@1361
   190
#if SDL_VIDEO_DRIVER_X11_VIDMODE
slouken@0
   191
	/* VidMode errors are non-fatal. :) */
slouken@0
   192
	/* Are the errors offset by one from the error base?
slouken@0
   193
	   e.g. the error base is 143, the code is 148, and the
slouken@0
   194
	        actual error is XF86VidModeExtensionDisabled (4) ?
slouken@0
   195
	 */
slouken@0
   196
        if ( (vm_error >= 0) &&
slouken@0
   197
	     (((e->error_code == BadRequest)&&(e->request_code == vm_error)) ||
slouken@0
   198
	      ((e->error_code > vm_error) &&
slouken@0
   199
	       (e->error_code <= (vm_error+XF86VidModeNumberErrors)))) ) {
slouken@0
   200
#ifdef XFREE86_DEBUG
slouken@0
   201
{ char errmsg[1024];
icculus@1575
   202
  XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg));
slouken@0
   203
printf("VidMode error: %s\n", errmsg);
slouken@0
   204
}
slouken@0
   205
#endif
slouken@0
   206
        	return(0);
slouken@0
   207
        }
slouken@1361
   208
#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
slouken@0
   209
slouken@1361
   210
#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
slouken@0
   211
	/* DGA errors can be non-fatal. :) */
slouken@0
   212
        if ( (dga_error >= 0) &&
slouken@0
   213
	     ((e->error_code > dga_error) &&
slouken@0
   214
	      (e->error_code <= (dga_error+XF86DGANumberErrors))) ) {
slouken@0
   215
#ifdef XFREE86_DEBUG
slouken@0
   216
{ char errmsg[1024];
icculus@1575
   217
  XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg));
slouken@0
   218
printf("DGA error: %s\n", errmsg);
slouken@0
   219
}
slouken@0
   220
#endif
slouken@0
   221
        	return(0);
slouken@0
   222
        }
slouken@1361
   223
#endif /* SDL_VIDEO_DRIVER_X11_DGAMOUSE */
slouken@0
   224
slouken@0
   225
	return(X_handler(d,e));
slouken@0
   226
}
slouken@0
   227
slouken@0
   228
/* X11 I/O error handler routine */
slouken@0
   229
static int (*XIO_handler)(Display *) = NULL;
slouken@0
   230
static int xio_errhandler(Display *d)
slouken@0
   231
{
slouken@0
   232
	/* Ack!  Lost X11 connection! */
slouken@0
   233
slouken@0
   234
	/* We will crash if we try to clean up our display */
slouken@0
   235
	if ( current_video->hidden->Ximage ) {
slouken@0
   236
		SDL_VideoSurface->pixels = NULL;
slouken@0
   237
	}
slouken@0
   238
	current_video->hidden->X11_Display = NULL;
slouken@0
   239
slouken@0
   240
	/* Continue with the standard X11 error handler */
slouken@0
   241
	return(XIO_handler(d));
slouken@0
   242
}
slouken@0
   243
icculus@1248
   244
static int (*Xext_handler)(Display *,char *,char *) = NULL;
icculus@1248
   245
static int xext_errhandler(Display *d, char *ext_name, char *reason)
icculus@1248
   246
{
icculus@1248
   247
#ifdef XFREE86_DEBUG
icculus@1248
   248
	printf("Xext error inside SDL (may be harmless):\n");
icculus@1248
   249
	printf("  Extension \"%s\" %s on display \"%s\".\n",
icculus@1575
   250
	       ext_name, reason, XDisplayString(d));
icculus@1248
   251
#endif
icculus@1248
   252
slouken@1336
   253
	if (SDL_strcmp(reason, "missing") == 0) {
icculus@1248
   254
		/*
icculus@1248
   255
		 * Since the query itself, elsewhere, can handle a missing extension
icculus@1248
   256
		 *  and the default behaviour in Xlib is to write to stderr, which
icculus@1248
   257
		 *  generates unnecessary bug reports, we just ignore these.
icculus@1248
   258
		 */
icculus@1248
   259
		return 0;
icculus@1248
   260
	}
icculus@1248
   261
icculus@1248
   262
	/* Everything else goes to the default handler... */
icculus@1248
   263
	return Xext_handler(d, ext_name, reason);
icculus@1248
   264
}
icculus@1248
   265
slouken@1325
   266
/* Find out what class name we should use */
slouken@1325
   267
static char *get_classname(char *classname, int maxlen)
slouken@1325
   268
{
slouken@1325
   269
	char *spot;
slouken@1402
   270
#if defined(__LINUX__) || defined(__FREEBSD__)
slouken@1325
   271
	char procfile[1024];
slouken@1325
   272
	char linkfile[1024];
slouken@1325
   273
	int linksize;
slouken@1325
   274
#endif
slouken@1325
   275
slouken@1325
   276
	/* First allow environment variable override */
slouken@1336
   277
	spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS");
slouken@1325
   278
	if ( spot ) {
slouken@1379
   279
		SDL_strlcpy(classname, spot, maxlen);
slouken@1325
   280
		return classname;
slouken@1325
   281
	}
slouken@1325
   282
slouken@1325
   283
	/* Next look at the application's executable name */
slouken@1402
   284
#if defined(__LINUX__) || defined(__FREEBSD__)
slouken@1402
   285
#if defined(__LINUX__)
slouken@1338
   286
	SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid());
slouken@1402
   287
#elif defined(__FREEBSD__)
slouken@1338
   288
	SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file", getpid());
slouken@1325
   289
#else
slouken@1325
   290
#error Where can we find the executable name?
slouken@1325
   291
#endif
slouken@1325
   292
	linksize = readlink(procfile, linkfile, sizeof(linkfile)-1);
slouken@1325
   293
	if ( linksize > 0 ) {
slouken@1325
   294
		linkfile[linksize] = '\0';
slouken@1336
   295
		spot = SDL_strrchr(linkfile, '/');
slouken@1325
   296
		if ( spot ) {
slouken@1379
   297
			SDL_strlcpy(classname, spot+1, maxlen);
slouken@1325
   298
		} else {
slouken@1379
   299
			SDL_strlcpy(classname, linkfile, maxlen);
slouken@1325
   300
		}
slouken@1325
   301
		return classname;
slouken@1325
   302
	}
slouken@1402
   303
#endif /* __LINUX__ */
slouken@1325
   304
slouken@1325
   305
	/* Finally use the default we've used forever */
slouken@1379
   306
	SDL_strlcpy(classname, "SDL_App", maxlen);
slouken@1325
   307
	return classname;
slouken@1325
   308
}
slouken@1325
   309
slouken@0
   310
/* Create auxiliary (toplevel) windows with the current visual */
slouken@0
   311
static void create_aux_windows(_THIS)
slouken@0
   312
{
slouken@1558
   313
    Atom _NET_WM_NAME;
slouken@1558
   314
    Atom _NET_WM_ICON_NAME;
slouken@1325
   315
    char classname[1024];
slouken@0
   316
    XSetWindowAttributes xattr;
slouken@0
   317
    XWMHints *hints;
slouken@1558
   318
    XTextProperty titleprop, titlepropUTF8, iconprop, iconpropUTF8;
slouken@0
   319
    int def_vis = (SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen));
slouken@0
   320
slouken@1558
   321
    /* Look up some useful Atoms */
icculus@1575
   322
    WM_DELETE_WINDOW = XInternAtom(SDL_Display, "WM_DELETE_WINDOW", False);
icculus@1575
   323
    _NET_WM_NAME = XInternAtom(SDL_Display, "_NET_WM_NAME", False);
icculus@1575
   324
    _NET_WM_ICON_NAME = XInternAtom(SDL_Display, "_NET_WM_ICON_NAME", False);
slouken@1558
   325
slouken@0
   326
    /* Don't create any extra windows if we are being managed */
slouken@0
   327
    if ( SDL_windowid ) {
slouken@0
   328
	FSwindow = 0;
slouken@1336
   329
	WMwindow = SDL_strtol(SDL_windowid, NULL, 0);
slouken@0
   330
        return;
slouken@0
   331
    }
slouken@0
   332
slouken@0
   333
    if(FSwindow)
icculus@1575
   334
	XDestroyWindow(SDL_Display, FSwindow);
slouken@0
   335
slouken@0
   336
    xattr.override_redirect = True;
slouken@0
   337
    xattr.background_pixel = def_vis ? BlackPixel(SDL_Display, SDL_Screen) : 0;
slouken@0
   338
    xattr.border_pixel = 0;
slouken@0
   339
    xattr.colormap = SDL_XColorMap;
slouken@0
   340
icculus@1575
   341
    FSwindow = XCreateWindow(SDL_Display, SDL_Root,
slouken@499
   342
                             xinerama_x, xinerama_y, 32, 32, 0,
slouken@0
   343
			     this->hidden->depth, InputOutput, SDL_Visual,
slouken@0
   344
			     CWOverrideRedirect | CWBackPixel | CWBorderPixel
slouken@0
   345
			     | CWColormap,
slouken@0
   346
			     &xattr);
slouken@0
   347
icculus@1575
   348
    XSelectInput(SDL_Display, FSwindow, StructureNotifyMask);
slouken@0
   349
slouken@0
   350
    /* Tell KDE to keep the fullscreen window on top */
slouken@0
   351
    {
slouken@0
   352
	XEvent ev;
slouken@0
   353
	long mask;
slouken@0
   354
slouken@1336
   355
	SDL_memset(&ev, 0, sizeof(ev));
slouken@0
   356
	ev.xclient.type = ClientMessage;
slouken@0
   357
	ev.xclient.window = SDL_Root;
icculus@1575
   358
	ev.xclient.message_type = XInternAtom(SDL_Display,
slouken@0
   359
					      "KWM_KEEP_ON_TOP", False);
slouken@0
   360
	ev.xclient.format = 32;
slouken@0
   361
	ev.xclient.data.l[0] = FSwindow;
slouken@0
   362
	ev.xclient.data.l[1] = CurrentTime;
slouken@0
   363
	mask = SubstructureRedirectMask;
icculus@1575
   364
	XSendEvent(SDL_Display, SDL_Root, False, mask, &ev);
slouken@0
   365
    }
slouken@0
   366
slouken@0
   367
    hints = NULL;
slouken@1558
   368
    titleprop.value = titlepropUTF8.value = NULL;
slouken@1558
   369
    iconprop.value = iconpropUTF8.value = NULL;
slouken@0
   370
    if(WMwindow) {
slouken@0
   371
	/* All window attributes must survive the recreation */
icculus@1575
   372
	hints = XGetWMHints(SDL_Display, WMwindow);
icculus@1575
   373
	XGetTextProperty(SDL_Display, WMwindow, &titleprop, XA_WM_NAME);
icculus@1575
   374
	XGetTextProperty(SDL_Display, WMwindow, &titlepropUTF8, _NET_WM_NAME);
icculus@1575
   375
	XGetTextProperty(SDL_Display, WMwindow, &iconprop, XA_WM_ICON_NAME);
icculus@1575
   376
	XGetTextProperty(SDL_Display, WMwindow, &iconpropUTF8, _NET_WM_ICON_NAME);
icculus@1575
   377
	XDestroyWindow(SDL_Display, WMwindow);
slouken@0
   378
    }
slouken@0
   379
slouken@0
   380
    /* Create the window for windowed management */
slouken@0
   381
    /* (reusing the xattr structure above) */
icculus@1575
   382
    WMwindow = XCreateWindow(SDL_Display, SDL_Root, 0, 0, 32, 32, 0,
slouken@0
   383
			     this->hidden->depth, InputOutput, SDL_Visual,
slouken@0
   384
			     CWBackPixel | CWBorderPixel | CWColormap,
slouken@0
   385
			     &xattr);
slouken@0
   386
slouken@0
   387
    /* Set the input hints so we get keyboard input */
slouken@0
   388
    if(!hints) {
icculus@1575
   389
	hints = XAllocWMHints();
slouken@0
   390
	hints->input = True;
slouken@0
   391
	hints->flags = InputHint;
slouken@0
   392
    }
icculus@1575
   393
    XSetWMHints(SDL_Display, WMwindow, hints);
icculus@1575
   394
    XFree(hints);
slouken@0
   395
    if(titleprop.value) {
icculus@1575
   396
	XSetTextProperty(SDL_Display, WMwindow, &titleprop, XA_WM_NAME);
icculus@1575
   397
	XFree(titleprop.value);
slouken@0
   398
    }
slouken@1558
   399
    if(titlepropUTF8.value) {
icculus@1575
   400
	XSetTextProperty(SDL_Display, WMwindow, &titlepropUTF8, _NET_WM_NAME);
icculus@1575
   401
	XFree(titlepropUTF8.value);
slouken@1558
   402
    }
slouken@0
   403
    if(iconprop.value) {
icculus@1575
   404
	XSetTextProperty(SDL_Display, WMwindow, &iconprop, XA_WM_ICON_NAME);
icculus@1575
   405
	XFree(iconprop.value);
slouken@0
   406
    }
slouken@1558
   407
    if(iconpropUTF8.value) {
icculus@1575
   408
	XSetTextProperty(SDL_Display, WMwindow, &iconpropUTF8, _NET_WM_ICON_NAME);
icculus@1575
   409
	XFree(iconpropUTF8.value);
slouken@1558
   410
    }
slouken@0
   411
icculus@1575
   412
    XSelectInput(SDL_Display, WMwindow,
slouken@0
   413
		 FocusChangeMask | KeyPressMask | KeyReleaseMask
slouken@0
   414
		 | PropertyChangeMask | StructureNotifyMask | KeymapStateMask);
slouken@0
   415
slouken@0
   416
    /* Set the class hints so we can get an icon (AfterStep) */
slouken@1325
   417
    get_classname(classname, sizeof(classname));
slouken@0
   418
    {
slouken@0
   419
	XClassHint *classhints;
icculus@1575
   420
	classhints = XAllocClassHint();
slouken@0
   421
	if(classhints != NULL) {
slouken@449
   422
	    classhints->res_name = classname;
slouken@449
   423
	    classhints->res_class = classname;
icculus@1575
   424
	    XSetClassHint(SDL_Display, WMwindow, classhints);
icculus@1575
   425
	    XFree(classhints);
slouken@0
   426
	}
slouken@0
   427
    }
slouken@0
   428
icculus@1178
   429
    /* Setup the communication with the IM server */
icculus@1575
   430
	SDL_IM = NULL;
icculus@1575
   431
	SDL_IC = NULL;
icculus@1178
   432
icculus@1575
   433
	#ifdef X_HAVE_UTF8_STRING
icculus@1575
   434
	if (SDL_X11_HAVE_UTF8) {
icculus@1575
   435
		SDL_IM = XOpenIM(SDL_Display, NULL, classname, classname);
icculus@1575
   436
		if (SDL_IM == NULL) {
icculus@1575
   437
			SDL_SetError("no input method could be opened");
icculus@1575
   438
		} else {
icculus@1575
   439
			SDL_IC = pXCreateIC(SDL_IM,
icculus@1575
   440
					XNClientWindow, WMwindow,
icculus@1575
   441
					XNFocusWindow, WMwindow,
icculus@1575
   442
					XNInputStyle, XIMPreeditNothing  | XIMStatusNothing,
icculus@1575
   443
					XNResourceName, classname,
icculus@1575
   444
					XNResourceClass, classname,
icculus@1575
   445
					NULL);
icculus@1575
   446
icculus@1575
   447
			if (SDL_IC == NULL) {
icculus@1575
   448
				SDL_SetError("no input context could be created");
icculus@1575
   449
				XCloseIM(SDL_IM);
icculus@1575
   450
				SDL_IM = NULL;
icculus@1575
   451
			}
icculus@1575
   452
		}
icculus@1178
   453
	}
icculus@1575
   454
	#endif
icculus@1178
   455
icculus@1575
   456
	/* Allow the window to be deleted by the window manager */
icculus@1575
   457
	XSetWMProtocols(SDL_Display, WMwindow, &WM_DELETE_WINDOW, 1);
slouken@0
   458
}
slouken@0
   459
slouken@0
   460
static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat)
slouken@0
   461
{
slouken@0
   462
	char *display;
slouken@0
   463
	int i;
slouken@0
   464
slouken@0
   465
	/* Open the X11 display */
slouken@0
   466
	display = NULL;		/* Get it from DISPLAY environment variable */
slouken@0
   467
icculus@1575
   468
	if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) ||
icculus@1575
   469
	     (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) {
slouken@0
   470
		local_X11 = 1;
slouken@0
   471
	} else {
slouken@0
   472
		local_X11 = 0;
slouken@0
   473
	}
icculus@1575
   474
	SDL_Display = XOpenDisplay(display);
slouken@1361
   475
#if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC)
icculus@1299
   476
	/* On Tru64 if linking without -lX11, it fails and you get following message.
icculus@1299
   477
	 * Xlib: connection to ":0.0" refused by server
icculus@1299
   478
	 * Xlib: XDM authorization key matches an existing client!
icculus@1299
   479
	 *
icculus@1299
   480
	 * It succeeds if retrying 1 second later
icculus@1299
   481
	 * or if running xhost +localhost on shell.
icculus@1299
   482
	 *
icculus@1299
   483
	 */
icculus@1299
   484
	if ( SDL_Display == NULL ) {
icculus@1299
   485
		SDL_Delay(1000);
icculus@1575
   486
		SDL_Display = XOpenDisplay(display);
icculus@1299
   487
	}
icculus@1299
   488
#endif
slouken@0
   489
	if ( SDL_Display == NULL ) {
slouken@0
   490
		SDL_SetError("Couldn't open X11 display");
slouken@0
   491
		return(-1);
slouken@0
   492
	}
slouken@0
   493
#ifdef X11_DEBUG
icculus@1575
   494
	XSynchronize(SDL_Display, True);
slouken@0
   495
#endif
slouken@0
   496
slouken@0
   497
	/* Create an alternate X display for graphics updates -- allows us
slouken@0
   498
	   to do graphics updates in a separate thread from event handling.
slouken@0
   499
	   Thread-safe X11 doesn't seem to exist.
slouken@0
   500
	 */
icculus@1575
   501
	GFX_Display = XOpenDisplay(display);
slouken@0
   502
	if ( GFX_Display == NULL ) {
slouken@0
   503
		SDL_SetError("Couldn't open X11 display");
slouken@0
   504
		return(-1);
slouken@0
   505
	}
slouken@0
   506
slouken@0
   507
	/* Set the normal X error handler */
icculus@1575
   508
	X_handler = XSetErrorHandler(x_errhandler);
slouken@0
   509
slouken@0
   510
	/* Set the error handler if we lose the X display */
icculus@1575
   511
	XIO_handler = XSetIOErrorHandler(xio_errhandler);
slouken@0
   512
icculus@1248
   513
	/* Set the X extension error handler */
icculus@1575
   514
	Xext_handler = XSetExtensionErrorHandler(xext_errhandler);
icculus@1248
   515
slouken@0
   516
	/* use default screen (from $DISPLAY) */
slouken@0
   517
	SDL_Screen = DefaultScreen(SDL_Display);
slouken@0
   518
slouken@0
   519
#ifndef NO_SHARED_MEMORY
slouken@0
   520
	/* Check for MIT shared memory extension */
slouken@556
   521
	use_mitshm = 0;
slouken@0
   522
	if ( local_X11 ) {
icculus@1575
   523
		use_mitshm = XShmQueryExtension(SDL_Display);
slouken@0
   524
	}
slouken@0
   525
#endif /* NO_SHARED_MEMORY */
slouken@0
   526
slouken@0
   527
	/* Get the available video modes */
slouken@0
   528
	if(X11_GetVideoModes(this) < 0)
slouken@0
   529
	    return -1;
slouken@0
   530
slouken@1545
   531
	/* Determine the current screen size */
slouken@1545
   532
	this->info.current_w = DisplayWidth(SDL_Display, SDL_Screen);
slouken@1545
   533
	this->info.current_h = DisplayHeight(SDL_Display, SDL_Screen);
slouken@1545
   534
slouken@0
   535
	/* Determine the default screen depth:
slouken@0
   536
	   Use the default visual (or at least one with the same depth) */
slouken@0
   537
	SDL_DisplayColormap = DefaultColormap(SDL_Display, SDL_Screen);
slouken@0
   538
	for(i = 0; i < this->hidden->nvisuals; i++)
slouken@0
   539
	    if(this->hidden->visuals[i].depth == DefaultDepth(SDL_Display,
slouken@0
   540
							      SDL_Screen))
slouken@0
   541
		break;
slouken@0
   542
	if(i == this->hidden->nvisuals) {
slouken@0
   543
	    /* default visual was useless, take the deepest one instead */
slouken@0
   544
	    i = 0;
slouken@0
   545
	}
slouken@0
   546
	SDL_Visual = this->hidden->visuals[i].visual;
slouken@0
   547
	if ( SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen) ) {
slouken@0
   548
	    SDL_XColorMap = SDL_DisplayColormap;
slouken@0
   549
	} else {
icculus@1575
   550
	    SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
slouken@0
   551
					    SDL_Visual, AllocNone);
slouken@0
   552
	}
slouken@0
   553
	this->hidden->depth = this->hidden->visuals[i].depth;
slouken@0
   554
	vformat->BitsPerPixel = this->hidden->visuals[i].bpp;
slouken@0
   555
	if ( vformat->BitsPerPixel > 8 ) {
slouken@0
   556
		vformat->Rmask = SDL_Visual->red_mask;
slouken@0
   557
	  	vformat->Gmask = SDL_Visual->green_mask;
slouken@0
   558
	  	vformat->Bmask = SDL_Visual->blue_mask;
slouken@0
   559
	}
slouken@0
   560
	X11_SaveVidModeGamma(this);
slouken@0
   561
slouken@0
   562
	/* See if we have been passed a window to use */
slouken@1336
   563
	SDL_windowid = SDL_getenv("SDL_WINDOWID");
slouken@0
   564
slouken@0
   565
	/* Create the fullscreen and managed windows */
slouken@0
   566
	create_aux_windows(this);
slouken@0
   567
slouken@0
   568
	/* Create the blank cursor */
slouken@0
   569
	SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask,
slouken@0
   570
					BLANK_CWIDTH, BLANK_CHEIGHT,
slouken@0
   571
						BLANK_CHOTX, BLANK_CHOTY);
slouken@0
   572
slouken@0
   573
	/* Fill in some window manager capabilities */
slouken@0
   574
	this->info.wm_available = 1;
slouken@0
   575
slouken@0
   576
	/* We're done! */
icculus@1575
   577
	XFlush(SDL_Display);
slouken@0
   578
	return(0);
slouken@0
   579
}
slouken@0
   580
slouken@0
   581
static void X11_DestroyWindow(_THIS, SDL_Surface *screen)
slouken@0
   582
{
slouken@0
   583
	/* Clean up OpenGL */
slouken@0
   584
	if ( screen ) {
slouken@0
   585
		screen->flags &= ~(SDL_OPENGL|SDL_OPENGLBLIT);
slouken@0
   586
	}
slouken@0
   587
	X11_GL_Shutdown(this);
slouken@0
   588
slouken@0
   589
	if ( ! SDL_windowid ) {
slouken@0
   590
		/* Hide the managed window */
slouken@0
   591
		if ( WMwindow ) {
icculus@1575
   592
			XUnmapWindow(SDL_Display, WMwindow);
slouken@0
   593
		}
slouken@0
   594
		if ( screen && (screen->flags & SDL_FULLSCREEN) ) {
slouken@0
   595
			screen->flags &= ~SDL_FULLSCREEN;
slouken@0
   596
			X11_LeaveFullScreen(this);
slouken@0
   597
		}
slouken@0
   598
slouken@0
   599
		/* Destroy the output window */
slouken@0
   600
		if ( SDL_Window ) {
icculus@1575
   601
			XDestroyWindow(SDL_Display, SDL_Window);
slouken@0
   602
		}
slouken@0
   603
slouken@0
   604
		/* Free the colormap entries */
slouken@0
   605
		if ( SDL_XPixels ) {
slouken@0
   606
			int numcolors;
slouken@0
   607
			unsigned long pixel;
slouken@0
   608
			numcolors = SDL_Visual->map_entries;
slouken@0
   609
			for ( pixel=0; pixel<numcolors; ++pixel ) {
slouken@0
   610
				while ( SDL_XPixels[pixel] > 0 ) {
icculus@1575
   611
					XFreeColors(GFX_Display,
slouken@0
   612
						SDL_DisplayColormap,&pixel,1,0);
slouken@0
   613
					--SDL_XPixels[pixel];
slouken@0
   614
				}
slouken@0
   615
			}
slouken@1336
   616
			SDL_free(SDL_XPixels);
slouken@0
   617
			SDL_XPixels = NULL;
slouken@0
   618
		} 
slouken@0
   619
slouken@0
   620
		/* Free the graphics context */
slouken@0
   621
		if ( SDL_GC ) {
icculus@1575
   622
			XFreeGC(SDL_Display, SDL_GC);
slouken@0
   623
			SDL_GC = 0;
slouken@0
   624
		}
slouken@0
   625
	}
slouken@0
   626
}
slouken@0
   627
slouken@497
   628
static SDL_bool X11_WindowPosition(_THIS, int *x, int *y, int w, int h)
slouken@497
   629
{
slouken@1336
   630
	const char *window = SDL_getenv("SDL_VIDEO_WINDOW_POS");
slouken@1336
   631
	const char *center = SDL_getenv("SDL_VIDEO_CENTERED");
slouken@497
   632
	if ( window ) {
slouken@1336
   633
		if ( SDL_sscanf(window, "%d,%d", x, y) == 2 ) {
slouken@497
   634
			return SDL_TRUE;
slouken@497
   635
		}
slouken@1336
   636
		if ( SDL_strcmp(window, "center") == 0 ) {
slouken@497
   637
			center = window;
slouken@497
   638
		}
slouken@497
   639
	}
slouken@497
   640
	if ( center ) {
slouken@497
   641
		*x = (DisplayWidth(SDL_Display, SDL_Screen) - w)/2;
slouken@497
   642
		*y = (DisplayHeight(SDL_Display, SDL_Screen) - h)/2;
slouken@497
   643
		return SDL_TRUE;
slouken@497
   644
	}
slouken@497
   645
	return SDL_FALSE;
slouken@497
   646
}
slouken@497
   647
slouken@0
   648
static void X11_SetSizeHints(_THIS, int w, int h, Uint32 flags)
slouken@0
   649
{
slouken@0
   650
	XSizeHints *hints;
slouken@0
   651
icculus@1575
   652
	hints = XAllocSizeHints();
slouken@0
   653
	if ( hints ) {
slouken@0
   654
		if ( flags & SDL_RESIZABLE ) {
slouken@0
   655
			hints->min_width = 32;
slouken@0
   656
			hints->min_height = 32;
slouken@0
   657
			hints->max_height = 4096;
slouken@0
   658
			hints->max_width = 4096;
slouken@0
   659
		} else {
slouken@0
   660
			hints->min_width = hints->max_width = w;
slouken@0
   661
			hints->min_height = hints->max_height = h;
slouken@0
   662
		}
slouken@0
   663
		hints->flags = PMaxSize | PMinSize;
slouken@0
   664
		if ( flags & SDL_FULLSCREEN ) {
slouken@0
   665
			hints->x = 0;
slouken@0
   666
			hints->y = 0;
slouken@0
   667
			hints->flags |= USPosition;
slouken@0
   668
		} else
slouken@0
   669
		/* Center it, if desired */
slouken@497
   670
		if ( X11_WindowPosition(this, &hints->x, &hints->y, w, h) ) {
slouken@0
   671
			hints->flags |= USPosition;
icculus@1575
   672
			XMoveWindow(SDL_Display, WMwindow, hints->x, hints->y);
slouken@0
   673
slouken@0
   674
			/* Flush the resize event so we don't catch it later */
icculus@1575
   675
			XSync(SDL_Display, True);
slouken@0
   676
		}
icculus@1575
   677
		XSetWMNormalHints(SDL_Display, WMwindow, hints);
icculus@1575
   678
		XFree(hints);
slouken@0
   679
	}
slouken@0
   680
slouken@0
   681
	/* Respect the window caption style */
slouken@0
   682
	if ( flags & SDL_NOFRAME ) {
slouken@0
   683
		SDL_bool set;
slouken@0
   684
		Atom WM_HINTS;
slouken@0
   685
slouken@0
   686
		/* We haven't modified the window manager hints yet */
slouken@0
   687
		set = SDL_FALSE;
slouken@0
   688
slouken@0
   689
		/* First try to set MWM hints */
icculus@1575
   690
		WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True);
slouken@0
   691
		if ( WM_HINTS != None ) {
slouken@0
   692
			/* Hints used by Motif compliant window managers */
slouken@0
   693
			struct {
slouken@0
   694
				unsigned long flags;
slouken@0
   695
				unsigned long functions;
slouken@0
   696
				unsigned long decorations;
slouken@0
   697
				long input_mode;
slouken@0
   698
				unsigned long status;
slouken@0
   699
			} MWMHints = { (1L << 1), 0, 0, 0, 0 };
slouken@0
   700
icculus@1575
   701
			XChangeProperty(SDL_Display, WMwindow,
slouken@0
   702
			                WM_HINTS, WM_HINTS, 32,
slouken@0
   703
			                PropModeReplace,
slouken@0
   704
					(unsigned char *)&MWMHints,
slouken@0
   705
					sizeof(MWMHints)/sizeof(long));
slouken@0
   706
			set = SDL_TRUE;
slouken@0
   707
		}
slouken@0
   708
		/* Now try to set KWM hints */
icculus@1575
   709
		WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True);
slouken@0
   710
		if ( WM_HINTS != None ) {
slouken@0
   711
			long KWMHints = 0;
slouken@0
   712
icculus@1575
   713
			XChangeProperty(SDL_Display, WMwindow,
slouken@0
   714
			                WM_HINTS, WM_HINTS, 32,
slouken@0
   715
			                PropModeReplace,
slouken@0
   716
					(unsigned char *)&KWMHints,
slouken@0
   717
					sizeof(KWMHints)/sizeof(long));
slouken@0
   718
			set = SDL_TRUE;
slouken@0
   719
		}
slouken@0
   720
		/* Now try to set GNOME hints */
icculus@1575
   721
		WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True);
slouken@0
   722
		if ( WM_HINTS != None ) {
slouken@0
   723
			long GNOMEHints = 0;
slouken@0
   724
icculus@1575
   725
			XChangeProperty(SDL_Display, WMwindow,
slouken@0
   726
			                WM_HINTS, WM_HINTS, 32,
slouken@0
   727
			                PropModeReplace,
slouken@0
   728
					(unsigned char *)&GNOMEHints,
slouken@0
   729
					sizeof(GNOMEHints)/sizeof(long));
slouken@0
   730
			set = SDL_TRUE;
slouken@0
   731
		}
slouken@0
   732
		/* Finally set the transient hints if necessary */
slouken@0
   733
		if ( ! set ) {
icculus@1575
   734
			XSetTransientForHint(SDL_Display, WMwindow, SDL_Root);
slouken@0
   735
		}
slouken@0
   736
	} else {
slouken@0
   737
		SDL_bool set;
slouken@0
   738
		Atom WM_HINTS;
slouken@0
   739
slouken@0
   740
		/* We haven't modified the window manager hints yet */
slouken@0
   741
		set = SDL_FALSE;
slouken@0
   742
slouken@0
   743
		/* First try to unset MWM hints */
icculus@1575
   744
		WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True);
slouken@0
   745
		if ( WM_HINTS != None ) {
icculus@1575
   746
			XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
slouken@0
   747
			set = SDL_TRUE;
slouken@0
   748
		}
slouken@0
   749
		/* Now try to unset KWM hints */
icculus@1575
   750
		WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True);
slouken@0
   751
		if ( WM_HINTS != None ) {
icculus@1575
   752
			XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
slouken@0
   753
			set = SDL_TRUE;
slouken@0
   754
		}
slouken@0
   755
		/* Now try to unset GNOME hints */
icculus@1575
   756
		WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True);
slouken@0
   757
		if ( WM_HINTS != None ) {
icculus@1575
   758
			XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
slouken@0
   759
			set = SDL_TRUE;
slouken@0
   760
		}
slouken@0
   761
		/* Finally unset the transient hints if necessary */
slouken@0
   762
		if ( ! set ) {
slouken@0
   763
			/* NOTE: Does this work? */
icculus@1575
   764
			XSetTransientForHint(SDL_Display, WMwindow, None);
slouken@0
   765
		}
slouken@0
   766
	}
slouken@0
   767
}
slouken@0
   768
slouken@0
   769
static int X11_CreateWindow(_THIS, SDL_Surface *screen,
slouken@0
   770
			    int w, int h, int bpp, Uint32 flags)
slouken@0
   771
{
slouken@0
   772
	int i, depth;
slouken@0
   773
	Visual *vis;
slouken@0
   774
	int vis_change;
slouken@0
   775
slouken@0
   776
	/* If a window is already present, destroy it and start fresh */
slouken@0
   777
	if ( SDL_Window ) {
slouken@0
   778
		X11_DestroyWindow(this, screen);
icculus@860
   779
		switch_waiting = 0; /* Prevent jump back to now-meaningless state. */
slouken@0
   780
	}
slouken@0
   781
slouken@0
   782
	/* See if we have been given a window id */
slouken@0
   783
	if ( SDL_windowid ) {
slouken@1336
   784
		SDL_Window = SDL_strtol(SDL_windowid, NULL, 0);
slouken@0
   785
	} else {
slouken@0
   786
		SDL_Window = 0;
slouken@0
   787
	}
slouken@0
   788
slouken@0
   789
	/* find out which visual we are going to use */
slouken@0
   790
	if ( flags & SDL_OPENGL ) {
slouken@0
   791
		XVisualInfo *vi;
slouken@0
   792
slouken@0
   793
		vi = X11_GL_GetVisual(this);
slouken@0
   794
		if( !vi ) {
slouken@0
   795
			return -1;
slouken@0
   796
		}
slouken@0
   797
		vis = vi->visual;
slouken@0
   798
		depth = vi->depth;
slouken@0
   799
	} else if ( SDL_windowid ) {
slouken@0
   800
		XWindowAttributes a;
slouken@0
   801
icculus@1575
   802
		XGetWindowAttributes(SDL_Display, SDL_Window, &a);
slouken@0
   803
		vis = a.visual;
slouken@0
   804
		depth = a.depth;
slouken@0
   805
	} else {
slouken@0
   806
		for ( i = 0; i < this->hidden->nvisuals; i++ ) {
slouken@0
   807
			if ( this->hidden->visuals[i].bpp == bpp )
slouken@0
   808
				break;
slouken@0
   809
		}
slouken@0
   810
		if ( i == this->hidden->nvisuals ) {
slouken@0
   811
			SDL_SetError("No matching visual for requested depth");
slouken@0
   812
			return -1;	/* should never happen */
slouken@0
   813
		}
slouken@0
   814
		vis = this->hidden->visuals[i].visual;
slouken@0
   815
		depth = this->hidden->visuals[i].depth;
slouken@0
   816
	}
slouken@0
   817
#ifdef X11_DEBUG
slouken@0
   818
        printf("Choosing %s visual at %d bpp - %d colormap entries\n", vis->class == PseudoColor ? "PseudoColor" : (vis->class == TrueColor ? "TrueColor" : (vis->class == DirectColor ? "DirectColor" : "Unknown")), depth, vis->map_entries);
slouken@0
   819
#endif
slouken@0
   820
	vis_change = (vis != SDL_Visual);
slouken@0
   821
	SDL_Visual = vis;
slouken@0
   822
	this->hidden->depth = depth;
slouken@0
   823
slouken@0
   824
	/* Allocate the new pixel format for this video mode */
slouken@0
   825
	if ( ! SDL_ReallocFormat(screen, bpp,
slouken@0
   826
			vis->red_mask, vis->green_mask, vis->blue_mask, 0) )
slouken@0
   827
		return -1;
slouken@0
   828
slouken@0
   829
	/* Create the appropriate colormap */
slouken@0
   830
	if ( SDL_XColorMap != SDL_DisplayColormap ) {
icculus@1575
   831
		XFreeColormap(SDL_Display, SDL_XColorMap);
slouken@0
   832
	}
slouken@0
   833
	if ( SDL_Visual->class == PseudoColor ) {
slouken@0
   834
	    int ncolors;
slouken@0
   835
slouken@0
   836
	    /* Allocate the pixel flags */
slouken@0
   837
	    ncolors = SDL_Visual->map_entries;
slouken@1336
   838
	    SDL_XPixels = SDL_malloc(ncolors * sizeof(int));
slouken@0
   839
	    if(SDL_XPixels == NULL) {
slouken@0
   840
		SDL_OutOfMemory();
slouken@0
   841
		return -1;
slouken@0
   842
	    }
slouken@1336
   843
	    SDL_memset(SDL_XPixels, 0, ncolors * sizeof(*SDL_XPixels));
slouken@0
   844
slouken@0
   845
	    /* always allocate a private colormap on non-default visuals */
slouken@0
   846
	    if ( SDL_Visual != DefaultVisual(SDL_Display, SDL_Screen) ) {
slouken@0
   847
		flags |= SDL_HWPALETTE;
slouken@0
   848
	    }
slouken@0
   849
	    if ( flags & SDL_HWPALETTE ) {
slouken@0
   850
		screen->flags |= SDL_HWPALETTE;
icculus@1575
   851
		SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
slouken@0
   852
		                                SDL_Visual, AllocAll);
slouken@0
   853
	    } else {
slouken@0
   854
		SDL_XColorMap = SDL_DisplayColormap;
slouken@0
   855
	    }
slouken@0
   856
	} else if ( SDL_Visual->class == DirectColor ) {
slouken@0
   857
slouken@0
   858
	    /* Create a colormap which we can manipulate for gamma */
icculus@1575
   859
	    SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
slouken@0
   860
		                            SDL_Visual, AllocAll);
icculus@1575
   861
            XSync(SDL_Display, False);
slouken@0
   862
slouken@0
   863
	    /* Initialize the colormap to the identity mapping */
slouken@0
   864
	    SDL_GetGammaRamp(0, 0, 0);
slouken@0
   865
	    this->screen = screen;
slouken@0
   866
	    X11_SetGammaRamp(this, this->gamma);
slouken@0
   867
	    this->screen = NULL;
slouken@0
   868
	} else {
slouken@0
   869
	    /* Create a read-only colormap for our window */
icculus@1575
   870
	    SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
slouken@0
   871
	                                    SDL_Visual, AllocNone);
slouken@0
   872
	}
slouken@0
   873
slouken@0
   874
	/* Recreate the auxiliary windows, if needed (required for GL) */
slouken@0
   875
	if ( vis_change )
slouken@0
   876
	    create_aux_windows(this);
slouken@0
   877
slouken@0
   878
	if(screen->flags & SDL_HWPALETTE) {
slouken@0
   879
	    /* Since the full-screen window might have got a nonzero background
slouken@0
   880
	       colour (0 is white on some displays), we should reset the
slouken@0
   881
	       background to 0 here since that is what the user expects
slouken@0
   882
	       with a private colormap */
icculus@1575
   883
	    XSetWindowBackground(SDL_Display, FSwindow, 0);
icculus@1575
   884
	    XClearWindow(SDL_Display, FSwindow);
slouken@0
   885
	}
slouken@0
   886
slouken@0
   887
	/* resize the (possibly new) window manager window */
slouken@0
   888
	if( !SDL_windowid ) {
slouken@0
   889
	        X11_SetSizeHints(this, w, h, flags);
slouken@1545
   890
		window_w = w;
slouken@1545
   891
		window_h = h;
icculus@1575
   892
		XResizeWindow(SDL_Display, WMwindow, w, h);
slouken@0
   893
	}
slouken@0
   894
slouken@0
   895
	/* Create (or use) the X11 display window */
slouken@0
   896
	if ( !SDL_windowid ) {
slouken@0
   897
		if ( flags & SDL_OPENGL ) {
slouken@0
   898
			if ( X11_GL_CreateWindow(this, w, h) < 0 ) {
slouken@0
   899
				return(-1);
slouken@0
   900
			}
slouken@0
   901
		} else {
slouken@0
   902
			XSetWindowAttributes swa;
slouken@0
   903
slouken@0
   904
			swa.background_pixel = 0;
slouken@0
   905
			swa.border_pixel = 0;
slouken@0
   906
			swa.colormap = SDL_XColorMap;
icculus@1575
   907
			SDL_Window = XCreateWindow(SDL_Display, WMwindow,
slouken@0
   908
		                           	0, 0, w, h, 0, depth,
slouken@0
   909
		                           	InputOutput, SDL_Visual,
slouken@0
   910
		                           	CWBackPixel | CWBorderPixel
slouken@0
   911
		                           	| CWColormap, &swa);
slouken@0
   912
		}
slouken@0
   913
		/* Only manage our input if we own the window */
icculus@1575
   914
		XSelectInput(SDL_Display, SDL_Window,
slouken@0
   915
					( EnterWindowMask | LeaveWindowMask
slouken@0
   916
					| ButtonPressMask | ButtonReleaseMask
slouken@0
   917
					| PointerMotionMask | ExposureMask ));
slouken@0
   918
	}
slouken@0
   919
	/* Create the graphics context here, once we have a window */
slouken@0
   920
	if ( flags & SDL_OPENGL ) {
slouken@0
   921
		if ( X11_GL_CreateContext(this) < 0 ) {
slouken@0
   922
			return(-1);
slouken@0
   923
		} else {
slouken@0
   924
			screen->flags |= SDL_OPENGL;
slouken@0
   925
		}
slouken@0
   926
	} else {
slouken@0
   927
		XGCValues gcv;
slouken@0
   928
slouken@0
   929
		gcv.graphics_exposures = False;
icculus@1575
   930
		SDL_GC = XCreateGC(SDL_Display, SDL_Window,
slouken@0
   931
		                   GCGraphicsExposures, &gcv);
slouken@0
   932
		if ( ! SDL_GC ) {
slouken@0
   933
			SDL_SetError("Couldn't create graphics context");
slouken@0
   934
			return(-1);
slouken@0
   935
		}
slouken@0
   936
	}
slouken@0
   937
slouken@0
   938
	/* Set our colormaps when not setting a GL mode */
slouken@0
   939
	if ( ! (flags & SDL_OPENGL) ) {
icculus@1575
   940
		XSetWindowColormap(SDL_Display, SDL_Window, SDL_XColorMap);
slouken@0
   941
		if( !SDL_windowid ) {
icculus@1575
   942
		    XSetWindowColormap(SDL_Display, FSwindow, SDL_XColorMap);
icculus@1575
   943
		    XSetWindowColormap(SDL_Display, WMwindow, SDL_XColorMap);
slouken@0
   944
		}
slouken@0
   945
	}
slouken@0
   946
slouken@0
   947
#if 0 /* This is an experiment - are the graphics faster now? - nope. */
slouken@1336
   948
	if ( SDL_getenv("SDL_VIDEO_X11_BACKINGSTORE") )
slouken@0
   949
#endif
slouken@0
   950
	/* Cache the window in the server, when possible */
slouken@0
   951
	{
slouken@0
   952
		Screen *xscreen;
slouken@0
   953
		XSetWindowAttributes a;
slouken@0
   954
slouken@0
   955
		xscreen = ScreenOfDisplay(SDL_Display, SDL_Screen);
slouken@0
   956
		a.backing_store = DoesBackingStore(xscreen);
slouken@0
   957
		if ( a.backing_store != NotUseful ) {
icculus@1575
   958
			XChangeWindowAttributes(SDL_Display, SDL_Window,
slouken@0
   959
			                        CWBackingStore, &a);
slouken@0
   960
		}
slouken@0
   961
	}
slouken@0
   962
slouken@0
   963
	/* Update the internal keyboard state */
slouken@1327
   964
	X11_SetKeyboardState(SDL_Display, NULL);
slouken@0
   965
slouken@444
   966
	/* When the window is first mapped, ignore non-modifier keys */
slouken@444
   967
	{
slouken@444
   968
		Uint8 *keys = SDL_GetKeyState(NULL);
slouken@444
   969
		for ( i = 0; i < SDLK_LAST; ++i ) {
slouken@444
   970
			switch (i) {
slouken@444
   971
			    case SDLK_NUMLOCK:
slouken@444
   972
			    case SDLK_CAPSLOCK:
slouken@444
   973
			    case SDLK_LCTRL:
slouken@444
   974
			    case SDLK_RCTRL:
slouken@444
   975
			    case SDLK_LSHIFT:
slouken@444
   976
			    case SDLK_RSHIFT:
slouken@444
   977
			    case SDLK_LALT:
slouken@444
   978
			    case SDLK_RALT:
slouken@444
   979
			    case SDLK_LMETA:
slouken@444
   980
			    case SDLK_RMETA:
slouken@444
   981
			    case SDLK_MODE:
slouken@444
   982
				break;
slouken@444
   983
			    default:
slouken@444
   984
				keys[i] = SDL_RELEASED;
slouken@444
   985
				break;
slouken@444
   986
			}
slouken@444
   987
		}
slouken@444
   988
	}
slouken@444
   989
slouken@0
   990
	/* Map them both and go fullscreen, if requested */
slouken@0
   991
	if ( ! SDL_windowid ) {
icculus@1575
   992
		XMapWindow(SDL_Display, SDL_Window);
icculus@1575
   993
		XMapWindow(SDL_Display, WMwindow);
slouken@160
   994
		X11_WaitMapped(this, WMwindow);
slouken@0
   995
		if ( flags & SDL_FULLSCREEN ) {
slouken@0
   996
			screen->flags |= SDL_FULLSCREEN;
slouken@0
   997
			X11_EnterFullScreen(this);
slouken@0
   998
		} else {
slouken@0
   999
			screen->flags &= ~SDL_FULLSCREEN;
slouken@0
  1000
		}
slouken@0
  1001
	}
icculus@1178
  1002
	
slouken@0
  1003
	return(0);
slouken@0
  1004
}
slouken@0
  1005
slouken@0
  1006
static int X11_ResizeWindow(_THIS,
slouken@0
  1007
			SDL_Surface *screen, int w, int h, Uint32 flags)
slouken@0
  1008
{
slouken@0
  1009
	if ( ! SDL_windowid ) {
slouken@0
  1010
		/* Resize the window manager window */
slouken@0
  1011
		X11_SetSizeHints(this, w, h, flags);
slouken@1545
  1012
		window_w = w;
slouken@1545
  1013
		window_h = h;
icculus@1575
  1014
		XResizeWindow(SDL_Display, WMwindow, w, h);
slouken@0
  1015
slouken@0
  1016
		/* Resize the fullscreen and display windows */
slouken@0
  1017
		if ( flags & SDL_FULLSCREEN ) {
slouken@0
  1018
			if ( screen->flags & SDL_FULLSCREEN ) {
slouken@0
  1019
				X11_ResizeFullScreen(this);
slouken@0
  1020
			} else {
slouken@0
  1021
				screen->flags |= SDL_FULLSCREEN;
slouken@0
  1022
				X11_EnterFullScreen(this);
slouken@0
  1023
			}
slouken@0
  1024
		} else {
slouken@0
  1025
			if ( screen->flags & SDL_FULLSCREEN ) {
slouken@0
  1026
				screen->flags &= ~SDL_FULLSCREEN;
slouken@0
  1027
				X11_LeaveFullScreen(this);
slouken@0
  1028
			}
slouken@0
  1029
		}
icculus@1575
  1030
		XResizeWindow(SDL_Display, SDL_Window, w, h);
slouken@0
  1031
	}
slouken@0
  1032
	return(0);
slouken@0
  1033
}
slouken@0
  1034
slouken@0
  1035
SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current,
slouken@0
  1036
				int width, int height, int bpp, Uint32 flags)
slouken@0
  1037
{
slouken@0
  1038
	Uint32 saved_flags;
slouken@0
  1039
slouken@0
  1040
	/* Lock the event thread, in multi-threading environments */
slouken@0
  1041
	SDL_Lock_EventThread();
slouken@0
  1042
slouken@0
  1043
	/* Check the combination of flags we were passed */
slouken@0
  1044
	if ( flags & SDL_FULLSCREEN ) {
slouken@0
  1045
		/* Clear fullscreen flag if not supported */
slouken@0
  1046
		if ( SDL_windowid ) {
slouken@0
  1047
			flags &= ~SDL_FULLSCREEN;
slouken@0
  1048
		}
slouken@0
  1049
	}
slouken@0
  1050
slouken@0
  1051
	/* Flush any delayed updates */
icculus@1575
  1052
	XSync(GFX_Display, False);
slouken@0
  1053
slouken@0
  1054
	/* Set up the X11 window */
slouken@0
  1055
	saved_flags = current->flags;
icculus@867
  1056
	if ( (SDL_Window) && ((saved_flags&SDL_OPENGL) == (flags&SDL_OPENGL))
icculus@867
  1057
	      && (bpp == current->format->BitsPerPixel)
icculus@867
  1058
          && ((saved_flags&SDL_NOFRAME) == (flags&SDL_NOFRAME)) ) {
slouken@0
  1059
		if (X11_ResizeWindow(this, current, width, height, flags) < 0) {
slouken@0
  1060
			current = NULL;
slouken@0
  1061
			goto done;
slouken@0
  1062
		}
slouken@0
  1063
	} else {
slouken@0
  1064
		if (X11_CreateWindow(this,current,width,height,bpp,flags) < 0) {
slouken@0
  1065
			current = NULL;
slouken@0
  1066
			goto done;
slouken@0
  1067
		}
slouken@0
  1068
	}
slouken@0
  1069
slouken@0
  1070
	/* Set up the new mode framebuffer */
slouken@0
  1071
	if ( ((current->w != width) || (current->h != height)) ||
slouken@0
  1072
             ((saved_flags&SDL_OPENGL) != (flags&SDL_OPENGL)) ) {
slouken@0
  1073
		current->w = width;
slouken@0
  1074
		current->h = height;
slouken@0
  1075
		current->pitch = SDL_CalculatePitch(current);
slouken@0
  1076
		X11_ResizeImage(this, current, flags);
slouken@0
  1077
	}
slouken@0
  1078
	current->flags |= (flags&(SDL_RESIZABLE|SDL_NOFRAME));
slouken@0
  1079
slouken@0
  1080
  done:
slouken@0
  1081
	/* Release the event thread */
icculus@1575
  1082
	XSync(SDL_Display, False);
slouken@0
  1083
	SDL_Unlock_EventThread();
slouken@0
  1084
slouken@0
  1085
	/* We're done! */
slouken@0
  1086
	return(current);
slouken@0
  1087
}
slouken@0
  1088
slouken@0
  1089
static int X11_ToggleFullScreen(_THIS, int on)
slouken@0
  1090
{
slouken@0
  1091
	Uint32 event_thread;
slouken@0
  1092
slouken@0
  1093
	/* Don't switch if we don't own the window */
slouken@0
  1094
	if ( SDL_windowid ) {
slouken@0
  1095
		return(0);
slouken@0
  1096
	}
slouken@0
  1097
slouken@0
  1098
	/* Don't lock if we are the event thread */
slouken@0
  1099
	event_thread = SDL_EventThreadID();
slouken@0
  1100
	if ( event_thread && (SDL_ThreadID() == event_thread) ) {
slouken@0
  1101
		event_thread = 0;
slouken@0
  1102
	}
slouken@0
  1103
	if ( event_thread ) {
slouken@0
  1104
		SDL_Lock_EventThread();
slouken@0
  1105
	}
slouken@0
  1106
	if ( on ) {
slouken@0
  1107
		this->screen->flags |= SDL_FULLSCREEN;
slouken@0
  1108
		X11_EnterFullScreen(this);
slouken@0
  1109
	} else {
slouken@0
  1110
		this->screen->flags &= ~SDL_FULLSCREEN;
slouken@0
  1111
		X11_LeaveFullScreen(this);
slouken@0
  1112
	}
slouken@0
  1113
	X11_RefreshDisplay(this);
slouken@0
  1114
	if ( event_thread ) {
slouken@0
  1115
		SDL_Unlock_EventThread();
slouken@0
  1116
	}
slouken@0
  1117
	SDL_ResetKeyboard();
slouken@0
  1118
	return(1);
slouken@0
  1119
}
slouken@0
  1120
slouken@0
  1121
/* Update the current mouse state and position */
slouken@0
  1122
static void X11_UpdateMouse(_THIS)
slouken@0
  1123
{
slouken@0
  1124
	Window u1; int u2;
slouken@0
  1125
	Window current_win;
slouken@0
  1126
	int x, y;
slouken@0
  1127
	unsigned int mask;
slouken@0
  1128
slouken@0
  1129
	/* Lock the event thread, in multi-threading environments */
slouken@0
  1130
	SDL_Lock_EventThread();
icculus@1575
  1131
	if ( XQueryPointer(SDL_Display, SDL_Window, &u1, &current_win,
slouken@0
  1132
	                   &u2, &u2, &x, &y, &mask) ) {
slouken@0
  1133
		if ( (x >= 0) && (x < SDL_VideoSurface->w) &&
slouken@0
  1134
		     (y >= 0) && (y < SDL_VideoSurface->h) ) {
slouken@0
  1135
			SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
slouken@0
  1136
			SDL_PrivateMouseMotion(0, 0, x, y);
slouken@0
  1137
		} else {
slouken@0
  1138
			SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
slouken@0
  1139
		}
slouken@0
  1140
	}
slouken@0
  1141
	SDL_Unlock_EventThread();
slouken@0
  1142
}
slouken@0
  1143
slouken@0
  1144
/* simple colour distance metric. Supposed to be better than a plain
slouken@0
  1145
   Euclidian distance anyway. */
slouken@0
  1146
#define COLOUR_FACTOR 3
slouken@0
  1147
#define LIGHT_FACTOR 1
slouken@0
  1148
#define COLOUR_DIST(r1, g1, b1, r2, g2, b2)				\
slouken@0
  1149
	(COLOUR_FACTOR * (abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2))	\
slouken@0
  1150
	 + LIGHT_FACTOR * abs(r1 + g1 + b1 - (r2 + g2 + b2)))
slouken@0
  1151
slouken@0
  1152
static void allocate_nearest(_THIS, SDL_Color *colors,
slouken@0
  1153
			     SDL_Color *want, int nwant)
slouken@0
  1154
{
slouken@0
  1155
	/*
slouken@0
  1156
	 * There is no way to know which ones to choose from, so we retrieve
slouken@0
  1157
	 * the entire colormap and try the nearest possible, until we find one
slouken@0
  1158
	 * that is shared.
slouken@0
  1159
	 */
slouken@0
  1160
	XColor all[256];
slouken@0
  1161
	int i;
slouken@0
  1162
	for(i = 0; i < 256; i++)
slouken@0
  1163
		all[i].pixel = i;
slouken@0
  1164
	/* 
slouken@0
  1165
	 * XQueryColors sets the flags in the XColor struct, so we use
slouken@0
  1166
	 * that to keep track of which colours are available
slouken@0
  1167
	 */
icculus@1575
  1168
	XQueryColors(GFX_Display, SDL_XColorMap, all, 256);
slouken@0
  1169
slouken@0
  1170
	for(i = 0; i < nwant; i++) {
slouken@0
  1171
		XColor *c;
slouken@0
  1172
		int j;
slouken@0
  1173
		int best = 0;
slouken@0
  1174
		int mindist = 0x7fffffff;
slouken@0
  1175
		int ri = want[i].r;
slouken@0
  1176
		int gi = want[i].g;
slouken@0
  1177
		int bi = want[i].b;
slouken@0
  1178
		for(j = 0; j < 256; j++) {
slouken@0
  1179
			int rj, gj, bj, d2;
slouken@0
  1180
			if(!all[j].flags)
slouken@0
  1181
				continue;	/* unavailable colour cell */
slouken@0
  1182
			rj = all[j].red >> 8;
slouken@0
  1183
			gj = all[j].green >> 8;
slouken@0
  1184
			bj = all[j].blue >> 8;
slouken@0
  1185
			d2 = COLOUR_DIST(ri, gi, bi, rj, gj, bj);
slouken@0
  1186
			if(d2 < mindist) {
slouken@0
  1187
				mindist = d2;
slouken@0
  1188
				best = j;
slouken@0
  1189
			}
slouken@0
  1190
		}
slouken@0
  1191
		if(SDL_XPixels[best])
slouken@0
  1192
			continue; /* already allocated, waste no more time */
slouken@0
  1193
		c = all + best;
icculus@1575
  1194
		if(XAllocColor(GFX_Display, SDL_XColorMap, c)) {
slouken@0
  1195
			/* got it */
slouken@236
  1196
			colors[c->pixel].r = c->red >> 8;
slouken@236
  1197
			colors[c->pixel].g = c->green >> 8;
slouken@236
  1198
			colors[c->pixel].b = c->blue >> 8;
slouken@236
  1199
			++SDL_XPixels[c->pixel];
slouken@0
  1200
		} else {
slouken@0
  1201
			/* 
slouken@0
  1202
			 * The colour couldn't be allocated, probably being
slouken@0
  1203
			 * owned as a r/w cell by another client. Flag it as
slouken@0
  1204
			 * unavailable and try again. The termination of the
slouken@0
  1205
			 * loop is guaranteed since at least black and white
slouken@0
  1206
			 * are always there.
slouken@0
  1207
			 */
slouken@0
  1208
			c->flags = 0;
slouken@0
  1209
			i--;
slouken@0
  1210
		}
slouken@0
  1211
	}
slouken@0
  1212
}
slouken@0
  1213
slouken@0
  1214
int X11_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
slouken@0
  1215
{
slouken@0
  1216
	int nrej = 0;
slouken@0
  1217
slouken@0
  1218
	/* Check to make sure we have a colormap allocated */
slouken@0
  1219
	if ( SDL_XPixels == NULL ) {
slouken@0
  1220
		return(0);
slouken@0
  1221
	}
slouken@0
  1222
	if ( (this->screen->flags & SDL_HWPALETTE) == SDL_HWPALETTE ) {
slouken@0
  1223
	        /* private writable colormap: just set the colours we need */
slouken@0
  1224
	        XColor  *xcmap;
slouken@0
  1225
		int i;
slouken@1338
  1226
	        xcmap = SDL_stack_alloc(XColor, ncolors);
slouken@0
  1227
		if(xcmap == NULL)
slouken@0
  1228
		        return 0;
slouken@0
  1229
		for ( i=0; i<ncolors; ++i ) {
slouken@0
  1230
			xcmap[i].pixel = i + firstcolor;
slouken@0
  1231
			xcmap[i].red   = (colors[i].r<<8)|colors[i].r;
slouken@0
  1232
			xcmap[i].green = (colors[i].g<<8)|colors[i].g;
slouken@0
  1233
			xcmap[i].blue  = (colors[i].b<<8)|colors[i].b;
slouken@0
  1234
			xcmap[i].flags = (DoRed|DoGreen|DoBlue);
slouken@0
  1235
		}
icculus@1575
  1236
		XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors);
icculus@1575
  1237
		XSync(GFX_Display, False);
slouken@1338
  1238
		SDL_stack_free(xcmap);
slouken@0
  1239
	} else {
slouken@0
  1240
	        /*
slouken@0
  1241
		 * Shared colormap: We only allocate read-only cells, which
slouken@0
  1242
		 * increases the likelyhood of colour sharing with other
slouken@0
  1243
		 * clients. The pixel values will almost certainly be
slouken@0
  1244
		 * different from the requested ones, so the user has to
slouken@0
  1245
		 * walk the colormap and see which index got what colour.
slouken@0
  1246
		 *
slouken@0
  1247
		 * We can work directly with the logical palette since it
slouken@0
  1248
		 * has already been set when we get here.
slouken@0
  1249
		 */
slouken@0
  1250
		SDL_Color *want, *reject;
slouken@0
  1251
	        unsigned long *freelist;
slouken@0
  1252
		int i;
slouken@0
  1253
		int nfree = 0;
slouken@0
  1254
		int nc = this->screen->format->palette->ncolors;
slouken@0
  1255
	        colors = this->screen->format->palette->colors;
slouken@1338
  1256
		freelist = SDL_stack_alloc(unsigned long, nc);
slouken@0
  1257
		/* make sure multiple allocations of the same cell are freed */
slouken@0
  1258
	        for(i = 0; i < ncolors; i++) {
slouken@0
  1259
		        int pixel = firstcolor + i;
slouken@0
  1260
		        while(SDL_XPixels[pixel]) {
slouken@0
  1261
			        freelist[nfree++] = pixel;
slouken@0
  1262
				--SDL_XPixels[pixel];
slouken@0
  1263
			}
slouken@0
  1264
		}
icculus@1575
  1265
		XFreeColors(GFX_Display, SDL_XColorMap, freelist, nfree, 0);
slouken@1338
  1266
		SDL_stack_free(freelist);
slouken@0
  1267
slouken@1338
  1268
		want = SDL_stack_alloc(SDL_Color, ncolors);
slouken@1338
  1269
		reject = SDL_stack_alloc(SDL_Color, ncolors);
slouken@1336
  1270
		SDL_memcpy(want, colors + firstcolor, ncolors * sizeof(SDL_Color));
slouken@0
  1271
		/* make sure the user isn't fooled by her own wishes
slouken@0
  1272
		   (black is safe, always available in the default colormap) */
slouken@1336
  1273
		SDL_memset(colors + firstcolor, 0, ncolors * sizeof(SDL_Color));
slouken@0
  1274
slouken@0
  1275
		/* now try to allocate the colours */
slouken@0
  1276
		for(i = 0; i < ncolors; i++) {
slouken@0
  1277
		        XColor col;
slouken@0
  1278
			col.red = want[i].r << 8;
slouken@0
  1279
			col.green = want[i].g << 8;
slouken@0
  1280
			col.blue = want[i].b << 8;
slouken@0
  1281
			col.flags = DoRed | DoGreen | DoBlue;
icculus@1575
  1282
			if(XAllocColor(GFX_Display, SDL_XColorMap, &col)) {
slouken@0
  1283
			        /* We got the colour, or at least the nearest
slouken@0
  1284
				   the hardware could get. */
slouken@0
  1285
			        colors[col.pixel].r = col.red >> 8;
slouken@0
  1286
				colors[col.pixel].g = col.green >> 8;
slouken@0
  1287
				colors[col.pixel].b = col.blue >> 8;
slouken@0
  1288
				++SDL_XPixels[col.pixel];
slouken@0
  1289
			} else {
slouken@0
  1290
				/*
slouken@0
  1291
				 * no more free cells, add it to the list
slouken@0
  1292
				 * of rejected colours
slouken@0
  1293
				 */
slouken@0
  1294
				reject[nrej++] = want[i];
slouken@0
  1295
			}
slouken@0
  1296
		}
slouken@0
  1297
		if(nrej)
slouken@0
  1298
			allocate_nearest(this, colors, reject, nrej);
slouken@1338
  1299
		SDL_stack_free(reject);
slouken@1338
  1300
		SDL_stack_free(want);
slouken@0
  1301
	}
slouken@0
  1302
	return nrej == 0;
slouken@0
  1303
}
slouken@0
  1304
slouken@0
  1305
int X11_SetGammaRamp(_THIS, Uint16 *ramp)
slouken@0
  1306
{
slouken@0
  1307
	int i, ncolors;
slouken@0
  1308
	XColor xcmap[256];
slouken@0
  1309
slouken@0
  1310
	/* See if actually setting the gamma is supported */
slouken@0
  1311
	if ( SDL_Visual->class != DirectColor ) {
slouken@0
  1312
	    SDL_SetError("Gamma correction not supported on this visual");
slouken@0
  1313
	    return(-1);
slouken@0
  1314
	}
slouken@0
  1315
slouken@0
  1316
	/* Calculate the appropriate palette for the given gamma ramp */
slouken@0
  1317
	ncolors = SDL_Visual->map_entries;
slouken@0
  1318
	for ( i=0; i<ncolors; ++i ) {
slouken@0
  1319
		Uint8 c = (256 * i / ncolors);
slouken@0
  1320
		xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c);
slouken@0
  1321
		xcmap[i].red   = ramp[0*256+c];
slouken@0
  1322
		xcmap[i].green = ramp[1*256+c];
slouken@0
  1323
		xcmap[i].blue  = ramp[2*256+c];
slouken@0
  1324
		xcmap[i].flags = (DoRed|DoGreen|DoBlue);
slouken@0
  1325
	}
icculus@1575
  1326
	XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors);
icculus@1575
  1327
	XSync(GFX_Display, False);
slouken@0
  1328
	return(0);
slouken@0
  1329
}
slouken@0
  1330
slouken@0
  1331
/* Note:  If we are terminated, this could be called in the middle of
slouken@0
  1332
   another SDL video routine -- notably UpdateRects.
slouken@0
  1333
*/
slouken@0
  1334
void X11_VideoQuit(_THIS)
slouken@0
  1335
{
slouken@0
  1336
	/* Shutdown everything that's still up */
slouken@0
  1337
	/* The event thread should be done, so we can touch SDL_Display */
slouken@0
  1338
	if ( SDL_Display != NULL ) {
slouken@0
  1339
		/* Flush any delayed updates */
icculus@1575
  1340
		XSync(GFX_Display, False);
slouken@0
  1341
icculus@1178
  1342
		/* Close the connection with the IM server */
icculus@1178
  1343
		#ifdef X_HAVE_UTF8_STRING
icculus@1319
  1344
		if (SDL_IC != NULL) {
icculus@1575
  1345
			XDestroyIC(SDL_IC);
icculus@1178
  1346
			SDL_IC = NULL;
icculus@1178
  1347
		}
icculus@1319
  1348
		if (SDL_IM != NULL) {
icculus@1575
  1349
			XCloseIM(SDL_IM);
icculus@1178
  1350
			SDL_IM = NULL;
icculus@1178
  1351
		}
icculus@1178
  1352
		#endif
icculus@1178
  1353
slouken@0
  1354
		/* Start shutting down the windows */
slouken@0
  1355
		X11_DestroyImage(this, this->screen);
slouken@0
  1356
		X11_DestroyWindow(this, this->screen);
slouken@0
  1357
		X11_FreeVideoModes(this);
slouken@0
  1358
		if ( SDL_XColorMap != SDL_DisplayColormap ) {
icculus@1575
  1359
			XFreeColormap(SDL_Display, SDL_XColorMap);
slouken@0
  1360
		}
slouken@0
  1361
		if ( SDL_iconcolors ) {
slouken@0
  1362
			unsigned long pixel;
slouken@236
  1363
			Colormap dcmap = DefaultColormap(SDL_Display,
slouken@236
  1364
							 SDL_Screen);
slouken@236
  1365
			for(pixel = 0; pixel < 256; ++pixel) {
slouken@236
  1366
				while(SDL_iconcolors[pixel] > 0) {
icculus@1575
  1367
					XFreeColors(GFX_Display,
slouken@236
  1368
						    dcmap, &pixel, 1, 0);
slouken@0
  1369
					--SDL_iconcolors[pixel];
slouken@0
  1370
				}
slouken@0
  1371
			}
slouken@1336
  1372
			SDL_free(SDL_iconcolors);
slouken@0
  1373
			SDL_iconcolors = NULL;
slouken@0
  1374
		} 
slouken@0
  1375
		/* Restore gamma settings if they've changed */
slouken@0
  1376
		if ( SDL_GetAppState() & SDL_APPACTIVE ) {
slouken@0
  1377
			X11_SwapVidModeGamma(this);
slouken@0
  1378
		}
slouken@0
  1379
slouken@0
  1380
		/* Free that blank cursor */
slouken@0
  1381
		if ( SDL_BlankCursor != NULL ) {
slouken@0
  1382
			this->FreeWMCursor(this, SDL_BlankCursor);
slouken@0
  1383
			SDL_BlankCursor = NULL;
slouken@0
  1384
		}
slouken@0
  1385
slouken@0
  1386
		/* Close the X11 graphics connection */
slouken@0
  1387
		if ( GFX_Display != NULL ) {
icculus@1575
  1388
			XCloseDisplay(GFX_Display);
slouken@0
  1389
			GFX_Display = NULL;
slouken@0
  1390
		}
slouken@0
  1391
slouken@0
  1392
		/* Close the X11 display connection */
icculus@1575
  1393
		XCloseDisplay(SDL_Display);
slouken@0
  1394
		SDL_Display = NULL;
slouken@0
  1395
slouken@0
  1396
		/* Reset the X11 error handlers */
slouken@0
  1397
		if ( XIO_handler ) {
icculus@1575
  1398
			XSetIOErrorHandler(XIO_handler);
slouken@0
  1399
		}
slouken@0
  1400
		if ( X_handler ) {
icculus@1575
  1401
			XSetErrorHandler(X_handler);
slouken@0
  1402
		}
slouken@0
  1403
slouken@0
  1404
		/* Unload GL library after X11 shuts down */
slouken@0
  1405
		X11_GL_UnloadLibrary(this);
slouken@0
  1406
	}
slouken@0
  1407
	if ( this->screen && (this->screen->flags & SDL_HWSURFACE) ) {
slouken@0
  1408
		/* Direct screen access, no memory buffer */
slouken@0
  1409
		this->screen->pixels = NULL;
slouken@0
  1410
	}
slouken@0
  1411
}
slouken@0
  1412