aboutsummaryrefslogtreecommitdiffstats
path: root/distrib/sdl-1.2.12/src/video/x11/SDL_x11wm.c
blob: 76706b3f5a64c88bd2806b9a1680da20280b50cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2006 Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Sam Lantinga
    slouken@libsdl.org
*/
#include "SDL_config.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "SDL_version.h"
#include "SDL_timer.h"
#include "SDL_video.h"
#include "SDL_syswm.h"
#include "../SDL_pixels_c.h"
#include "../../events/SDL_events_c.h"
#include "SDL_x11modes_c.h"
#include "SDL_x11wm_c.h"

static Uint8 reverse_byte(Uint8 x)
{
	x = (x & 0xaa) >> 1 | (x & 0x55) << 1;
	x = (x & 0xcc) >> 2 | (x & 0x33) << 2;
	x = (x & 0xf0) >> 4 | (x & 0x0f) << 4;
	return x;
}

void X11_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
{
	SDL_Surface *sicon;
	XWMHints *wmhints;
	XImage *icon_image;
	Pixmap icon_pixmap;
	Pixmap mask_pixmap;
	Window icon_window = None;
	GC gc;
	XGCValues GCvalues;
	int i, dbpp;
	SDL_Rect bounds;
	Uint8 *LSBmask;
	Visual *dvis;
	char *p;
	int masksize;

	SDL_Lock_EventThread();

	/* The icon must use the default visual, depth and colormap of the
	   screen, so it might need a conversion */
	dvis = DefaultVisual(SDL_Display, SDL_Screen);
	dbpp = DefaultDepth(SDL_Display, SDL_Screen);
	for(i = 0; i < this->hidden->nvisuals; i++) {
		if(this->hidden->visuals[i].visual == dvis) {
			dbpp = this->hidden->visuals[i].bpp;
			break;
		}
	}

	/* The Visual struct is supposed to be opaque but we cheat a little */
	sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
				     dbpp,
				     dvis->red_mask, dvis->green_mask,
				     dvis->blue_mask, 0);
	if ( sicon == NULL )
		goto done;

	if(dbpp == 8) {
		/* Default visual is 8bit; we need to allocate colours from
		   the default colormap */
		SDL_Color want[256], got[256];
		int nwant;
		Colormap dcmap;
		int missing;
		dcmap = DefaultColormap(SDL_Display, SDL_Screen);
		if(icon->format->palette) {
			/* The icon has a palette as well - we just have to
			   find those colours */
			nwant = icon->format->palette->ncolors;
			SDL_memcpy(want, icon->format->palette->colors,
			       nwant * sizeof want[0]);
		} else {
			/* try the standard 6x6x6 cube for lack of better
			   ideas */
			int r, g, b, i;
			for(r = i = 0; r < 256; r += 0x33)
				for(g = 0; g < 256; g += 0x33)
					for(b = 0; b < 256; b += 0x33, i++) {
						want[i].r = r;
						want[i].g = g;
						want[i].b = b;
					}
			nwant = 216;
		}
		if(SDL_iconcolors) {
			/* free already allocated colours first */
			unsigned long freelist[512];
			int nfree = 0;
			for(i = 0; i < 256; i++) {
				while(SDL_iconcolors[i]) {
					freelist[nfree++] = i;
					SDL_iconcolors[i]--;
				}
			}
			XFreeColors(GFX_Display, dcmap, freelist, nfree, 0);
		}
		if(!SDL_iconcolors)
			SDL_iconcolors = SDL_malloc(256 * sizeof *SDL_iconcolors);
		SDL_memset(SDL_iconcolors, 0, 256 * sizeof *SDL_iconcolors);

		/* try to allocate the colours */
		SDL_memset(got, 0, sizeof got);
		missing = 0;
		for(i = 0; i < nwant; i++) {
			XColor c;
			c.red = want[i].r << 8;
			c.green = want[i].g << 8;
			c.blue = want[i].b << 8;
			c.flags = DoRed | DoGreen | DoBlue;
			if(XAllocColor(GFX_Display, dcmap, &c)) {
				/* got the colour */
				SDL_iconcolors[c.pixel]++;
				got[c.pixel] = want[i];
			} else {
				missing = 1;
			}
		}
		if(missing) {
			/* Some colours were apparently missing, so we just
			   allocate all the rest as well */
			XColor cols[256];
			for(i = 0; i < 256; i++)
				cols[i].pixel = i;
			XQueryColors(GFX_Display, dcmap, cols, 256);
			for(i = 0; i < 256; i++) {
				got[i].r = cols[i].red >> 8;
				got[i].g = cols[i].green >> 8;
				got[i].b = cols[i].blue >> 8;
				if(!SDL_iconcolors[i]) {
					if(XAllocColor(GFX_Display, dcmap,
							cols + i)) {
						SDL_iconcolors[i] = 1;
					} else {
						/* index not available */
						got[i].r = 0;
						got[i].g = 0;
						got[i].b = 0;
					}
				}
			}
		}

		SDL_SetColors(sicon, got, 0, 256);
	}

	bounds.x = 0;
	bounds.y = 0;
	bounds.w = icon->w;
	bounds.h = icon->h;
	if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 )
		goto done;

	/* We need the mask as given, except in LSBfirst format instead of
	   MSBfirst. Reverse the bits in each byte. */
	masksize = ((sicon->w + 7) >> 3) * sicon->h;
	LSBmask = SDL_malloc(masksize);
	if ( LSBmask == NULL ) {
		goto done;
	}
	SDL_memset(LSBmask, 0, masksize);
	for(i = 0; i < masksize; i++)
		LSBmask[i] = reverse_byte(mask[i]);
	mask_pixmap = XCreatePixmapFromBitmapData(SDL_Display, WMwindow,
						  (char *)LSBmask,
						  sicon->w, sicon->h,
						  1L, 0L, 1);

	/* Transfer the image to an X11 pixmap */
	icon_image = XCreateImage(SDL_Display,
				  DefaultVisual(SDL_Display, SDL_Screen),
				  DefaultDepth(SDL_Display, SDL_Screen),
				  ZPixmap, 0, sicon->pixels,
				  sicon->w, sicon->h,
				  32, 0);
	icon_image->byte_order = (SDL_BYTEORDER == SDL_BIG_ENDIAN)
		                 ? MSBFirst : LSBFirst;
	icon_pixmap = XCreatePixmap(SDL_Display, SDL_Root, sicon->w, sicon->h,
				    DefaultDepth(SDL_Display, SDL_Screen));
	gc = XCreateGC(SDL_Display, icon_pixmap, 0, &GCvalues);
	XPutImage(SDL_Display, icon_pixmap, gc, icon_image,
		  0, 0, 0, 0, sicon->w, sicon->h);
	XFreeGC(SDL_Display, gc);
	XDestroyImage(icon_image);
	SDL_free(LSBmask);
	sicon->pixels = NULL;

	/* Some buggy window managers (some versions of Enlightenment, it
	   seems) need an icon window *and* icon pixmap to work properly, while
	   it screws up others. The default is only to use a pixmap. */
	p = SDL_getenv("SDL_VIDEO_X11_ICONWIN");
	if(p && *p) {
		icon_window = XCreateSimpleWindow(SDL_Display, SDL_Root,
						  0, 0, sicon->w, sicon->h, 0,
						  CopyFromParent,
						  CopyFromParent);
		XSetWindowBackgroundPixmap(SDL_Display, icon_window,
					   icon_pixmap);
		XClearWindow(SDL_Display, icon_window);
	}

	/* Set the window icon to the icon pixmap (and icon window) */
	wmhints = XAllocWMHints();
	wmhints->flags = (IconPixmapHint | IconMaskHint);
	wmhints->icon_pixmap = icon_pixmap;
	wmhints->icon_mask = mask_pixmap;
	if(icon_window != None) {
		wmhints->flags |= IconWindowHint;
		wmhints->icon_window = icon_window;
	}
	XSetWMHints(SDL_Display, WMwindow, wmhints);
	XFree(wmhints);
	XSync(SDL_Display, False);

  done:
	SDL_Unlock_EventThread();
	SDL_FreeSurface(sicon);
}

