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