rnd-19990604-1-src
[rocksndiamonds.git] / src / misc.c
1 /***********************************************************
2 *  Rocks'n'Diamonds -- McDuffin Strikes Back!              *
3 *----------------------------------------------------------*
4 *  (c) 1995-98 Artsoft Entertainment                       *
5 *              Holger Schemel                              *
6 *              Oststrasse 11a                              *
7 *              33604 Bielefeld                             *
8 *              phone: ++49 +521 290471                     *
9 *              email: aeglos@valinor.owl.de                *
10 *----------------------------------------------------------*
11 *  misc.c                                                  *
12 ***********************************************************/
13
14 #include <pwd.h>
15 #include <unistd.h>
16 #include <time.h>
17 #include <sys/time.h>
18 #include <sys/param.h>
19 #include <sys/types.h>
20 #include <stdarg.h>
21 #include <ctype.h>
22
23 #include "misc.h"
24 #include "init.h"
25 #include "tools.h"
26 #include "sound.h"
27 #include "random.h"
28 #include "joystick.h"
29 #include "files.h"
30
31 #ifdef MSDOS
32 volatile unsigned long counter = 0;
33
34 void increment_counter()
35 {
36   counter++;
37 }
38
39 END_OF_FUNCTION(increment_counter);
40 #endif
41
42
43
44 /* maximal allowed length of a command line option */
45 #define MAX_OPTION_LEN          256
46
47 #ifndef MSDOS
48 static unsigned long mainCounter(int mode)
49 {
50   static struct timeval base_time = { 0, 0 };
51   struct timeval current_time;
52   unsigned long counter_ms;
53
54   gettimeofday(&current_time, NULL);
55
56   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
57     base_time = current_time;
58
59   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
60              + (current_time.tv_usec - base_time.tv_usec) / 1000;
61
62   return counter_ms;            /* return milliseconds since last init */
63 }
64 #endif
65
66 void InitCounter()              /* set counter back to zero */
67 {
68 #ifndef MSDOS
69   mainCounter(INIT_COUNTER);
70 #else
71   LOCK_VARIABLE(counter);
72   LOCK_FUNCTION(increment_counter);
73   install_int_ex(increment_counter, BPS_TO_TIMER(100));
74 #endif
75 }
76
77 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
78 {
79 #ifndef MSDOS
80   return mainCounter(READ_COUNTER);
81 #else
82   return (counter * 10);
83 #endif
84 }
85
86 static void sleep_milliseconds(unsigned long milliseconds_delay)
87 {
88   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
89
90 #ifdef MSDOS
91   /* donĂ¯t use select() to perform waiting operations under DOS/Windows
92      environment; always use a busy loop for waiting instead */
93   do_busy_waiting = TRUE;
94 #endif
95
96   if (do_busy_waiting)
97   {
98     /* we want to wait only a few ms -- if we assume that we have a
99        kernel timer resolution of 10 ms, we would wait far to long;
100        therefore it's better to do a short interval of busy waiting
101        to get our sleeping time more accurate */
102
103     unsigned long base_counter = Counter(), actual_counter = Counter();
104
105     while (actual_counter < base_counter + milliseconds_delay &&
106            actual_counter >= base_counter)
107       actual_counter = Counter();
108   }
109   else
110   {
111     struct timeval delay;
112
113     delay.tv_sec  = milliseconds_delay / 1000;
114     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
115
116     if (select(0, NULL, NULL, NULL, &delay) != 0)
117       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
118   }
119 }
120
121 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
122 {
123   sleep_milliseconds(delay);
124 }
125
126 boolean FrameReached(unsigned long *frame_counter_var,
127                      unsigned long frame_delay)
128 {
129   unsigned long actual_frame_counter = FrameCounter;
130
131   if (actual_frame_counter < *frame_counter_var+frame_delay &&
132       actual_frame_counter >= *frame_counter_var)
133     return(FALSE);
134
135   *frame_counter_var = actual_frame_counter;
136   return(TRUE);
137 }
138
139 boolean DelayReached(unsigned long *counter_var,
140                      unsigned long delay)
141 {
142   unsigned long actual_counter = Counter();
143
144   if (actual_counter < *counter_var + delay &&
145       actual_counter >= *counter_var)
146     return(FALSE);
147
148   *counter_var = actual_counter;
149   return(TRUE);
150 }
151
152 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
153 {
154   unsigned long actual_counter;
155
156   while(1)
157   {
158     actual_counter = Counter();
159
160     if (actual_counter < *counter_var + delay &&
161         actual_counter >= *counter_var)
162       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
163     else
164       break;
165   }
166
167   *counter_var = actual_counter;
168 }
169
170 char *int2str(int number, int size)
171 {
172   static char s[40];
173
174   if (size > 20)
175     size = 20;
176
177   if (size)
178   {
179     sprintf(s, "                    %09d", number);
180     return &s[strlen(s) - size];
181   }
182   else
183   {
184     sprintf(s, "%d", number);
185     return s;
186   }
187 }
188
189 unsigned int SimpleRND(unsigned int max)
190 {
191   static unsigned long root = 654321;
192   struct timeval current_time;
193
194   gettimeofday(&current_time,NULL);
195   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
196   return (root % max);
197 }
198
199 #ifdef DEBUG
200 static unsigned int last_RND_value = 0;
201
202 unsigned int last_RND()
203 {
204   return last_RND_value;
205 }
206 #endif
207
208 unsigned int RND(unsigned int max)
209 {
210 #ifdef DEBUG
211   return (last_RND_value = random_linux_libc() % max);
212 #else
213   return (random_linux_libc() % max);
214 #endif
215 }
216
217 unsigned int InitRND(long seed)
218 {
219   struct timeval current_time;
220
221   if (seed == NEW_RANDOMIZE)
222   {
223     gettimeofday(&current_time,NULL);
224     srandom_linux_libc((unsigned int) current_time.tv_usec);
225     return (unsigned int)current_time.tv_usec;
226   }
227   else
228   {
229     srandom_linux_libc((unsigned int) seed);
230     return (unsigned int)seed;
231   }
232 }
233
234 char *getLoginName()
235 {
236   struct passwd *pwd;
237
238   if ((pwd = getpwuid(getuid())) == NULL)
239     return ANONYMOUS_NAME;
240   else
241     return pwd->pw_name;
242 }
243
244 char *getRealName()
245 {
246 #ifndef MSDOS
247   struct passwd *pwd;
248
249   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
250     return ANONYMOUS_NAME;
251   else
252   {
253     static char real_name[1024];
254     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
255
256     if (strchr(pwd->pw_gecos, 'ĂŸ') == NULL)
257       return pwd->pw_gecos;
258
259     /* the user's real name contains a 'ĂŸ' character (german sharp s),
260        which has no equivalent in upper case letters (which our fonts use) */
261     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
262     {
263       if (*from_ptr != 'ĂŸ')
264         *to_ptr++ = *from_ptr++;
265       else
266       {
267         from_ptr++;
268         *to_ptr++ = 's';
269         *to_ptr++ = 's';
270       }
271     }
272     *to_ptr = '\0';
273
274     return real_name;
275   }
276 #else
277   return ANONYMOUS_NAME;
278 #endif
279 }
280
281 char *getHomeDir()
282 {
283 #ifndef MSDOS
284   static char *home_dir = NULL;
285
286   if (!home_dir)
287   {
288     if (!(home_dir = getenv("HOME")))
289     {
290       struct passwd *pwd;
291
292       if ((pwd = getpwuid(getuid())))
293         home_dir = pwd->pw_dir;
294       else
295         home_dir = ".";
296     }
297   }
298
299   return home_dir;
300 #else
301   return ".";
302 #endif
303 }
304
305 char *getPath2(char *path1, char *path2)
306 {
307   char *complete_path = checked_malloc(strlen(path1) + 1 +
308                                        strlen(path2) + 1);
309
310   sprintf(complete_path, "%s/%s", path1, path2);
311   return complete_path;
312 }
313
314 char *getPath3(char *path1, char *path2, char *path3)
315 {
316   char *complete_path = checked_malloc(strlen(path1) + 1 +
317                                        strlen(path2) + 1 +
318                                        strlen(path3) + 1);
319
320   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
321   return complete_path;
322 }
323
324 char *getStringCopy(char *s)
325 {
326   char *s_copy = checked_malloc(strlen(s) + 1);
327
328   strcpy(s_copy, s);
329   return s_copy;
330 }
331
332 char *getStringToLower(char *s)
333 {
334   char *s_copy = checked_malloc(strlen(s) + 1);
335   char *s_ptr = s_copy;
336
337   while (*s)
338     *s_ptr++ = tolower(*s++);
339
340   return s_copy;
341 }
342
343 void MarkTileDirty(int x, int y)
344 {
345   int xx = redraw_x1 + x;
346   int yy = redraw_y1 + y;
347
348   if (!redraw[xx][yy])
349     redraw_tiles++;
350
351   redraw[xx][yy] = TRUE;
352   redraw_mask |= REDRAW_TILES;
353 }
354
355 void SetBorderElement()
356 {
357   int x, y;
358
359   BorderElement = EL_LEERRAUM;
360
361   for(y=0; y<lev_fieldy && BorderElement == EL_LEERRAUM; y++)
362   {
363     for(x=0; x<lev_fieldx; x++)
364     {
365       if (!IS_MASSIVE(Feld[x][y]))
366         BorderElement = EL_BETON;
367
368       if (y != 0 && y != lev_fieldy - 1 && x != lev_fieldx - 1)
369         x = lev_fieldx - 2;
370     }
371   }
372 }
373
374 void GetOptions(char *argv[])
375 {
376   char **options_left = &argv[1];
377
378   /* initialize global program options */
379   options.display_name = NULL;
380   options.server_host = NULL;
381   options.server_port = 0;
382   options.ro_base_directory = RO_BASE_PATH;
383   options.rw_base_directory = RW_BASE_PATH;
384   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
385   options.serveronly = FALSE;
386   options.network = FALSE;
387   options.verbose = FALSE;
388
389   while (*options_left)
390   {
391     char option_str[MAX_OPTION_LEN];
392     char *option = options_left[0];
393     char *next_option = options_left[1];
394     char *option_arg = NULL;
395     int option_len = strlen(option);
396
397     if (option_len >= MAX_OPTION_LEN)
398       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
399
400     strcpy(option_str, option);                 /* copy argument into buffer */
401     option = option_str;
402
403     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
404       break;
405
406     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
407       option++;
408
409     option_arg = strchr(option, '=');
410     if (option_arg == NULL)                     /* no '=' in option */
411       option_arg = next_option;
412     else
413     {
414       *option_arg++ = '\0';                     /* cut argument from option */
415       if (*option_arg == '\0')                  /* no argument after '=' */
416         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
417     }
418
419     option_len = strlen(option);
420
421     if (strcmp(option, "-") == 0)
422       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
423     else if (strncmp(option, "-help", option_len) == 0)
424     {
425       printf("Usage: %s [options] [server.name [port]]\n"
426              "Options:\n"
427              "  -d, --display machine:0       X server display\n"
428              "  -b, --basepath directory      alternative base directory\n"
429              "  -l, --levels directory        alternative level directory\n"
430              "  -s, --serveronly              only start network server\n"
431              "  -n, --network                 network multiplayer game\n"
432              "  -v, --verbose                 verbose mode\n",
433              program_name);
434       exit(0);
435     }
436     else if (strncmp(option, "-display", option_len) == 0)
437     {
438       if (option_arg == NULL)
439         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
440
441       options.display_name = option_arg;
442       if (option_arg == next_option)
443         options_left++;
444     }
445     else if (strncmp(option, "-basepath", option_len) == 0)
446     {
447       if (option_arg == NULL)
448         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
449
450       /* this should be extended to separate options for ro and rw data */
451       options.ro_base_directory = option_arg;
452       options.rw_base_directory = option_arg;
453       if (option_arg == next_option)
454         options_left++;
455
456       /* adjust path for level directory accordingly */
457       options.level_directory =
458         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
459     }
460     else if (strncmp(option, "-levels", option_len) == 0)
461     {
462       if (option_arg == NULL)
463         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
464
465       options.level_directory = option_arg;
466       if (option_arg == next_option)
467         options_left++;
468     }
469     else if (strncmp(option, "-network", option_len) == 0)
470     {
471       options.network = TRUE;
472     }
473     else if (strncmp(option, "-serveronly", option_len) == 0)
474     {
475       options.serveronly = TRUE;
476     }
477     else if (strncmp(option, "-verbose", option_len) == 0)
478     {
479       options.verbose = TRUE;
480     }
481     else if (*option == '-')
482     {
483       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
484     }
485     else if (options.server_host == NULL)
486     {
487       options.server_host = *options_left;
488     }
489     else if (options.server_port == 0)
490     {
491       options.server_port = atoi(*options_left);
492       if (options.server_port < 1024)
493         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
494     }
495     else
496       Error(ERR_EXIT_HELP, "too many arguments");
497
498     options_left++;
499   }
500 }
501
502 void Error(int mode, char *format, ...)
503 {
504   char *process_name = "";
505   FILE *error = stderr;
506
507   /* display warnings only when running in verbose mode */
508   if (mode & ERR_WARN && !options.verbose)
509     return;
510
511 #ifdef MSDOS
512   if ((error = openErrorFile()) == NULL)
513   {
514     printf("Cannot write to error output file!\n");
515     CloseAllAndExit(1);
516   }
517 #endif
518
519   if (mode & ERR_SOUND_SERVER)
520     process_name = " sound server";
521   else if (mode & ERR_NETWORK_SERVER)
522     process_name = " network server";
523   else if (mode & ERR_NETWORK_CLIENT)
524     process_name = " network client **";
525
526   if (format)
527   {
528     va_list ap;
529
530     fprintf(error, "%s%s: ", program_name, process_name);
531
532     if (mode & ERR_WARN)
533       fprintf(error, "warning: ");
534
535     va_start(ap, format);
536     vfprintf(error, format, ap);
537     va_end(ap);
538   
539     fprintf(error, "\n");
540   }
541   
542   if (mode & ERR_HELP)
543     fprintf(error, "%s: Try option '--help' for more information.\n",
544             program_name);
545
546   if (mode & ERR_EXIT)
547     fprintf(error, "%s%s: aborting\n", program_name, process_name);
548
549   if (error != stderr)
550     fclose(error);
551
552   if (mode & ERR_EXIT)
553   {
554     if (mode & ERR_FROM_SERVER)
555       exit(1);                          /* child process: normal exit */
556     else
557       CloseAllAndExit(1);               /* main process: clean up stuff */
558   }
559 }
560
561 void *checked_malloc(unsigned long size)
562 {
563   void *ptr;
564
565   ptr = malloc(size);
566
567   if (ptr == NULL)
568     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
569
570   return ptr;
571 }
572
573 void *checked_calloc(unsigned long size)
574 {
575   void *ptr;
576
577   ptr = calloc(1, size);
578
579   if (ptr == NULL)
580     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
581
582   return ptr;
583 }
584
585 short getFile16BitInteger(FILE *file, int byte_order)
586 {
587   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
588     return ((fgetc(file) <<  8) |
589             (fgetc(file) <<  0));
590   else           /* BYTE_ORDER_LITTLE_ENDIAN */
591     return ((fgetc(file) <<  0) |
592             (fgetc(file) <<  8));
593 }
594
595 void putFile16BitInteger(FILE *file, short value, int byte_order)
596 {
597   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
598   {
599     fputc((value >>  8) & 0xff, file);
600     fputc((value >>  0) & 0xff, file);
601   }
602   else           /* BYTE_ORDER_LITTLE_ENDIAN */
603   {
604     fputc((value >>  0) & 0xff, file);
605     fputc((value >>  8) & 0xff, file);
606   }
607 }
608
609 int getFile32BitInteger(FILE *file, int byte_order)
610 {
611   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
612     return ((fgetc(file) << 24) |
613             (fgetc(file) << 16) |
614             (fgetc(file) <<  8) |
615             (fgetc(file) <<  0));
616   else           /* BYTE_ORDER_LITTLE_ENDIAN */
617     return ((fgetc(file) <<  0) |
618             (fgetc(file) <<  8) |
619             (fgetc(file) << 16) |
620             (fgetc(file) << 24));
621 }
622
623 void putFile32BitInteger(FILE *file, int value, int byte_order)
624 {
625   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
626   {
627     fputc((value >> 24) & 0xff, file);
628     fputc((value >> 16) & 0xff, file);
629     fputc((value >>  8) & 0xff, file);
630     fputc((value >>  0) & 0xff, file);
631   }
632   else           /* BYTE_ORDER_LITTLE_ENDIAN */
633   {
634     fputc((value >>  0) & 0xff, file);
635     fputc((value >>  8) & 0xff, file);
636     fputc((value >> 16) & 0xff, file);
637     fputc((value >> 24) & 0xff, file);
638   }
639 }
640
641 void getFileChunk(FILE *file, char *chunk_buffer, int *chunk_length,
642                   int byte_order)
643 {
644   const int chunk_identifier_length = 4;
645
646   /* read chunk identifier */
647   fgets(chunk_buffer, chunk_identifier_length + 1, file);
648
649   /* read chunk length */
650   *chunk_length = getFile32BitInteger(file, byte_order);
651 }
652
653 void putFileChunk(FILE *file, char *chunk_name, int chunk_length,
654                   int byte_order)
655 {
656   /* write chunk identifier */
657   fputs(chunk_name, file);
658
659   /* write chunk length */
660   putFile32BitInteger(file, chunk_length, byte_order);
661 }
662
663 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
664 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
665 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
666
667 void translate_keyname(KeySym *keysym, char **x11name, char **name, int mode)
668 {
669   static struct
670   {
671     KeySym keysym;
672     char *x11name;
673     char *name;
674   } translate_key[] =
675   {
676     /* normal cursor keys */
677     { XK_Left,          "XK_Left",              "cursor left" },
678     { XK_Right,         "XK_Right",             "cursor right" },
679     { XK_Up,            "XK_Up",                "cursor up" },
680     { XK_Down,          "XK_Down",              "cursor down" },
681
682     /* keypad cursor keys */
683 #ifdef XK_KP_Left
684     { XK_KP_Left,       "XK_KP_Left",           "keypad left" },
685     { XK_KP_Right,      "XK_KP_Right",          "keypad right" },
686     { XK_KP_Up,         "XK_KP_Up",             "keypad up" },
687     { XK_KP_Down,       "XK_KP_Down",           "keypad down" },
688 #endif
689
690     /* other keypad keys */
691 #ifdef XK_KP_Enter
692     { XK_KP_Enter,      "XK_KP_Enter",          "keypad enter" },
693     { XK_KP_Add,        "XK_KP_Add",            "keypad +" },
694     { XK_KP_Subtract,   "XK_KP_Subtract",       "keypad -" },
695     { XK_KP_Multiply,   "XK_KP_Multiply",       "keypad mltply" },
696     { XK_KP_Divide,     "XK_KP_Divide",         "keypad /" },
697     { XK_KP_Separator,  "XK_KP_Separator",      "keypad ," },
698 #endif
699
700     /* modifier keys */
701     { XK_Shift_L,       "XK_Shift_L",           "left shift" },
702     { XK_Shift_R,       "XK_Shift_R",           "right shift" },
703     { XK_Control_L,     "XK_Control_L",         "left control" },
704     { XK_Control_R,     "XK_Control_R",         "right control" },
705     { XK_Meta_L,        "XK_Meta_L",            "left meta" },
706     { XK_Meta_R,        "XK_Meta_R",            "right meta" },
707     { XK_Alt_L,         "XK_Alt_L",             "left alt" },
708     { XK_Alt_R,         "XK_Alt_R",             "right alt" },
709     { XK_Mode_switch,   "XK_Mode_switch",       "mode switch" },
710     { XK_Multi_key,     "XK_Multi_key",         "multi key" },
711
712     /* some special keys */
713     { XK_BackSpace,     "XK_BackSpace",         "backspace" },
714     { XK_Delete,        "XK_Delete",            "delete" },
715     { XK_Insert,        "XK_Insert",            "insert" },
716     { XK_Tab,           "XK_Tab",               "tab" },
717     { XK_Home,          "XK_Home",              "home" },
718     { XK_End,           "XK_End",               "end" },
719     { XK_Page_Up,       "XK_Page_Up",           "page up" },
720     { XK_Page_Down,     "XK_Page_Down",         "page down" },
721
722
723     /* ASCII 0x20 to 0x40 keys (except numbers) */
724     { XK_space,         "XK_space",             "space" },
725     { XK_exclam,        "XK_exclam",            "!" },
726     { XK_quotedbl,      "XK_quotedbl",          "\"" },
727     { XK_numbersign,    "XK_numbersign",        "#" },
728     { XK_dollar,        "XK_dollar",            "$" },
729     { XK_percent,       "XK_percent",           "%" },
730     { XK_ampersand,     "XK_ampersand",         "&" },
731     { XK_apostrophe,    "XK_apostrophe",        "'" },
732     { XK_parenleft,     "XK_parenleft",         "(" },
733     { XK_parenright,    "XK_parenright",        ")" },
734     { XK_asterisk,      "XK_asterisk",          "*" },
735     { XK_plus,          "XK_plus",              "+" },
736     { XK_comma,         "XK_comma",             "," },
737     { XK_minus,         "XK_minus",             "-" },
738     { XK_period,        "XK_period",            "." },
739     { XK_slash,         "XK_slash",             "/" },
740     { XK_colon,         "XK_colon",             ":" },
741     { XK_semicolon,     "XK_semicolon",         ";" },
742     { XK_less,          "XK_less",              "<" },
743     { XK_equal,         "XK_equal",             "=" },
744     { XK_greater,       "XK_greater",           ">" },
745     { XK_question,      "XK_question",          "?" },
746     { XK_at,            "XK_at",                "@" },
747
748     /* more ASCII keys */
749     { XK_bracketleft,   "XK_bracketleft",       "[" },
750     { XK_backslash,     "XK_backslash",         "backslash" },
751     { XK_bracketright,  "XK_bracketright",      "]" },
752     { XK_asciicircum,   "XK_asciicircum",       "circumflex" },
753     { XK_underscore,    "XK_underscore",        "_" },
754     { XK_grave,         "XK_grave",             "grave" },
755     { XK_quoteleft,     "XK_quoteleft",         "quote left" },
756     { XK_braceleft,     "XK_braceleft",         "brace left" },
757     { XK_bar,           "XK_bar",               "bar" },
758     { XK_braceright,    "XK_braceright",        "brace right" },
759     { XK_asciitilde,    "XK_asciitilde",        "ascii tilde" },
760
761     /* special (non-ASCII) keys */
762     { XK_Adiaeresis,    "XK_Adiaeresis",        "Ă„" },
763     { XK_Odiaeresis,    "XK_Odiaeresis",        "Ă–" },
764     { XK_Udiaeresis,    "XK_Udiaeresis",        "Ăœ" },
765     { XK_adiaeresis,    "XK_adiaeresis",        "ä" },
766     { XK_odiaeresis,    "XK_odiaeresis",        "ö" },
767     { XK_udiaeresis,    "XK_udiaeresis",        "Ă¼" },
768     { XK_ssharp,        "XK_ssharp",            "sharp s" },
769
770     /* end-of-array identifier */
771     { 0,                NULL,                   NULL }
772   };
773
774   int i;
775
776   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
777   {
778     static char name_buffer[30];
779     KeySym key = *keysym;
780
781     if (key >= XK_A && key <= XK_Z)
782       sprintf(name_buffer, "%c", 'A' + (char)(key - XK_A));
783     else if (key >= XK_a && key <= XK_z)
784       sprintf(name_buffer, "%c", 'a' + (char)(key - XK_a));
785     else if (key >= XK_0 && key <= XK_9)
786       sprintf(name_buffer, "%c", '0' + (char)(key - XK_0));
787     else if (key >= XK_KP_0 && key <= XK_KP_9)
788       sprintf(name_buffer, "keypad %c", '0' + (char)(key - XK_KP_0));
789     else if (key >= XK_F1 && key <= XK_F24)
790       sprintf(name_buffer, "function F%d", (int)(key - XK_F1 + 1));
791     else if (key == KEY_UNDEFINDED)
792       strcpy(name_buffer, "(undefined)");
793     else
794     {
795       i = 0;
796
797       do
798       {
799         if (key == translate_key[i].keysym)
800         {
801           strcpy(name_buffer, translate_key[i].name);
802           break;
803         }
804       }
805       while (translate_key[++i].name);
806
807       if (!translate_key[i].name)
808         strcpy(name_buffer, "(unknown)");
809     }
810
811     *name = name_buffer;
812   }
813   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
814   {
815     static char name_buffer[30];
816     KeySym key = *keysym;
817
818     if (key >= XK_A && key <= XK_Z)
819       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - XK_A));
820     else if (key >= XK_a && key <= XK_z)
821       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - XK_a));
822     else if (key >= XK_0 && key <= XK_9)
823       sprintf(name_buffer, "XK_%c", '0' + (char)(key - XK_0));
824     else if (key >= XK_KP_0 && key <= XK_KP_9)
825       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - XK_KP_0));
826     else if (key >= XK_F1 && key <= XK_F24)
827       sprintf(name_buffer, "XK_F%d", (int)(key - XK_F1 + 1));
828     else if (key == KEY_UNDEFINDED)
829       strcpy(name_buffer, "[undefined]");
830     else
831     {
832       i = 0;
833
834       do
835       {
836         if (key == translate_key[i].keysym)
837         {
838           strcpy(name_buffer, translate_key[i].x11name);
839           break;
840         }
841       }
842       while (translate_key[++i].x11name);
843
844       if (!translate_key[i].x11name)
845         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
846     }
847
848     *x11name = name_buffer;
849   }
850   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
851   {
852     KeySym key = XK_VoidSymbol;
853     char *name_ptr = *x11name;
854
855     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
856     {
857       char c = name_ptr[3];
858
859       if (c >= 'A' && c <= 'Z')
860         key = XK_A + (KeySym)(c - 'A');
861       else if (c >= 'a' && c <= 'z')
862         key = XK_a + (KeySym)(c - 'a');
863       else if (c >= '0' && c <= '9')
864         key = XK_0 + (KeySym)(c - '0');
865     }
866     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
867     {
868       char c = name_ptr[6];
869
870       if (c >= '0' && c <= '9')
871         key = XK_0 + (KeySym)(c - '0');
872     }
873     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
874     {
875       char c1 = name_ptr[4];
876       char c2 = name_ptr[5];
877       int d = 0;
878
879       if ((c1 >= '0' && c1 <= '9') &&
880           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
881         d = atoi(&name_ptr[4]);
882
883       if (d >=1 && d <= 24)
884         key = XK_F1 + (KeySym)(d - 1);
885     }
886     else if (strncmp(name_ptr, "XK_", 3) == 0)
887     {
888       i = 0;
889
890       do
891       {
892         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
893         {
894           key = translate_key[i].keysym;
895           break;
896         }
897       }
898       while (translate_key[++i].x11name);
899     }
900     else if (strncmp(name_ptr, "0x", 2) == 0)
901     {
902       unsigned long value = 0;
903
904       name_ptr += 2;
905
906       while (name_ptr)
907       {
908         char c = *name_ptr++;
909         int d = -1;
910
911         if (c >= '0' && c <= '9')
912           d = (int)(c - '0');
913         else if (c >= 'a' && c <= 'f')
914           d = (int)(c - 'a' + 10);
915         else if (c >= 'A' && c <= 'F')
916           d = (int)(c - 'A' + 10);
917
918         if (d == -1)
919         {
920           value = -1;
921           break;
922         }
923
924         value = value * 16 + d;
925       }
926
927       if (value != -1)
928         key = (KeySym)value;
929     }
930
931     *keysym = key;
932   }
933 }
934
935 char *getKeyNameFromKeySym(KeySym keysym)
936 {
937   char *name;
938
939   translate_keyname(&keysym, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
940   return name;
941 }
942
943 char *getX11KeyNameFromKeySym(KeySym keysym)
944 {
945   char *x11name;
946
947   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
948   return x11name;
949 }
950
951 KeySym getKeySymFromX11KeyName(char *x11name)
952 {
953   KeySym keysym;
954
955   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
956   return keysym;
957 }
958
959 char getCharFromKeySym(KeySym keysym)
960 {
961   char *keyname = getKeyNameFromKeySym(keysym);
962   char letter = 0;
963
964   if (strlen(keyname) == 1)
965     letter = keyname[0];
966   else if (strcmp(keyname, "space") == 0)
967     letter = ' ';
968   else if (strcmp(keyname, "circumflex") == 0)
969     letter = '^';
970
971   return letter;
972 }
973
974 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
975 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
976
977 void translate_joyname(int *joysymbol, char **name, int mode)
978 {
979   static struct
980   {
981     int joysymbol;
982     char *name;
983   } translate_joy[] =
984   {
985     { JOY_LEFT,         "joystick_left" },
986     { JOY_RIGHT,        "joystick_right" },
987     { JOY_UP,           "joystick_up" },
988     { JOY_DOWN,         "joystick_down" },
989     { JOY_BUTTON_1,     "joystick_button_1" },
990     { JOY_BUTTON_2,     "joystick_button_2" },
991   };
992
993   int i;
994
995   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
996   {
997     *name = "[undefined]";
998
999     for (i=0; i<6; i++)
1000     {
1001       if (*joysymbol == translate_joy[i].joysymbol)
1002       {
1003         *name = translate_joy[i].name;
1004         break;
1005       }
1006     }
1007   }
1008   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
1009   {
1010     *joysymbol = 0;
1011
1012     for (i=0; i<6; i++)
1013     {
1014       if (strcmp(*name, translate_joy[i].name) == 0)
1015       {
1016         *joysymbol = translate_joy[i].joysymbol;
1017         break;
1018       }
1019     }
1020   }
1021 }
1022
1023 char *getJoyNameFromJoySymbol(int joysymbol)
1024 {
1025   char *name;
1026
1027   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
1028   return name;
1029 }
1030
1031 int getJoySymbolFromJoyName(char *name)
1032 {
1033   int joysymbol;
1034
1035   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
1036   return joysymbol;
1037 }
1038
1039 int getJoystickNrFromDeviceName(char *device_name)
1040 {
1041   char c;
1042   int joystick_nr = 0;
1043
1044   if (device_name == NULL || device_name[0] == '\0')
1045     return 0;
1046
1047   c = device_name[strlen(device_name) - 1];
1048
1049   if (c >= '0' && c <= '9')
1050     joystick_nr = (int)(c - '0');
1051
1052   if (joystick_nr < 0 || joystick_nr >= MAX_PLAYERS)
1053     joystick_nr = 0;
1054
1055   return joystick_nr;
1056 }
1057
1058 /* ----------------------------------------------------------------- */
1059 /* the following is only for debugging purpose and normally not used */
1060 /* ----------------------------------------------------------------- */
1061
1062 #define DEBUG_NUM_TIMESTAMPS    3
1063
1064 void debug_print_timestamp(int counter_nr, char *message)
1065 {
1066   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1067
1068   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1069     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1070
1071   counter[counter_nr][0] = Counter();
1072
1073   if (message)
1074     printf("%s %.2f seconds\n", message,
1075            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1076
1077   counter[counter_nr][1] = Counter();
1078 }