void X11_SetCaptionNoLock(_THIS, const char *title, const char *icon)
{
	XTextProperty titleprop, iconprop;
	Status status;

#ifdef X_HAVE_UTF8_STRING
	Atom _NET_WM_NAME = 0;
	Atom _NET_WM_ICON_NAME = 0;

	/* Look up some useful Atoms */
	if (SDL_X11_HAVE_UTF8) {
		_NET_WM_NAME = XInternAtom(SDL_Display, "_NET_WM_NAME", False);
		_NET_WM_ICON_NAME = XInternAtom(SDL_Display, "_NET_WM_ICON_NAME", False);
	}
#endif

	if ( title != NULL ) {
		char *title_locale = SDL_iconv_utf8_locale(title);
		if ( !title_locale ) {
			SDL_OutOfMemory();
			return;
		}
		status = XStringListToTextProperty(&title_locale, 1, &titleprop);
		SDL_free(title_locale);
		if ( status ) {
			XSetTextProperty(SDL_Display, WMwindow, &titleprop, XA_WM_NAME);
			XFree(titleprop.value);
		}
#ifdef X_HAVE_UTF8_STRING
		if (SDL_X11_HAVE_UTF8) {
			status = Xutf8TextListToTextProperty(SDL_Display,
					(char **)&title, 1, XUTF8StringStyle, &titleprop);
			if ( status == Success ) {
				XSetTextProperty(SDL_Display, WMwindow, &titleprop, _NET_WM_NAME);
				XFree(titleprop.value);
			}
		}
#endif
	}
	if ( icon != NULL ) {
		char *icon_locale = SDL_iconv_utf8_locale(icon);
		if ( !icon_locale ) {
			SDL_OutOfMemory();
			return;
		}
		status = XStringListToTextProperty(&icon_locale, 1, &iconprop);
		SDL_free(icon_locale);
		if ( status ) {
			XSetTextProperty(SDL_Display, WMwindow, &iconprop, XA_WM_ICON_NAME);
			XFree(iconprop.value);
		}
#ifdef X_HAVE_UTF8_STRING
		if (SDL_X11_HAVE_UTF8) {
			status = Xutf8TextListToTextProperty(SDL_Display,
					(char **)&icon, 1, XUTF8StringStyle, &iconprop);
			if ( status == Success ) {
				XSetTextProperty(SDL_Display, WMwindow, &iconprop, _NET_WM_ICON_NAME);
				XFree(iconprop.value);
			}
		}
#endif
	}
	XSync(SDL_Display, False);
}

