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