rnd-19990219-2
[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.base_directory = BASE_PATH;
383   options.level_directory = BASE_PATH "/" LEVELS_DIRECTORY;
384   options.serveronly = FALSE;
385   options.network = FALSE;
386   options.verbose = FALSE;
387
388   while (*options_left)
389   {
390     char option_str[MAX_OPTION_LEN];
391     char *option = options_left[0];
392     char *next_option = options_left[1];
393     char *option_arg = NULL;
394     int option_len = strlen(option);
395
396     if (option_len >= MAX_OPTION_LEN)
397       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
398
399     strcpy(option_str, option);                 /* copy argument into buffer */
400     option = option_str;
401
402     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
403       break;
404
405     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
406       option++;
407
408     option_arg = strchr(option, '=');
409     if (option_arg == NULL)                     /* no '=' in option */
410       option_arg = next_option;
411     else
412     {
413       *option_arg++ = '\0';                     /* cut argument from option */
414       if (*option_arg == '\0')                  /* no argument after '=' */
415         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
416     }
417
418     option_len = strlen(option);
419
420     if (strcmp(option, "-") == 0)
421       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
422     else if (strncmp(option, "-help", option_len) == 0)
423     {
424       printf("Usage: %s [options] [server.name [port]]\n"
425              "Options:\n"
426              "  -d, --display machine:0       X server display\n"
427              "  -b, --basepath directory      alternative base directory\n"
428              "  -l, --levels directory        alternative level directory\n"
429              "  -s, --serveronly              only start network server\n"
430              "  -n, --network                 network multiplayer game\n"
431              "  -v, --verbose                 verbose mode\n",
432              program_name);
433       exit(0);
434     }
435     else if (strncmp(option, "-display", option_len) == 0)
436     {
437       if (option_arg == NULL)
438         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
439
440       options.display_name = option_arg;
441       if (option_arg == next_option)
442         options_left++;
443     }
444     else if (strncmp(option, "-basepath", option_len) == 0)
445     {
446       if (option_arg == NULL)
447         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
448
449       options.base_directory = option_arg;
450       if (option_arg == next_option)
451         options_left++;
452
453       /* adjust path for level directory accordingly */
454       options.level_directory =
455         getPath2(options.base_directory, LEVELS_DIRECTORY);
456     }
457     else if (strncmp(option, "-levels", option_len) == 0)
458     {
459       if (option_arg == NULL)
460         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
461
462       options.level_directory = option_arg;
463       if (option_arg == next_option)
464         options_left++;
465     }
466     else if (strncmp(option, "-network", option_len) == 0)
467     {
468       options.network = TRUE;
469     }
470     else if (strncmp(option, "-serveronly", option_len) == 0)
471     {
472       options.serveronly = TRUE;
473     }
474     else if (strncmp(option, "-verbose", option_len) == 0)
475     {
476       options.verbose = TRUE;
477     }
478     else if (*option == '-')
479     {
480       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
481     }
482     else if (options.server_host == NULL)
483     {
484       options.server_host = *options_left;
485     }
486     else if (options.server_port == 0)
487     {
488       options.server_port = atoi(*options_left);
489       if (options.server_port < 1024)
490         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
491     }
492     else
493       Error(ERR_EXIT_HELP, "too many arguments");
494
495     options_left++;
496   }
497 }
498
499 void Error(int mode, char *format, ...)
500 {
501   char *process_name = "";
502   FILE *error = stderr;
503
504   /* display warnings only when running in verbose mode */
505   if (mode & ERR_WARN && !options.verbose)
506     return;
507
508 #ifdef MSDOS
509   if ((error = openErrorFile()) == NULL)
510   {
511     printf("Cannot write to error output file!\n");
512     CloseAllAndExit(1);
513   }
514 #endif
515
516   if (mode & ERR_SOUND_SERVER)
517     process_name = " sound server";
518   else if (mode & ERR_NETWORK_SERVER)
519     process_name = " network server";
520   else if (mode & ERR_NETWORK_CLIENT)
521     process_name = " network client **";
522
523   if (format)
524   {
525     va_list ap;
526
527     fprintf(error, "%s%s: ", program_name, process_name);
528
529     if (mode & ERR_WARN)
530       fprintf(error, "warning: ");
531
532     va_start(ap, format);
533     vfprintf(error, format, ap);
534     va_end(ap);
535   
536     fprintf(error, "\n");
537   }
538   
539   if (mode & ERR_HELP)
540     fprintf(error, "%s: Try option '--help' for more information.\n",
541             program_name);
542
543   if (mode & ERR_EXIT)
544     fprintf(error, "%s%s: aborting\n", program_name, process_name);
545
546   if (error != stderr)
547     fclose(error);
548
549   if (mode & ERR_EXIT)
550   {
551     if (mode & ERR_FROM_SERVER)
552       exit(1);                          /* child process: normal exit */
553     else
554       CloseAllAndExit(1);               /* main process: clean up stuff */
555   }
556 }
557
558 void *checked_malloc(unsigned long size)
559 {
560   void *ptr;
561
562   ptr = malloc(size);
563
564   if (ptr == NULL)
565     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
566
567   return ptr;
568 }
569
570 void *checked_calloc(unsigned long size)
571 {
572   void *ptr;
573
574   ptr = calloc(1, size);
575
576   if (ptr == NULL)
577     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
578
579   return ptr;
580 }
581
582 short getFile16BitInteger(FILE *file, int byte_order)
583 {
584   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
585     return ((fgetc(file) <<  8) |
586             (fgetc(file) <<  0));
587   else           /* BYTE_ORDER_LITTLE_ENDIAN */
588     return ((fgetc(file) <<  0) |
589             (fgetc(file) <<  8));
590 }
591
592 void putFile16BitInteger(FILE *file, short value, int byte_order)
593 {
594   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
595   {
596     fputc((value >>  8) & 0xff, file);
597     fputc((value >>  0) & 0xff, file);
598   }
599   else           /* BYTE_ORDER_LITTLE_ENDIAN */
600   {
601     fputc((value >>  0) & 0xff, file);
602     fputc((value >>  8) & 0xff, file);
603   }
604 }
605
606 int getFile32BitInteger(FILE *file, int byte_order)
607 {
608   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
609     return ((fgetc(file) << 24) |
610             (fgetc(file) << 16) |
611             (fgetc(file) <<  8) |
612             (fgetc(file) <<  0));
613   else           /* BYTE_ORDER_LITTLE_ENDIAN */
614     return ((fgetc(file) <<  0) |
615             (fgetc(file) <<  8) |
616             (fgetc(file) << 16) |
617             (fgetc(file) << 24));
618 }
619
620 void putFile32BitInteger(FILE *file, int value, int byte_order)
621 {
622   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
623   {
624     fputc((value >> 24) & 0xff, file);
625     fputc((value >> 16) & 0xff, file);
626     fputc((value >>  8) & 0xff, file);
627     fputc((value >>  0) & 0xff, file);
628   }
629   else           /* BYTE_ORDER_LITTLE_ENDIAN */
630   {
631     fputc((value >>  0) & 0xff, file);
632     fputc((value >>  8) & 0xff, file);
633     fputc((value >> 16) & 0xff, file);
634     fputc((value >> 24) & 0xff, file);
635   }
636 }
637
638 void getFileChunk(FILE *file, char *chunk_buffer, int *chunk_length,
639                   int byte_order)
640 {
641   const int chunk_identifier_length = 4;
642
643   /* read chunk identifier */
644   fgets(chunk_buffer, chunk_identifier_length + 1, file);
645
646   /* read chunk length */
647   *chunk_length = getFile32BitInteger(file, byte_order);
648 }
649
650 void putFileChunk(FILE *file, char *chunk_name, int chunk_length,
651                   int byte_order)
652 {
653   /* write chunk identifier */
654   fputs(chunk_name, file);
655
656   /* write chunk length */
657   putFile32BitInteger(file, chunk_length, byte_order);
658 }
659
660 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
661 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
662 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
663
664 void translate_keyname(KeySym *keysym, char **x11name, char **name, int mode)
665 {
666   static struct
667   {
668     KeySym keysym;
669     char *x11name;
670     char *name;
671   } translate_key[] =
672   {
673     /* normal cursor keys */
674     { XK_Left,          "XK_Left",              "cursor left" },
675     { XK_Right,         "XK_Right",             "cursor right" },
676     { XK_Up,            "XK_Up",                "cursor up" },
677     { XK_Down,          "XK_Down",              "cursor down" },
678
679     /* keypad cursor keys */
680 #ifdef XK_KP_Left
681     { XK_KP_Left,       "XK_KP_Left",           "keypad left" },
682     { XK_KP_Right,      "XK_KP_Right",          "keypad right" },
683     { XK_KP_Up,         "XK_KP_Up",             "keypad up" },
684     { XK_KP_Down,       "XK_KP_Down",           "keypad down" },
685 #endif
686
687     /* other keypad keys */
688 #ifdef XK_KP_Enter
689     { XK_KP_Enter,      "XK_KP_Enter",          "keypad enter" },
690     { XK_KP_Add,        "XK_KP_Add",            "keypad +" },
691     { XK_KP_Subtract,   "XK_KP_Subtract",       "keypad -" },
692     { XK_KP_Multiply,   "XK_KP_Multiply",       "keypad mltply" },
693     { XK_KP_Divide,     "XK_KP_Divide",         "keypad /" },
694     { XK_KP_Separator,  "XK_KP_Separator",      "keypad ," },
695 #endif
696
697     /* modifier keys */
698     { XK_Shift_L,       "XK_Shift_L",           "left shift" },
699     { XK_Shift_R,       "XK_Shift_R",           "right shift" },
700     { XK_Control_L,     "XK_Control_L",         "left control" },
701     { XK_Control_R,     "XK_Control_R",         "right control" },
702     { XK_Meta_L,        "XK_Meta_L",            "left meta" },
703     { XK_Meta_R,        "XK_Meta_R",            "right meta" },
704     { XK_Alt_L,         "XK_Alt_L",             "left alt" },
705     { XK_Alt_R,         "XK_Alt_R",             "right alt" },
706     { XK_Mode_switch,   "XK_Mode_switch",       "mode switch" },
707     { XK_Multi_key,     "XK_Multi_key",         "multi key" },
708
709     /* some special keys */
710     { XK_BackSpace,     "XK_BackSpace",         "backspace" },
711     { XK_Delete,        "XK_Delete",            "delete" },
712     { XK_Insert,        "XK_Insert",            "insert" },
713     { XK_Tab,           "XK_Tab",               "tab" },
714     { XK_Home,          "XK_Home",              "home" },
715     { XK_End,           "XK_End",               "end" },
716     { XK_Page_Up,       "XK_Page_Up",           "page up" },
717     { XK_Page_Down,     "XK_Page_Down",         "page down" },
718
719
720     /* ASCII 0x20 to 0x40 keys (except numbers) */
721     { XK_space,         "XK_space",             "space" },
722     { XK_exclam,        "XK_exclam",            "!" },
723     { XK_quotedbl,      "XK_quotedbl",          "\"" },
724     { XK_numbersign,    "XK_numbersign",        "#" },
725     { XK_dollar,        "XK_dollar",            "$" },
726     { XK_percent,       "XK_percent",           "%" },
727     { XK_ampersand,     "XK_ampersand",         "&" },
728     { XK_apostrophe,    "XK_apostrophe",        "'" },
729     { XK_parenleft,     "XK_parenleft",         "(" },
730     { XK_parenright,    "XK_parenright",        ")" },
731     { XK_asterisk,      "XK_asterisk",          "*" },
732     { XK_plus,          "XK_plus",              "+" },
733     { XK_comma,         "XK_comma",             "," },
734     { XK_minus,         "XK_minus",             "-" },
735     { XK_period,        "XK_period",            "." },
736     { XK_slash,         "XK_slash",             "/" },
737     { XK_colon,         "XK_colon",             ":" },
738     { XK_semicolon,     "XK_semicolon",         ";" },
739     { XK_less,          "XK_less",              "<" },
740     { XK_equal,         "XK_equal",             "=" },
741     { XK_greater,       "XK_greater",           ">" },
742     { XK_question,      "XK_question",          "?" },
743     { XK_at,            "XK_at",                "@" },
744
745     /* more ASCII keys */
746     { XK_bracketleft,   "XK_bracketleft",       "[" },
747     { XK_backslash,     "XK_backslash",         "backslash" },
748     { XK_bracketright,  "XK_bracketright",      "]" },
749     { XK_asciicircum,   "XK_asciicircum",       "circumflex" },
750     { XK_underscore,    "XK_underscore",        "_" },
751     { XK_grave,         "XK_grave",             "grave" },
752     { XK_quoteleft,     "XK_quoteleft",         "quote left" },
753     { XK_braceleft,     "XK_braceleft",         "brace left" },
754     { XK_bar,           "XK_bar",               "bar" },
755     { XK_braceright,    "XK_braceright",        "brace right" },
756     { XK_asciitilde,    "XK_asciitilde",        "ascii tilde" },
757
758     /* special (non-ASCII) keys */
759     { XK_Adiaeresis,    "XK_Adiaeresis",        "Ă„" },
760     { XK_Odiaeresis,    "XK_Odiaeresis",        "Ă–" },
761     { XK_Udiaeresis,    "XK_Udiaeresis",        "Ăœ" },
762     { XK_adiaeresis,    "XK_adiaeresis",        "ä" },
763     { XK_odiaeresis,    "XK_odiaeresis",        "ö" },
764     { XK_udiaeresis,    "XK_udiaeresis",        "Ă¼" },
765     { XK_ssharp,        "XK_ssharp",            "sharp s" },
766
767     /* end-of-array identifier */
768     { 0,                NULL,                   NULL }
769   };
770
771   int i;
772
773   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
774   {
775     static char name_buffer[30];
776     KeySym key = *keysym;
777
778     if (key >= XK_A && key <= XK_Z)
779       sprintf(name_buffer, "%c", 'A' + (char)(key - XK_A));
780     else if (key >= XK_a && key <= XK_z)
781       sprintf(name_buffer, "%c", 'a' + (char)(key - XK_a));
782     else if (key >= XK_0 && key <= XK_9)
783       sprintf(name_buffer, "%c", '0' + (char)(key - XK_0));
784     else if (key >= XK_KP_0 && key <= XK_KP_9)
785       sprintf(name_buffer, "keypad %c", '0' + (char)(key - XK_KP_0));
786     else if (key >= XK_F1 && key <= XK_F24)
787       sprintf(name_buffer, "function F%d", (int)(key - XK_F1 + 1));
788     else if (key == KEY_UNDEFINDED)
789       strcpy(name_buffer, "(undefined)");
790     else
791     {
792       i = 0;
793
794       do
795       {
796         if (key == translate_key[i].keysym)
797         {
798           strcpy(name_buffer, translate_key[i].name);
799           break;
800         }
801       }
802       while (translate_key[++i].name);
803
804       if (!translate_key[i].name)
805         strcpy(name_buffer, "(unknown)");
806     }
807
808     *name = name_buffer;
809   }
810   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
811   {
812     static char name_buffer[30];
813     KeySym key = *keysym;
814
815     if (key >= XK_A && key <= XK_Z)
816       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - XK_A));
817     else if (key >= XK_a && key <= XK_z)
818       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - XK_a));
819     else if (key >= XK_0 && key <= XK_9)
820       sprintf(name_buffer, "XK_%c", '0' + (char)(key - XK_0));
821     else if (key >= XK_KP_0 && key <= XK_KP_9)
822       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - XK_KP_0));
823     else if (key >= XK_F1 && key <= XK_F24)
824       sprintf(name_buffer, "XK_F%d", (int)(key - XK_F1 + 1));
825     else if (key == KEY_UNDEFINDED)
826       strcpy(name_buffer, "[undefined]");
827     else
828     {
829       i = 0;
830
831       do
832       {
833         if (key == translate_key[i].keysym)
834         {
835           strcpy(name_buffer, translate_key[i].x11name);
836           break;
837         }
838       }
839       while (translate_key[++i].x11name);
840
841       if (!translate_key[i].x11name)
842         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
843     }
844
845     *x11name = name_buffer;
846   }
847   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
848   {
849     KeySym key = XK_VoidSymbol;
850     char *name_ptr = *x11name;
851
852     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
853     {
854       char c = name_ptr[3];
855
856       if (c >= 'A' && c <= 'Z')
857         key = XK_A + (KeySym)(c - 'A');
858       else if (c >= 'a' && c <= 'z')
859         key = XK_a + (KeySym)(c - 'a');
860       else if (c >= '0' && c <= '9')
861         key = XK_0 + (KeySym)(c - '0');
862     }
863     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
864     {
865       char c = name_ptr[6];
866
867       if (c >= '0' && c <= '9')
868         key = XK_0 + (KeySym)(c - '0');
869     }
870     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
871     {
872       char c1 = name_ptr[4];
873       char c2 = name_ptr[5];
874       int d = 0;
875
876       if ((c1 >= '0' && c1 <= '9') &&
877           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
878         d = atoi(&name_ptr[4]);
879
880       if (d >=1 && d <= 24)
881         key = XK_F1 + (KeySym)(d - 1);
882     }
883     else if (strncmp(name_ptr, "XK_", 3) == 0)
884     {
885       i = 0;
886
887       do
888       {
889         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
890         {
891           key = translate_key[i].keysym;
892           break;
893         }
894       }
895       while (translate_key[++i].x11name);
896     }
897     else if (strncmp(name_ptr, "0x", 2) == 0)
898     {
899       unsigned long value = 0;
900
901       name_ptr += 2;
902
903       while (name_ptr)
904       {
905         char c = *name_ptr++;
906         int d = -1;
907
908         if (c >= '0' && c <= '9')
909           d = (int)(c - '0');
910         else if (c >= 'a' && c <= 'f')
911           d = (int)(c - 'a' + 10);
912         else if (c >= 'A' && c <= 'F')
913           d = (int)(c - 'A' + 10);
914
915         if (d == -1)
916         {
917           value = -1;
918           break;
919         }
920
921         value = value * 16 + d;
922       }
923
924       if (value != -1)
925         key = (KeySym)value;
926     }
927
928     *keysym = key;
929   }
930 }
931
932 char *getKeyNameFromKeySym(KeySym keysym)
933 {
934   char *name;
935
936   translate_keyname(&keysym, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
937   return name;
938 }
939
940 char *getX11KeyNameFromKeySym(KeySym keysym)
941 {
942   char *x11name;
943
944   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
945   return x11name;
946 }
947
948 KeySym getKeySymFromX11KeyName(char *x11name)
949 {
950   KeySym keysym;
951
952   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
953   return keysym;
954 }
955
956 char getCharFromKeySym(KeySym keysym)
957 {
958   char *keyname = getKeyNameFromKeySym(keysym);
959   char letter = 0;
960
961   if (strlen(keyname) == 1)
962     letter = keyname[0];
963   else if (strcmp(keyname, "space") == 0)
964     letter = ' ';
965   else if (strcmp(keyname, "circumflex") == 0)
966     letter = '^';
967
968   return letter;
969 }
970
971 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
972 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
973
974 void translate_joyname(int *joysymbol, char **name, int mode)
975 {
976   static struct
977   {
978     int joysymbol;
979     char *name;
980   } translate_joy[] =
981   {
982     { JOY_LEFT,         "joystick_left" },
983     { JOY_RIGHT,        "joystick_right" },
984     { JOY_UP,           "joystick_up" },
985     { JOY_DOWN,         "joystick_down" },
986     { JOY_BUTTON_1,     "joystick_button_1" },
987     { JOY_BUTTON_2,     "joystick_button_2" },
988   };
989
990   int i;
991
992   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
993   {
994     *name = "[undefined]";
995
996     for (i=0; i<6; i++)
997     {
998       if (*joysymbol == translate_joy[i].joysymbol)
999       {
1000         *name = translate_joy[i].name;
1001         break;
1002       }
1003     }
1004   }
1005   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
1006   {
1007     *joysymbol = 0;
1008
1009     for (i=0; i<6; i++)
1010     {
1011       if (strcmp(*name, translate_joy[i].name) == 0)
1012       {
1013         *joysymbol = translate_joy[i].joysymbol;
1014         break;
1015       }
1016     }
1017   }
1018 }
1019
1020 char *getJoyNameFromJoySymbol(int joysymbol)
1021 {
1022   char *name;
1023
1024   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
1025   return name;
1026 }
1027
1028 int getJoySymbolFromJoyName(char *name)
1029 {
1030   int joysymbol;
1031
1032   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
1033   return joysymbol;
1034 }
1035
1036 int getJoystickNrFromDeviceName(char *device_name)
1037 {
1038   char c;
1039   int joystick_nr = 0;
1040
1041   if (device_name == NULL || device_name[0] == '\0')
1042     return 0;
1043
1044   c = device_name[strlen(device_name) - 1];
1045
1046   if (c >= '0' && c <= '9')
1047     joystick_nr = (int)(c - '0');
1048
1049   if (joystick_nr < 0 || joystick_nr >= MAX_PLAYERS)
1050     joystick_nr = 0;
1051
1052   return joystick_nr;
1053 }
1054
1055 /* ----------------------------------------------------------------- */
1056 /* the following is only for debugging purpose and normally not used */
1057 /* ----------------------------------------------------------------- */
1058
1059 #define DEBUG_NUM_TIMESTAMPS    3
1060
1061 void debug_print_timestamp(int counter_nr, char *message)
1062 {
1063   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1064
1065   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1066     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1067
1068   counter[counter_nr][0] = Counter();
1069
1070   if (message)
1071     printf("%s %.2f seconds\n", message,
1072            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1073
1074   counter[counter_nr][1] = Counter();
1075 }