void X11_SetCaption(_THIS, const char *title, const char *icon)
{
	SDL_Lock_EventThread();
	X11_SetCaptionNoLock(this, title, icon);
	SDL_Unlock_EventThread();
}

/* Iconify the window */
int X11_IconifyWindow(_THIS)
{
	int result;

	SDL_Lock_EventThread();
	result = XIconifyWindow(SDL_Display, WMwindow, SDL_Screen);
	XSync(SDL_Display, False);
	SDL_Unlock_EventThread();
	return(result);
}

#if 0
#define  D(...)  printf(__VA_ARGS__)
#define  E(...)  D(__VA_ARGS__)
#else
#define  D(...)  ((void)0)
#define  E(...)  ((void)0)
#endif

static void  set_window_pos_nolock(_THIS, int x, int y)
{
    int          xNew, yNew;
    Window       child;
    int          xAdjust = X11_wmXAdjust;
    int          yAdjust = X11_wmYAdjust;

    /* don't do anything in full-screen mode, because the FSwindow is used
     * instead of the WMwindow, which will make the adjustment go wild
     */
    if (this->screen->flags & SDL_FULLSCREEN)
        return;

    /* this code is tricky because some window managers, but not all,
     * will translate the final window position by a given offset
     * corresponding to the frame decoration.
     *
     * so we first try to move the window, get the position that the
     * window manager has set, and if they are different, re-position the
     * window again with an adjustment.
     *
     * this causes a slight flicker since the window 'jumps' very
     * quickly from one position to the other.
     */

    D("%s: move to [%d,%d] adjusted to [%d,%d]\n", __FUNCTION__,
      x, y, x+xAdjust, y+yAdjust);
    XMoveWindow(SDL_Display, WMwindow, x + xAdjust, y + yAdjust);
    XSync(SDL_Display, True);
    XTranslateCoordinates( SDL_Display, WMwindow, SDL_Root, 0, 0, &xNew, &yNew, &child );
    if (xNew != x || yNew != y) {
        X11_wmXAdjust = xAdjust = x - xNew;
        X11_wmYAdjust = yAdjust = y - yNew;
        D("%s: read pos [%d,%d], recomputing adjust=[%d,%d] moving to [%d,%d]\n",
          __FUNCTION__, xNew, yNew, xAdjust, yAdjust, x+xAdjust, y+yAdjust);
        XMoveWindow(SDL_Display, WMwindow, x + xAdjust, y + yAdjust );
    }
    XSync(SDL_Display, False);
}

