f95c3da99e479ff9ce400a5b9fad1725d18c3dc7
[rocksndiamonds.git] / src / libgame / x11.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2006 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * x11.c                                                    *
12 ***********************************************************/
13
14 #include "system.h"
15 #include "pcx.h"
16 #include "misc.h"
17 #include "setup.h"
18
19
20 #if defined(TARGET_X11)
21
22 static void X11InitDisplay();
23 static DrawWindow *X11InitWindow();
24
25 static int X11DebugErrorHandler(Display *display, XErrorEvent *event)
26 {
27   int x = 0;
28
29   return 1 / x;         /* !!! crash program to give backtrace in gdb !!! */
30 }
31
32 void X11InitVideoDisplay(void)
33 {
34   /* initialize X11 video */
35   X11InitDisplay();
36
37   /* set default X11 depth */
38   video.default_depth = XDefaultDepth(display, screen);
39 }
40
41 void X11InitVideoBuffer(DrawBuffer **backbuffer, DrawWindow **window)
42 {
43   if (*window != NULL)
44     X11CloseWindow(*window);
45
46   *window = X11InitWindow();
47
48   XMapWindow(display, (*window)->drawable);
49
50   FlushDisplay();
51
52   /* create additional (off-screen) buffer for double-buffering */
53 #if 1
54   ReCreateBitmap(backbuffer, video.width, video.height, video.depth);
55 #else
56   *backbuffer = CreateBitmap(video.width, video.height, video.depth);
57 #endif
58 }
59
60 static void X11InitDisplay()
61 {
62 #if !defined(PLATFORM_MSDOS)
63   XVisualInfo vinfo_template, *vinfo;
64   int num_visuals;
65 #endif
66   unsigned int depth;
67
68   /* connect to X server */
69   if (!(display = XOpenDisplay(options.display_name)))
70     Error(ERR_EXIT, "cannot connect to X server %s",
71           XDisplayName(options.display_name));
72
73   if (options.debug_x11_sync)
74   {
75     Error(ERR_WARN, "running in X11 synchronous mode (debug only)");
76
77     XSynchronize(display, True);
78     XSetErrorHandler(X11DebugErrorHandler);
79   }
80
81   screen = DefaultScreen(display);
82   visual = DefaultVisual(display, screen);
83   depth  = DefaultDepth(display, screen);
84   cmap   = DefaultColormap(display, screen);
85
86 #if !defined(PLATFORM_MSDOS)
87   /* look for good enough visual */
88   vinfo_template.screen = screen;
89   vinfo_template.class = (depth == 8 ? PseudoColor : TrueColor);
90   vinfo_template.depth = depth;
91   if ((vinfo = XGetVisualInfo(display, VisualScreenMask | VisualClassMask |
92                               VisualDepthMask, &vinfo_template, &num_visuals)))
93   {
94     visual = vinfo->visual;
95     XFree((void *)vinfo);
96   }
97
98   /* got appropriate visual? */
99   if (depth < 8)
100     Error(ERR_EXIT, "X11 display not supported (less than 8 bits per pixel)");
101   else if ((depth ==8 && visual->class != PseudoColor) ||
102            (depth > 8 && visual->class != TrueColor &&
103             visual->class != DirectColor))
104     Error(ERR_EXIT, "X11 display not supported (inappropriate visual)");
105 #endif /* !PLATFORM_MSDOS */
106 }
107
108 static DrawWindow *X11InitWindow()
109 {
110   DrawWindow *new_window = CreateBitmapStruct();
111   unsigned int border_width = 4;
112   XGCValues gc_values;
113   unsigned long gc_valuemask;
114 #if !defined(PLATFORM_MSDOS)
115   XTextProperty windowName, iconName;
116   Pixmap icon_pixmap, iconmask_pixmap;
117   unsigned int icon_width, icon_height;
118   int icon_hot_x, icon_hot_y;
119   XSizeHints size_hints;
120   XWMHints wm_hints;
121   XClassHint class_hints;
122   char *window_name = program.window_title;
123   char *icon_name = program.window_title;
124   long window_event_mask;
125   Atom proto_atom = None, delete_atom = None;
126 #endif
127   int screen_width, screen_height;
128   int win_xpos, win_ypos;
129   unsigned long pen_fg = WhitePixel(display, screen);
130   unsigned long pen_bg = BlackPixel(display, screen);
131   const int width = video.width, height = video.height;
132   int i;
133
134   screen_width = XDisplayWidth(display, screen);
135   screen_height = XDisplayHeight(display, screen);
136
137   win_xpos = (screen_width - width) / 2;
138   win_ypos = (screen_height - height) / 2;
139
140   new_window->width = width;
141   new_window->height = height;
142
143   new_window->drawable = XCreateSimpleWindow(display,
144                                              RootWindow(display, screen),
145                                              win_xpos, win_ypos,
146                                              width, height, border_width,
147                                              pen_fg, pen_bg);
148
149 #if !defined(PLATFORM_MSDOS)
150   proto_atom = XInternAtom(display, "WM_PROTOCOLS", FALSE);
151   delete_atom = XInternAtom(display, "WM_DELETE_WINDOW", FALSE);
152   if ((proto_atom != None) && (delete_atom != None))
153     XChangeProperty(display, new_window->drawable, proto_atom, XA_ATOM, 32,
154                     PropModePrepend, (unsigned char *) &delete_atom, 1);
155
156   if (XReadBitmapFile(display, new_window->drawable,
157                       getCustomImageFilename(program.x11_icon_filename),
158                       &icon_width, &icon_height, &icon_pixmap,
159                       &icon_hot_x, &icon_hot_y) != BitmapSuccess)
160     Error(ERR_EXIT, "cannot read icon bitmap file '%s'",
161           program.x11_icon_filename);
162
163   if (XReadBitmapFile(display, new_window->drawable,
164                       getCustomImageFilename(program.x11_iconmask_filename),
165                       &icon_width, &icon_height, &iconmask_pixmap,
166                       &icon_hot_x, &icon_hot_y) != BitmapSuccess)
167     Error(ERR_EXIT, "cannot read icon bitmap file '%s'",
168           program.x11_iconmask_filename);
169
170   size_hints.width  = size_hints.min_width  = size_hints.max_width  = width;
171   size_hints.height = size_hints.min_height = size_hints.max_height = height;
172   size_hints.flags = PSize | PMinSize | PMaxSize;
173
174   if (win_xpos || win_ypos)
175   {
176     size_hints.x = win_xpos;
177     size_hints.y = win_ypos;
178     size_hints.flags |= PPosition;
179   }
180
181   if (!XStringListToTextProperty(&window_name, 1, &windowName))
182     Error(ERR_EXIT, "structure allocation for windowName failed");
183
184   if (!XStringListToTextProperty(&icon_name, 1, &iconName))
185     Error(ERR_EXIT, "structure allocation for iconName failed");
186
187   wm_hints.initial_state = NormalState;
188   wm_hints.input = True;
189   wm_hints.icon_pixmap = icon_pixmap;
190   wm_hints.icon_mask = iconmask_pixmap;
191   wm_hints.flags = StateHint | IconPixmapHint | IconMaskHint | InputHint;
192
193   class_hints.res_name = program.command_basename;
194   class_hints.res_class = program.program_title;
195
196   XSetWMProperties(display, new_window->drawable, &windowName, &iconName, 
197                    NULL, 0, &size_hints, &wm_hints, 
198                    &class_hints);
199
200   XFree(windowName.value);
201   XFree(iconName.value);
202
203   /* Select event types wanted */
204   window_event_mask =
205     ExposureMask | StructureNotifyMask | FocusChangeMask |
206     ButtonPressMask | ButtonReleaseMask |
207     PointerMotionMask | PointerMotionHintMask |
208     KeyPressMask | KeyReleaseMask;
209
210   XSelectInput(display, new_window->drawable, window_event_mask);
211 #endif
212
213   /* create GC for drawing with window depth and background color (black) */
214   gc_values.graphics_exposures = False;
215   gc_values.foreground = pen_bg;
216   gc_values.background = pen_bg;
217   gc_valuemask = GCGraphicsExposures | GCForeground | GCBackground;
218   new_window->gc =
219     XCreateGC(display, new_window->drawable, gc_valuemask, &gc_values);
220
221   /* create GCs for line drawing (black and white) */
222   for (i = 0; i < 2; i++)
223   {
224     gc_values.graphics_exposures = False;
225     gc_values.foreground = (i ? pen_fg : pen_bg);
226     gc_values.background = pen_bg;
227     gc_values.line_width = 4;
228     gc_values.line_style = LineSolid;
229     gc_values.cap_style = CapRound;
230     gc_values.join_style = JoinRound;
231
232     gc_valuemask = GCGraphicsExposures | GCForeground | GCBackground |
233                    GCLineWidth | GCLineStyle | GCCapStyle | GCJoinStyle;
234     new_window->line_gc[i] =
235       XCreateGC(display, new_window->drawable, gc_valuemask, &gc_values);
236   }
237
238   return new_window;
239 }
240
241 void X11CloseWindow(DrawWindow *window)
242 {
243   if (window->drawable)
244   {
245     XUnmapWindow(display, window->drawable);
246     XDestroyWindow(display, window->drawable);
247   }
248
249   if (window->gc)
250     XFreeGC(display, window->gc);
251
252   free(window);
253 }
254
255 void X11ZoomBitmap(Bitmap *src_bitmap, Bitmap *dst_bitmap)
256 {
257 #if defined(TARGET_ALLEGRO)
258   AllegroZoomBitmap(src_bitmap->drawable, dst_bitmap->drawable,
259                     src_bitmap->width, src_bitmap->height,
260                     dst_bitmap->width, dst_bitmap->height);
261 #else
262   ZoomPixmap(display, src_bitmap->gc,
263              src_bitmap->drawable, dst_bitmap->drawable,
264              src_bitmap->width, src_bitmap->height,
265              dst_bitmap->width, dst_bitmap->height);
266 #endif
267 }
268
269 static void SetImageDimensions(Bitmap *bitmap)
270 {
271 #if defined(TARGET_ALLEGRO)
272   BITMAP *allegro_bitmap = (BITMAP *)(bitmap->drawable);
273
274   bitmap->width  = allegro_bitmap->w;
275   bitmap->height = allegro_bitmap->h;
276 #else
277   Window root;
278   int x, y;
279   unsigned int border_width, depth;
280
281   XGetGeometry(display, bitmap->drawable, &root, &x, &y,
282                &bitmap->width, &bitmap->height, &border_width, &depth);
283 #endif
284 }
285
286 Bitmap *X11LoadImage(char *filename)
287 {
288   Bitmap *new_bitmap = CreateBitmapStruct();
289   char *error = "Read_PCX_to_Pixmap(): %s '%s'";
290   int pcx_err;
291   XGCValues clip_gc_values;
292   unsigned long clip_gc_valuemask;
293
294   pcx_err = Read_PCX_to_Pixmap(display, window->drawable, window->gc, filename,
295                                &new_bitmap->drawable, &new_bitmap->clip_mask);
296   switch(pcx_err)
297   {
298     case PCX_Success:
299       break;
300     case PCX_OpenFailed:
301       SetError(error, "cannot open PCX file", filename);
302       return NULL;
303     case PCX_ReadFailed:
304       SetError(error, "cannot read PCX file", filename);
305       return NULL;
306     case PCX_FileInvalid:
307       SetError(error, "invalid PCX file", filename);
308       return NULL;
309     case PCX_NoMemory:
310       SetError(error, "not enough memory for PCX file", filename);
311       return NULL;
312     case PCX_ColorFailed:
313       SetError(error, "cannot get colors for PCX file", filename);
314       return NULL;
315     case PCX_OtherError:
316       /* this should already have called SetError() */
317       return NULL;
318     default:
319       SetError(error, "unknown error reading PCX file", filename);
320       return NULL;
321   }
322
323   if (!new_bitmap->drawable)
324   {
325     SetError("X11LoadImage(): cannot get graphics for '%s'", filename);
326     return NULL;
327   }
328
329   if (!new_bitmap->clip_mask)
330   {
331     SetError("X11LoadImage(): cannot get clipmask for '%s'", filename);
332     return NULL;
333   }
334
335   clip_gc_values.graphics_exposures = False;
336   clip_gc_values.clip_mask = new_bitmap->clip_mask;
337   clip_gc_valuemask = GCGraphicsExposures | GCClipMask;
338   new_bitmap->stored_clip_gc = XCreateGC(display, window->drawable,
339                                          clip_gc_valuemask, &clip_gc_values);
340
341   /* set GraphicContext inheritated from Window */
342   new_bitmap->gc = window->gc;
343
344   /* set image width and height */
345   SetImageDimensions(new_bitmap);
346
347   return new_bitmap;
348 }
349
350 void X11CreateBitmapContent(Bitmap *new_bitmap,
351                             int width, int height, int depth)
352 {
353   Pixmap pixmap;
354
355   if ((pixmap = XCreatePixmap(display, window->drawable, width, height, depth))
356       == None)
357     Error(ERR_EXIT, "cannot create pixmap");
358
359   new_bitmap->drawable = pixmap;
360
361   if (window == NULL)
362     Error(ERR_EXIT, "Window GC needed for Bitmap -- create Window first");
363
364   new_bitmap->gc = window->gc;
365
366   new_bitmap->line_gc[0] = window->line_gc[0];
367   new_bitmap->line_gc[1] = window->line_gc[1];
368 }
369
370 void X11FreeBitmapPointers(Bitmap *bitmap)
371 {
372   /* The X11 version seems to have a memory leak here -- although
373      "XFreePixmap()" is called, the corresponding memory seems not
374      to be freed (according to "ps"). The SDL version apparently
375      does not have this problem. */
376
377   if (bitmap->drawable)
378     XFreePixmap(display, bitmap->drawable);
379   if (bitmap->clip_mask)
380     XFreePixmap(display, bitmap->clip_mask);
381   if (bitmap->stored_clip_gc)
382     XFreeGC(display, bitmap->stored_clip_gc);
383   /* the other GCs are only pointers to GCs used elsewhere */
384   bitmap->drawable = None;
385   bitmap->clip_mask = None;
386   bitmap->stored_clip_gc = None;
387 }
388
389 void X11CopyArea(Bitmap *src_bitmap, Bitmap *dst_bitmap,
390                  int src_x, int src_y, int width, int height,
391                  int dst_x, int dst_y, int mask_mode)
392 {
393   XCopyArea(display, src_bitmap->drawable, dst_bitmap->drawable,
394             (mask_mode == BLIT_MASKED ? src_bitmap->clip_gc : dst_bitmap->gc),
395             src_x, src_y, width, height, dst_x, dst_y);
396 }
397
398 void X11FillRectangle(Bitmap *bitmap, int x, int y,
399                       int width, int height, Pixel color)
400 {
401   XSetForeground(display, bitmap->gc, color);
402   XFillRectangle(display, bitmap->drawable, bitmap->gc, x, y, width, height);
403 }
404
405 void X11FadeRectangle(Bitmap *bitmap_cross, int x, int y, int width, int height,
406                       int fade_mode, int fade_delay, int post_delay,
407                       void (*draw_border_function)(void))
408 {
409   /* fading currently not supported -- simply copy backbuffer to screen */
410
411   if (fade_mode == FADE_MODE_FADE_OUT)
412     X11FillRectangle(backbuffer, x, y, width, height, BLACK_PIXEL);
413
414   if (draw_border_function != NULL)
415     draw_border_function();
416
417   X11CopyArea(backbuffer, window, x, y, width, height, x, y, BLIT_OPAQUE);
418
419   /* as we currently cannot use the fade delay, also do not use post delay */
420 }
421
422 void X11DrawSimpleLine(Bitmap *bitmap, int from_x, int from_y,
423                        int to_x, int to_y, Pixel color)
424 {
425   XSetForeground(display, bitmap->gc, color);
426   XDrawLine(display, bitmap->drawable, bitmap->gc, from_x, from_y, to_x, to_y);
427 }
428
429 Pixel X11GetPixel(Bitmap *bitmap, int x, int y)
430 {
431   XImage *pixel_image;
432   Pixel pixel_value;
433
434   pixel_image = XGetImage(display, bitmap->drawable, x, y, 1, 1,
435                           AllPlanes, ZPixmap);
436   pixel_value = XGetPixel(pixel_image, 0, 0);
437
438   X11DestroyImage(pixel_image);
439
440   return pixel_value;
441 }
442
443 #if defined(TARGET_X11_NATIVE)
444 Pixel X11GetPixelFromRGB(unsigned int color_r, unsigned int color_g,
445                          unsigned int color_b)
446 {
447   XColor xcolor;
448   Pixel pixel;
449
450   xcolor.flags = DoRed | DoGreen | DoBlue;
451   xcolor.red = (color_r << 8);
452   xcolor.green = (color_g << 8);
453   xcolor.blue = (color_b << 8);
454
455   XAllocColor(display, cmap, &xcolor);
456   pixel = xcolor.pixel;
457
458   return pixel;
459 }
460 #endif  /* TARGET_X11_NATIVE */
461
462 void X11DestroyImage(XImage *ximage)
463 {
464 #if defined(TARGET_X11_NATIVE)
465   /* this seems to be needed for OS/2, but does not hurt on other platforms */
466   if (ximage->data != NULL)
467   {
468     free(ximage->data);
469     ximage->data = NULL;
470   }
471 #endif  /* TARGET_X11_NATIVE */
472
473   XDestroyImage(ximage);
474 }
475
476
477 /* ------------------------------------------------------------------------- */
478 /* mouse pointer functions                                                   */
479 /* ------------------------------------------------------------------------- */
480
481 #if defined(TARGET_X11_NATIVE)
482
483 static Cursor create_cursor(struct MouseCursorInfo *cursor_info)
484 {
485   Pixmap pixmap_data, pixmap_mask;
486   XColor color_fg, color_bg;
487   Cursor cursor;
488
489   /* shape and mask are single plane pixmaps */
490   pixmap_data =
491     XCreatePixmapFromBitmapData(display, window->drawable, cursor_info->data,
492                                 cursor_info->width, cursor_info->height,
493                                 1, 0, 1);
494   pixmap_mask =
495     XCreatePixmapFromBitmapData(display, window->drawable, cursor_info->mask,
496                                 cursor_info->width, cursor_info->height,
497                                 1, 0, 1);
498
499   XParseColor(display, cmap, "black", &color_fg);
500   XParseColor(display, cmap, "white", &color_bg);
501
502   cursor = XCreatePixmapCursor(display, pixmap_data, pixmap_mask,
503                                &color_fg, &color_bg,
504                                cursor_info->hot_x, cursor_info->hot_y);
505
506   return cursor;
507 }
508
509 void X11SetMouseCursor(struct MouseCursorInfo *cursor_info)
510 {
511   static struct MouseCursorInfo *last_cursor_info = NULL;
512   static Cursor cursor_default = None;
513   static Cursor cursor_current = None;
514
515   if (cursor_info != NULL && cursor_info != last_cursor_info)
516   {
517     cursor_current = create_cursor(cursor_info);
518     last_cursor_info = cursor_info;
519   }
520
521   XDefineCursor(display, window->drawable,
522                 cursor_info ? cursor_current : cursor_default);
523 }
524 #endif  /* TARGET_X11_NATIVE */
525
526 #endif /* TARGET_X11 */