rnd-19981204-1
[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())))
239     return "ANONYMOUS";
240   else
241     return pwd->pw_name;
242 }
243
244 char *getHomeDir()
245 {
246 #ifndef MSDOS
247   static char *home_dir = NULL;
248
249   if (!home_dir)
250   {
251     if (!(home_dir = getenv("HOME")))
252     {
253       struct passwd *pwd;
254
255       if ((pwd = getpwuid(getuid())))
256         home_dir = pwd->pw_dir;
257       else
258         home_dir = ".";
259     }
260   }
261
262   return home_dir;
263 #else
264   return ".";
265 #endif
266 }
267
268 char *getPath2(char *path1, char *path2)
269 {
270   char *complete_path = checked_malloc(strlen(path1) + 1 +
271                                        strlen(path2) + 1);
272
273   sprintf(complete_path, "%s/%s", path1, path2);
274   return complete_path;
275 }
276
277 char *getPath3(char *path1, char *path2, char *path3)
278 {
279   char *complete_path = checked_malloc(strlen(path1) + 1 +
280                                        strlen(path2) + 1 +
281                                        strlen(path3) + 1);
282
283   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
284   return complete_path;
285 }
286
287 char *getStringCopy(char *s)
288 {
289   char *s_copy = checked_malloc(strlen(s) + 1);
290
291   strcpy(s_copy, s);
292   return s_copy;
293 }
294
295 char *getStringToLower(char *s)
296 {
297   char *s_copy = checked_malloc(strlen(s) + 1);
298   char *s_ptr = s_copy;
299
300   while (*s)
301     *s_ptr++ = tolower(*s++);
302
303   return s_copy;
304 }
305
306 void MarkTileDirty(int x, int y)
307 {
308   int xx = redraw_x1 + x;
309   int yy = redraw_y1 + y;
310
311   if (!redraw[xx][yy])
312     redraw_tiles++;
313
314   redraw[xx][yy] = TRUE;
315   redraw_mask |= REDRAW_TILES;
316 }
317
318 void GetOptions(char *argv[])
319 {
320   char **options_left = &argv[1];
321
322   /* initialize global program options */
323   options.display_name = NULL;
324   options.server_host = NULL;
325   options.server_port = 0;
326   options.base_directory = BASE_PATH;
327   options.level_directory = BASE_PATH "/" LEVELS_DIRECTORY;
328   options.serveronly = FALSE;
329   options.network = FALSE;
330   options.verbose = FALSE;
331
332   while (*options_left)
333   {
334     char option_str[MAX_OPTION_LEN];
335     char *option = options_left[0];
336     char *next_option = options_left[1];
337     char *option_arg = NULL;
338     int option_len = strlen(option);
339
340     if (option_len >= MAX_OPTION_LEN)
341       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
342
343     strcpy(option_str, option);                 /* copy argument into buffer */
344     option = option_str;
345
346     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
347       break;
348
349     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
350       option++;
351
352     option_arg = strchr(option, '=');
353     if (option_arg == NULL)                     /* no '=' in option */
354       option_arg = next_option;
355     else
356     {
357       *option_arg++ = '\0';                     /* cut argument from option */
358       if (*option_arg == '\0')                  /* no argument after '=' */
359         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
360     }
361
362     option_len = strlen(option);
363
364     if (strcmp(option, "-") == 0)
365       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
366     else if (strncmp(option, "-help", option_len) == 0)
367     {
368       printf("Usage: %s [options] [server.name [port]]\n"
369              "Options:\n"
370              "  -d, --display machine:0       X server display\n"
371              "  -b, --basepath directory      alternative base directory\n"
372              "  -l, --levels directory        alternative level directory\n"
373              "  -s, --serveronly              only start network server\n"
374              "  -n, --network                 network multiplayer game\n"
375              "  -v, --verbose                 verbose mode\n",
376              program_name);
377       exit(0);
378     }
379     else if (strncmp(option, "-display", option_len) == 0)
380     {
381       if (option_arg == NULL)
382         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
383
384       options.display_name = option_arg;
385       if (option_arg == next_option)
386         options_left++;
387     }
388     else if (strncmp(option, "-basepath", option_len) == 0)
389     {
390       if (option_arg == NULL)
391         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
392
393       options.base_directory = option_arg;
394       if (option_arg == next_option)
395         options_left++;
396
397       /* adjust path for level directory accordingly */
398       options.level_directory =
399         getPath2(options.base_directory, LEVELS_DIRECTORY);
400     }
401     else if (strncmp(option, "-levels", option_len) == 0)
402     {
403       if (option_arg == NULL)
404         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
405
406       options.level_directory = option_arg;
407       if (option_arg == next_option)
408         options_left++;
409     }
410     else if (strncmp(option, "-network", option_len) == 0)
411     {
412       options.network = TRUE;
413     }
414     else if (strncmp(option, "-serveronly", option_len) == 0)
415     {
416       options.serveronly = TRUE;
417     }
418     else if (strncmp(option, "-verbose", option_len) == 0)
419     {
420       options.verbose = TRUE;
421     }
422     else if (*option == '-')
423     {
424       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
425     }
426     else if (options.server_host == NULL)
427     {
428       options.server_host = *options_left;
429     }
430     else if (options.server_port == 0)
431     {
432       options.server_port = atoi(*options_left);
433       if (options.server_port < 1024)
434         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
435     }
436     else
437       Error(ERR_EXIT_HELP, "too many arguments");
438
439     options_left++;
440   }
441 }
442
443 void Error(int mode, char *format, ...)
444 {
445   char *process_name = "";
446   FILE *error = stderr;
447
448 #ifdef MSDOS
449   if ((error = openErrorFile()) == NULL)
450   {
451     printf("Cannot write to error output file!\n");
452     CloseAllAndExit(1);
453   }
454 #endif
455
456   if (mode & ERR_SOUND_SERVER)
457     process_name = " sound server";
458   else if (mode & ERR_NETWORK_SERVER)
459     process_name = " network server";
460   else if (mode & ERR_NETWORK_CLIENT)
461     process_name = " network client **";
462
463   if (format)
464   {
465     va_list ap;
466
467     fprintf(error, "%s%s: ", program_name, process_name);
468
469     if (mode & ERR_WARN)
470       fprintf(error, "warning: ");
471
472     va_start(ap, format);
473     vfprintf(error, format, ap);
474     va_end(ap);
475   
476     fprintf(error, "\n");
477   }
478   
479   if (mode & ERR_HELP)
480     fprintf(error, "%s: Try option '--help' for more information.\n",
481             program_name);
482
483   if (mode & ERR_EXIT)
484     fprintf(error, "%s%s: aborting\n", program_name, process_name);
485
486   if (error != stderr)
487     fclose(error);
488
489   if (mode & ERR_EXIT)
490   {
491     if (mode & ERR_FROM_SERVER)
492       exit(1);                          /* child process: normal exit */
493     else
494       CloseAllAndExit(1);               /* main process: clean up stuff */
495   }
496 }
497
498 void *checked_malloc(unsigned long size)
499 {
500   void *ptr;
501
502   ptr = malloc(size);
503
504   if (ptr == NULL)
505     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
506
507   return ptr;
508 }
509
510 void *checked_calloc(unsigned long size)
511 {
512   void *ptr;
513
514   ptr = calloc(1, size);
515
516   if (ptr == NULL)
517     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
518
519   return ptr;
520 }
521
522 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
523 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
524 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
525
526 void translate_keyname(KeySym *keysym, char **x11name, char **name, int mode)
527 {
528   static struct
529   {
530     KeySym keysym;
531     char *x11name;
532     char *name;
533   } translate_key[] =
534   {
535     /* normal cursor keys */
536     { XK_Left,          "XK_Left",              "cursor left" },
537     { XK_Right,         "XK_Right",             "cursor right" },
538     { XK_Up,            "XK_Up",                "cursor up" },
539     { XK_Down,          "XK_Down",              "cursor down" },
540
541     /* keypad cursor keys */
542 #ifdef XK_KP_Left
543     { XK_KP_Left,       "XK_KP_Left",           "keypad left" },
544     { XK_KP_Right,      "XK_KP_Right",          "keypad right" },
545     { XK_KP_Up,         "XK_KP_Up",             "keypad up" },
546     { XK_KP_Down,       "XK_KP_Down",           "keypad down" },
547 #endif
548
549     /* other keypad keys */
550 #ifdef XK_KP_Enter
551     { XK_KP_Enter,      "XK_KP_Enter",          "keypad enter" },
552     { XK_KP_Add,        "XK_KP_Add",            "keypad +" },
553     { XK_KP_Subtract,   "XK_KP_Subtract",       "keypad -" },
554     { XK_KP_Multiply,   "XK_KP_Multiply",       "keypad mltply" },
555     { XK_KP_Divide,     "XK_KP_Divide",         "keypad /" },
556     { XK_KP_Separator,  "XK_KP_Separator",      "keypad ," },
557 #endif
558
559     /* modifier keys */
560     { XK_Shift_L,       "XK_Shift_L",           "left shift" },
561     { XK_Shift_R,       "XK_Shift_R",           "right shift" },
562     { XK_Control_L,     "XK_Control_L",         "left control" },
563     { XK_Control_R,     "XK_Control_R",         "right control" },
564     { XK_Meta_L,        "XK_Meta_L",            "left meta" },
565     { XK_Meta_R,        "XK_Meta_R",            "right meta" },
566     { XK_Alt_L,         "XK_Alt_L",             "left alt" },
567     { XK_Alt_R,         "XK_Alt_R",             "right alt" },
568     { XK_Mode_switch,   "XK_Mode_switch",       "mode switch" },
569     { XK_Multi_key,     "XK_Multi_key",         "multi key" },
570
571     /* some special keys */
572     { XK_BackSpace,     "XK_BackSpace",         "backspace" },
573     { XK_Delete,        "XK_Delete",            "delete" },
574     { XK_Insert,        "XK_Insert",            "insert" },
575     { XK_Tab,           "XK_Tab",               "tab" },
576     { XK_Home,          "XK_Home",              "home" },
577     { XK_End,           "XK_End",               "end" },
578     { XK_Page_Up,       "XK_Page_Up",           "page up" },
579     { XK_Page_Down,     "XK_Page_Down",         "page down" },
580     { XK_space,         "XK_space",             "space" },
581
582     /* even more special keys */
583     { XK_adiaeresis,    "XK_adiaeresis",        "ä" },
584     { XK_odiaeresis,    "XK_odiaeresis",        "ö" },
585     { XK_udiaeresis,    "XK_udiaeresis",        "Ă¼" },
586     { XK_apostrophe,    "XK_apostrophe",        "'" },
587     { XK_plus,          "XK_plus",              "+" },
588     { XK_minus,         "XK_minus",             "-" },
589     { XK_equal,         "XK_equal",             "equal" },
590     { XK_comma,         "XK_comma",             "," },
591     { XK_period,        "XK_period",            "." },
592     { XK_colon,         "XK_colon",             ";" },
593     { XK_slash,         "XK_slash",             "/" },
594     { XK_numbersign,    "XK_numbersign",        "#" },
595     { XK_backslash,     "XK_backslash",         "backslash" },
596     { XK_braceleft,     "XK_braceleft",         "brace left" },
597     { XK_braceright,    "XK_braceright",        "brace right" },
598     { XK_less,          "XK_less",              "less" },
599     { XK_greater,       "XK_greater",           "greater" },
600     { XK_asciicircum,   "XK_asciicircum",       "circumflex" },
601     { XK_ssharp,        "XK_ssharp",            "sharp s" },
602
603     /* end-of-array identifier */
604     { 0,                NULL,                   NULL }
605   };
606
607   int i;
608
609   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
610   {
611     static char name_buffer[30];
612     KeySym key = *keysym;
613
614     if (key >= XK_A && key <= XK_Z)
615       sprintf(name_buffer, "%c", 'A' + (char)(key - XK_A));
616     else if (key >= XK_a && key <= XK_z)
617       sprintf(name_buffer, "%c", 'a' + (char)(key - XK_a));
618     else if (key >= XK_0 && key <= XK_9)
619       sprintf(name_buffer, "%c", '0' + (char)(key - XK_0));
620     else if (key >= XK_KP_0 && key <= XK_KP_9)
621       sprintf(name_buffer, "keypad %c", '0' + (char)(key - XK_KP_0));
622     else if (key >= XK_F1 && key <= XK_F24)
623       sprintf(name_buffer, "function F%d", (int)(key - XK_F1 + 1));
624     else if (key == KEY_UNDEFINDED)
625       strcpy(name_buffer, "(undefined)");
626     else
627     {
628       i = 0;
629
630       do
631       {
632         if (key == translate_key[i].keysym)
633         {
634           strcpy(name_buffer, translate_key[i].name);
635           break;
636         }
637       }
638       while (translate_key[++i].name);
639
640       if (!translate_key[i].name)
641         strcpy(name_buffer, "(unknown)");
642     }
643
644     *name = name_buffer;
645   }
646   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
647   {
648     static char name_buffer[30];
649     KeySym key = *keysym;
650
651     if (key >= XK_A && key <= XK_Z)
652       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - XK_A));
653     else if (key >= XK_a && key <= XK_z)
654       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - XK_a));
655     else if (key >= XK_0 && key <= XK_9)
656       sprintf(name_buffer, "XK_%c", '0' + (char)(key - XK_0));
657     else if (key >= XK_KP_0 && key <= XK_KP_9)
658       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - XK_KP_0));
659     else if (key >= XK_F1 && key <= XK_F24)
660       sprintf(name_buffer, "XK_F%d", (int)(key - XK_F1 + 1));
661     else if (key == KEY_UNDEFINDED)
662       strcpy(name_buffer, "[undefined]");
663     else
664     {
665       i = 0;
666
667       do
668       {
669         if (key == translate_key[i].keysym)
670         {
671           strcpy(name_buffer, translate_key[i].x11name);
672           break;
673         }
674       }
675       while (translate_key[++i].x11name);
676
677       if (!translate_key[i].x11name)
678         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
679     }
680
681     *x11name = name_buffer;
682   }
683   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
684   {
685     KeySym key = XK_VoidSymbol;
686     char *name_ptr = *x11name;
687
688     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
689     {
690       char c = name_ptr[3];
691
692       if (c >= 'A' && c <= 'Z')
693         key = XK_A + (KeySym)(c - 'A');
694       else if (c >= 'a' && c <= 'z')
695         key = XK_a + (KeySym)(c - 'a');
696       else if (c >= '0' && c <= '9')
697         key = XK_0 + (KeySym)(c - '0');
698     }
699     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
700     {
701       char c = name_ptr[6];
702
703       if (c >= '0' && c <= '9')
704         key = XK_0 + (KeySym)(c - '0');
705     }
706     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
707     {
708       char c1 = name_ptr[4];
709       char c2 = name_ptr[5];
710       int d = 0;
711
712       if ((c1 >= '0' && c1 <= '9') &&
713           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
714         d = atoi(&name_ptr[4]);
715
716       if (d >=1 && d <= 24)
717         key = XK_F1 + (KeySym)(d - 1);
718     }
719     else if (strncmp(name_ptr, "XK_", 3) == 0)
720     {
721       i = 0;
722
723       do
724       {
725         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
726         {
727           key = translate_key[i].keysym;
728           break;
729         }
730       }
731       while (translate_key[++i].x11name);
732     }
733     else if (strncmp(name_ptr, "0x", 2) == 0)
734     {
735       unsigned long value = 0;
736
737       name_ptr += 2;
738
739       while (name_ptr)
740       {
741         char c = *name_ptr++;
742         int d = -1;
743
744         if (c >= '0' && c <= '9')
745           d = (int)(c - '0');
746         else if (c >= 'a' && c <= 'f')
747           d = (int)(c - 'a' + 10);
748         else if (c >= 'A' && c <= 'F')
749           d = (int)(c - 'A' + 10);
750
751         if (d == -1)
752         {
753           value = -1;
754           break;
755         }
756
757         value = value * 16 + d;
758       }
759
760       if (value != -1)
761         key = (KeySym)value;
762     }
763
764     *keysym = key;
765   }
766 }
767
768 char *getKeyNameFromKeySym(KeySym keysym)
769 {
770   char *name;
771
772   translate_keyname(&keysym, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
773   return name;
774 }
775
776 char *getX11KeyNameFromKeySym(KeySym keysym)
777 {
778   char *x11name;
779
780   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
781   return x11name;
782 }
783
784 KeySym getKeySymFromX11KeyName(char *x11name)
785 {
786   KeySym keysym;
787
788   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
789   return keysym;
790 }
791
792 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
793 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
794
795 void translate_joyname(int *joysymbol, char **name, int mode)
796 {
797   static struct
798   {
799     int joysymbol;
800     char *name;
801   } translate_joy[] =
802   {
803     { JOY_LEFT,         "joystick_left" },
804     { JOY_RIGHT,        "joystick_right" },
805     { JOY_UP,           "joystick_up" },
806     { JOY_DOWN,         "joystick_down" },
807     { JOY_BUTTON_1,     "joystick_button_1" },
808     { JOY_BUTTON_2,     "joystick_button_2" },
809   };
810
811   int i;
812
813   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
814   {
815     *name = "[undefined]";
816
817     for (i=0; i<6; i++)
818     {
819       if (*joysymbol == translate_joy[i].joysymbol)
820       {
821         *name = translate_joy[i].name;
822         break;
823       }
824     }
825   }
826   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
827   {
828     *joysymbol = 0;
829
830     for (i=0; i<6; i++)
831     {
832       if (strcmp(*name, translate_joy[i].name) == 0)
833       {
834         *joysymbol = translate_joy[i].joysymbol;
835         break;
836       }
837     }
838   }
839 }
840
841 char *getJoyNameFromJoySymbol(int joysymbol)
842 {
843   char *name;
844
845   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
846   return name;
847 }
848
849 int getJoySymbolFromJoyName(char *name)
850 {
851   int joysymbol;
852
853   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
854   return joysymbol;
855 }
856
857 int getJoystickNrFromDeviceName(char *device_name)
858 {
859   char c;
860   int joystick_nr = 0;
861
862   if (device_name == NULL || device_name[0] == '\0')
863     return 0;
864
865   c = device_name[strlen(device_name) - 1];
866
867   if (c >= '0' && c <= '9')
868     joystick_nr = (int)(c - '0');
869
870   if (joystick_nr < 0 || joystick_nr >= MAX_PLAYERS)
871     joystick_nr = 0;
872
873   return joystick_nr;
874 }
875
876 /* ----------------------------------------------------------------- */
877 /* the following is only for debugging purpose and normally not used */
878 /* ----------------------------------------------------------------- */
879
880 #define DEBUG_NUM_TIMESTAMPS    3
881
882 void debug_print_timestamp(int counter_nr, char *message)
883 {
884   static long counter[DEBUG_NUM_TIMESTAMPS][2];
885
886   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
887     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
888
889   counter[counter_nr][0] = Counter();
890
891   if (message)
892     printf("%s %.2f seconds\n", message,
893            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
894
895   counter[counter_nr][1] = Counter();
896 }