/* Set window position */
void  X11_SetWindowPos(_THIS, int  x, int  y)
{
    SDL_Lock_EventThread();
    set_window_pos_nolock(this, x, y);
    SDL_Unlock_EventThread();
}

/* Get window position */
void  X11_GetWindowPos(_THIS, int  *px, int  *py)
{
    /* in full-screen mode, you can't move the window */
    if (this->screen->flags & SDL_FULLSCREEN) {
        *px = *py = 0;
        return;
    }


    SDL_Lock_EventThread();
    {
        Window  child;

        XTranslateCoordinates( SDL_Display, WMwindow, SDL_Root, 0, 0, px, py, &child );
    }
    SDL_Unlock_EventThread();
}

static int
is_window_visible(_THIS, int  screen_x, int  screen_y, int  screen_w, int  screen_h )
{
    XWindowAttributes   attr;
    int                 x, y;
    Window              child;

    XGetWindowAttributes( SDL_Display, WMwindow, &attr );
    XTranslateCoordinates( SDL_Display, WMwindow, SDL_Root, 0, 0, &x, &y, &child );

    return ( x >= screen_x && x + attr.width  <= screen_x + screen_w  &&
             y >= screen_y && y + attr.height <= screen_y + screen_h );
}

int  X11_IsWindowVisible(_THIS, int  recenter)
{
    int                 result = 0;
    XWindowAttributes   attr;
    int                 screen_w, screen_h;

    SDL_Lock_EventThread();
    XGetWindowAttributes( SDL_Display, SDL_Root, &attr );
    screen_w = attr.width;
    screen_h = attr.height;

#if SDL_VIDEO_DRIVER_X11_XINERAMA
    if (use_xinerama) {
        SDL_NAME(XineramaScreenInfo) *xinerama;
        int                           i, screens;

        xinerama = SDL_NAME(XineramaQueryScreens)(SDL_Display, &screens);
        for (i = 0; i < screens; i++) {
            if ( is_window_visible( this,
                                    xinerama[i].x_org, xinerama[i].y_org,
                                    xinerama[i].width, xinerama[i].height ) )
            {
                result = 1;
                break;
            }
        }

        if ( !result && recenter ) {
            set_window_pos_nolock(this,
                              xinerama[0].x_org + (xinerama[0].width  - this->screen->w)/2,
                              xinerama[0].y_org + (xinerama[0].height - this->screen->h)/2 );
        }
        XFree(xinerama);
        goto Exit;
    }
#endif
    if ( is_window_visible( this, 0, 0, screen_w, screen_h ) ) {
        result = 1;
    }

    if ( !result && recenter ) {
        set_window_pos_nolock( this,
                          (screen_w - this->screen->w)/2,
                          (screen_h - this->screen->h)/2 );
    }
#ifdef SDL_VIDEO_DRIVER_X11_XINERAMA
Exit:
#endif
    SDL_Unlock_EventThread();
    return result;
}

SDL_GrabMode X11_GrabInputNoLock(_THIS, SDL_GrabMode mode)
{
	int result;

	if ( this->screen == NULL ) {
		return(SDL_GRAB_OFF);
	}
	if ( ! SDL_Window ) {
		return(mode);	/* Will be set later on mode switch */
	}
	if ( mode == SDL_GRAB_OFF ) {
		XUngrabPointer(SDL_Display, CurrentTime);
		XUngrabKeyboard(SDL_Display, CurrentTime);
	} else {
		if ( this->screen->flags & SDL_FULLSCREEN ) {
			/* Unbind the mouse from the fullscreen window */
			XUngrabPointer(SDL_Display, CurrentTime);
		}
		/* Try to grab the mouse */
#if 0 /* We'll wait here until we actually grab, otherwise behavior undefined */
		for ( numtries = 0; numtries < 10; ++numtries ) {
#else
		for ( ; ; ) {
#endif
			result = XGrabPointer(SDL_Display, SDL_Window, True, 0,
						GrabModeAsync, GrabModeAsync,
						SDL_Window, None, CurrentTime);
			if ( result == GrabSuccess ) {
				break;
			}
			SDL_Delay(100);
		}
		if ( result != GrabSuccess ) {
			/* Uh, oh, what do we do here? */ ;
		}
		/* Now grab the keyboard */
		XGrabKeyboard(SDL_Display, WMwindow, True,
				GrabModeAsync, GrabModeAsync, CurrentTime);

		/* Raise the window if we grab the mouse */
		if ( !(this->screen->flags & SDL_FULLSCREEN) )
			XRaiseWindow(SDL_Display, WMwindow);

		/* Make sure we register input focus */
		SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
		/* Since we grabbed the pointer, we have mouse focus, too. */
		SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
	}
	XSync(SDL_Display, False);

	return(mode);
}

SDL_GrabMode X11_GrabInput(_THIS, SDL_GrabMode mode)
{
	SDL_Lock_EventThread();
	mode = X11_GrabInputNoLock(this, mode);
	SDL_Unlock_EventThread();

	return(mode);
}

#define  MM_PER_INCH  25.4

int
X11_GetMonitorDPI(_THIS, int  *px_dpi, int *py_dpi)
{
    Display*      display = SDL_Display;
    int           screen  = XDefaultScreen(display);
    int           xdpi, ydpi;

    int  width     = XDisplayWidth(display, screen);
    int  width_mm  = XDisplayWidthMM(display, screen);
    int  height    = XDisplayHeight(display, screen);
    int  height_mm = XDisplayHeightMM(display, screen);

    if (width_mm <= 0 || height_mm <= 0) {
        return -1;
    }

    xdpi = (int)(width  * MM_PER_INCH / width_mm + 0.5);
    ydpi = (int)(height * MM_PER_INCH / height_mm + 0.5);

    if (xdpi < 20 || xdpi > 400 || ydpi < 20 || ydpi > 400) {
        return -1;
    }

    *px_dpi = xdpi;
    *py_dpi = ydpi;

    return 0;
}

int
X11_GetMonitorRect(_THIS, SDL_Rect *rect)
{
    Display*  display = SDL_Display;
    int       screen  = XDefaultScreen(display);

    rect->x = 0;
    rect->y = 0;
    rect->w = XDisplayWidth(display, screen);
    rect->h = XDisplayHeight(display, screen);

    return 0;
}

/* If 'info' is the right version, this function fills it and returns 1.
   Otherwise, in case of a version mismatch, it returns -1.
*/
static void lock_display(void)
{
	SDL_Lock_EventThread();
}
static void unlock_display(void)
{
	/* Make sure any X11 transactions are completed */
	SDL_VideoDevice *this = current_video;
	XSync(SDL_Display, False);
	SDL_Unlock_EventThread();
}

#include <stdio.h>
int X11_GetWMInfo(_THIS, SDL_SysWMinfo *info)
{
	if ( info->version.major <= SDL_MAJOR_VERSION ) {
		info->subsystem = SDL_SYSWM_X11;
		info->info.x11.display = SDL_Display;
		info->info.x11.window = SDL_Window;
		if ( SDL_VERSIONNUM(info->version.major,
		                    info->version.minor,
		                    info->version.patch) >= 1002 ) {
			info->info.x11.fswindow = FSwindow;
			info->info.x11.wmwindow = WMwindow;
		}


		if ( SDL_VERSIONNUM(info->version.major,
		                    info->version.minor,
		                    info->version.patch) >= 1212 ) {
			info->info.x11.gfxdisplay = GFX_Display;
		}

		info->info.x11.lock_func = lock_display;
		info->info.x11.unlock_func = unlock_display;
		return(1);
	} else {
		SDL_SetError("Application not compiled with SDL %d.%d\n",
					SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
		return(-1);
	}
}