9fc0cf0405cfb3bdc3e6e4308e1ddf43bfd2c092
[rocksndiamonds.git] / src / libgame / misc.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2001 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * misc.c                                                   *
12 ***********************************************************/
13
14 #include <time.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 /*
18 #include <sys/stat.h>
19 */
20 #include <stdarg.h>
21 #include <ctype.h>
22 #include <string.h>
23 #include <unistd.h>
24
25 #include "platform.h"
26
27 #if !defined(PLATFORM_WIN32)
28 #include <pwd.h>
29 #include <sys/param.h>
30 #endif
31
32 #include "misc.h"
33 #include "setup.h"
34 #include "random.h"
35
36
37 #if defined(PLATFORM_MSDOS)
38 volatile unsigned long counter = 0;
39
40 void increment_counter()
41 {
42   counter++;
43 }
44
45 END_OF_FUNCTION(increment_counter);
46 #endif
47
48
49 /* maximal allowed length of a command line option */
50 #define MAX_OPTION_LEN          256
51
52 #ifdef TARGET_SDL
53 static unsigned long mainCounter(int mode)
54 {
55   static unsigned long base_ms = 0;
56   unsigned long current_ms;
57   unsigned long counter_ms;
58
59   current_ms = SDL_GetTicks();
60
61   /* reset base time in case of counter initializing or wrap-around */
62   if (mode == INIT_COUNTER || current_ms < base_ms)
63     base_ms = current_ms;
64
65   counter_ms = current_ms - base_ms;
66
67   return counter_ms;            /* return milliseconds since last init */
68 }
69
70 #else /* !TARGET_SDL */
71
72 #if defined(PLATFORM_UNIX)
73 static unsigned long mainCounter(int mode)
74 {
75   static struct timeval base_time = { 0, 0 };
76   struct timeval current_time;
77   unsigned long counter_ms;
78
79   gettimeofday(&current_time, NULL);
80
81   /* reset base time in case of counter initializing or wrap-around */
82   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
83     base_time = current_time;
84
85   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
86              + (current_time.tv_usec - base_time.tv_usec) / 1000;
87
88   return counter_ms;            /* return milliseconds since last init */
89 }
90 #endif /* PLATFORM_UNIX */
91 #endif /* !TARGET_SDL */
92
93 void InitCounter()              /* set counter back to zero */
94 {
95 #if !defined(PLATFORM_MSDOS)
96   mainCounter(INIT_COUNTER);
97 #else
98   LOCK_VARIABLE(counter);
99   LOCK_FUNCTION(increment_counter);
100   install_int_ex(increment_counter, BPS_TO_TIMER(100));
101 #endif
102 }
103
104 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
105 {
106 #if !defined(PLATFORM_MSDOS)
107   return mainCounter(READ_COUNTER);
108 #else
109   return (counter * 10);
110 #endif
111 }
112
113 static void sleep_milliseconds(unsigned long milliseconds_delay)
114 {
115   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
116
117 #if defined(PLATFORM_MSDOS)
118   /* don't use select() to perform waiting operations under DOS/Windows
119      environment; always use a busy loop for waiting instead */
120   do_busy_waiting = TRUE;
121 #endif
122
123   if (do_busy_waiting)
124   {
125     /* we want to wait only a few ms -- if we assume that we have a
126        kernel timer resolution of 10 ms, we would wait far to long;
127        therefore it's better to do a short interval of busy waiting
128        to get our sleeping time more accurate */
129
130     unsigned long base_counter = Counter(), actual_counter = Counter();
131
132     while (actual_counter < base_counter + milliseconds_delay &&
133            actual_counter >= base_counter)
134       actual_counter = Counter();
135   }
136   else
137   {
138 #if defined(TARGET_SDL)
139     SDL_Delay(milliseconds_delay);
140 #else
141     struct timeval delay;
142
143     delay.tv_sec  = milliseconds_delay / 1000;
144     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
145
146     if (select(0, NULL, NULL, NULL, &delay) != 0)
147       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
148 #endif
149   }
150 }
151
152 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
153 {
154   sleep_milliseconds(delay);
155 }
156
157 boolean FrameReached(unsigned long *frame_counter_var,
158                      unsigned long frame_delay)
159 {
160   unsigned long actual_frame_counter = FrameCounter;
161
162   if (actual_frame_counter < *frame_counter_var+frame_delay &&
163       actual_frame_counter >= *frame_counter_var)
164     return(FALSE);
165
166   *frame_counter_var = actual_frame_counter;
167   return(TRUE);
168 }
169
170 boolean DelayReached(unsigned long *counter_var,
171                      unsigned long delay)
172 {
173   unsigned long actual_counter = Counter();
174
175   if (actual_counter < *counter_var + delay &&
176       actual_counter >= *counter_var)
177     return(FALSE);
178
179   *counter_var = actual_counter;
180   return(TRUE);
181 }
182
183 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
184 {
185   unsigned long actual_counter;
186
187   while(1)
188   {
189     actual_counter = Counter();
190
191     if (actual_counter < *counter_var + delay &&
192         actual_counter >= *counter_var)
193       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
194     else
195       break;
196   }
197
198   *counter_var = actual_counter;
199 }
200
201 /* int2str() returns a number converted to a string;
202    the used memory is static, but will be overwritten by later calls,
203    so if you want to save the result, copy it to a private string buffer;
204    there can be 10 local calls of int2str() without buffering the result --
205    the 11th call will then destroy the result from the first call and so on.
206 */
207
208 char *int2str(int number, int size)
209 {
210   static char shift_array[10][40];
211   static int shift_counter = 0;
212   char *s = shift_array[shift_counter];
213
214   shift_counter = (shift_counter + 1) % 10;
215
216   if (size > 20)
217     size = 20;
218
219   if (size)
220   {
221     sprintf(s, "                    %09d", number);
222     return &s[strlen(s) - size];
223   }
224   else
225   {
226     sprintf(s, "%d", number);
227     return s;
228   }
229 }
230
231 unsigned int SimpleRND(unsigned int max)
232 {
233 #if defined(TARGET_SDL)
234   static unsigned long root = 654321;
235   unsigned long current_ms;
236
237   current_ms = SDL_GetTicks();
238   root = root * 4253261 + current_ms;
239   return (root % max);
240 #else
241   static unsigned long root = 654321;
242   struct timeval current_time;
243
244   gettimeofday(&current_time, NULL);
245   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
246   return (root % max);
247 #endif
248 }
249
250 #ifdef DEBUG
251 static unsigned int last_RND_value = 0;
252
253 unsigned int last_RND()
254 {
255   return last_RND_value;
256 }
257 #endif
258
259 unsigned int RND(unsigned int max)
260 {
261 #ifdef DEBUG
262   return (last_RND_value = random_linux_libc() % max);
263 #else
264   return (random_linux_libc() % max);
265 #endif
266 }
267
268 unsigned int InitRND(long seed)
269 {
270 #if defined(TARGET_SDL)
271   unsigned long current_ms;
272
273   if (seed == NEW_RANDOMIZE)
274   {
275     current_ms = SDL_GetTicks();
276     srandom_linux_libc((unsigned int) current_ms);
277     return (unsigned int) current_ms;
278   }
279   else
280   {
281     srandom_linux_libc((unsigned int) seed);
282     return (unsigned int) seed;
283   }
284 #else
285   struct timeval current_time;
286
287   if (seed == NEW_RANDOMIZE)
288   {
289     gettimeofday(&current_time, NULL);
290     srandom_linux_libc((unsigned int) current_time.tv_usec);
291     return (unsigned int) current_time.tv_usec;
292   }
293   else
294   {
295     srandom_linux_libc((unsigned int) seed);
296     return (unsigned int) seed;
297   }
298 #endif
299 }
300
301 char *getLoginName()
302 {
303 #if defined(PLATFORM_WIN32)
304   return ANONYMOUS_NAME;
305 #else
306   struct passwd *pwd;
307
308   if ((pwd = getpwuid(getuid())) == NULL)
309     return ANONYMOUS_NAME;
310   else
311     return pwd->pw_name;
312 #endif
313 }
314
315 char *getRealName()
316 {
317 #if defined(PLATFORM_UNIX)
318   struct passwd *pwd;
319
320   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
321     return ANONYMOUS_NAME;
322   else
323   {
324     static char real_name[1024];
325     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
326
327     if (strchr(pwd->pw_gecos, 'ß') == NULL)
328       return pwd->pw_gecos;
329
330     /* the user's real name contains a 'ß' character (german sharp s),
331        which has no equivalent in upper case letters (which our fonts use) */
332     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
333     {
334       if (*from_ptr != 'ß')
335         *to_ptr++ = *from_ptr++;
336       else
337       {
338         from_ptr++;
339         *to_ptr++ = 's';
340         *to_ptr++ = 's';
341       }
342     }
343     *to_ptr = '\0';
344
345     return real_name;
346   }
347 #else /* !PLATFORM_UNIX */
348   return ANONYMOUS_NAME;
349 #endif
350 }
351
352 char *getHomeDir()
353 {
354 #if defined(PLATFORM_UNIX)
355   static char *home_dir = NULL;
356
357   if (!home_dir)
358   {
359     if (!(home_dir = getenv("HOME")))
360     {
361       struct passwd *pwd;
362
363       if ((pwd = getpwuid(getuid())))
364         home_dir = pwd->pw_dir;
365       else
366         home_dir = ".";
367     }
368   }
369
370   return home_dir;
371 #else
372   return ".";
373 #endif
374 }
375
376 char *getPath2(char *path1, char *path2)
377 {
378   char *complete_path = checked_malloc(strlen(path1) + 1 +
379                                        strlen(path2) + 1);
380
381   sprintf(complete_path, "%s/%s", path1, path2);
382   return complete_path;
383 }
384
385 char *getPath3(char *path1, char *path2, char *path3)
386 {
387   char *complete_path = checked_malloc(strlen(path1) + 1 +
388                                        strlen(path2) + 1 +
389                                        strlen(path3) + 1);
390
391   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
392   return complete_path;
393 }
394
395 char *getStringCopy(char *s)
396 {
397   char *s_copy;
398
399   if (s == NULL)
400     return NULL;
401
402   s_copy = checked_malloc(strlen(s) + 1);
403
404   strcpy(s_copy, s);
405   return s_copy;
406 }
407
408 char *getStringToLower(char *s)
409 {
410   char *s_copy = checked_malloc(strlen(s) + 1);
411   char *s_ptr = s_copy;
412
413   while (*s)
414     *s_ptr++ = tolower(*s++);
415   *s_ptr = '\0';
416
417   return s_copy;
418 }
419
420 void GetOptions(char *argv[])
421 {
422   char **options_left = &argv[1];
423
424   /* initialize global program options */
425   options.display_name = NULL;
426   options.server_host = NULL;
427   options.server_port = 0;
428   options.ro_base_directory = RO_BASE_PATH;
429   options.rw_base_directory = RW_BASE_PATH;
430   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
431   options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
432   options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
433   options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
434   options.serveronly = FALSE;
435   options.network = FALSE;
436   options.verbose = FALSE;
437   options.debug = FALSE;
438
439   while (*options_left)
440   {
441     char option_str[MAX_OPTION_LEN];
442     char *option = options_left[0];
443     char *next_option = options_left[1];
444     char *option_arg = NULL;
445     int option_len = strlen(option);
446
447     if (option_len >= MAX_OPTION_LEN)
448       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
449
450     strcpy(option_str, option);                 /* copy argument into buffer */
451     option = option_str;
452
453     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
454       break;
455
456     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
457       option++;
458
459     option_arg = strchr(option, '=');
460     if (option_arg == NULL)                     /* no '=' in option */
461       option_arg = next_option;
462     else
463     {
464       *option_arg++ = '\0';                     /* cut argument from option */
465       if (*option_arg == '\0')                  /* no argument after '=' */
466         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
467     }
468
469     option_len = strlen(option);
470
471     if (strcmp(option, "-") == 0)
472       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
473     else if (strncmp(option, "-help", option_len) == 0)
474     {
475       printf("Usage: %s [options] [server.name [port]]\n"
476              "Options:\n"
477              "  -d, --display <host>[:<scr>]  X server display\n"
478              "  -b, --basepath <directory>    alternative base directory\n"
479              "  -l, --level <directory>       alternative level directory\n"
480              "  -g, --graphics <directory>    alternative graphics directory\n"
481              "  -s, --sounds <directory>      alternative graphics directory\n"
482              "  -m, --music <directory>       alternative graphics directory\n"
483              "  -n, --network                 network multiplayer game\n"
484              "      --serveronly              only start network server\n"
485              "  -v, --verbose                 verbose mode\n"
486              "      --debug                   display debugging information\n",
487              program.command_basename);
488       exit(0);
489     }
490     else if (strncmp(option, "-display", option_len) == 0)
491     {
492       if (option_arg == NULL)
493         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
494
495       options.display_name = option_arg;
496       if (option_arg == next_option)
497         options_left++;
498     }
499     else if (strncmp(option, "-basepath", option_len) == 0)
500     {
501       if (option_arg == NULL)
502         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
503
504       /* this should be extended to separate options for ro and rw data */
505       options.ro_base_directory = option_arg;
506       options.rw_base_directory = option_arg;
507       if (option_arg == next_option)
508         options_left++;
509
510       /* adjust path for level directory accordingly */
511       options.level_directory =
512         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
513     }
514     else if (strncmp(option, "-levels", option_len) == 0)
515     {
516       if (option_arg == NULL)
517         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
518
519       options.level_directory = option_arg;
520       if (option_arg == next_option)
521         options_left++;
522     }
523     else if (strncmp(option, "-graphics", option_len) == 0)
524     {
525       if (option_arg == NULL)
526         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
527
528       options.graphics_directory = option_arg;
529       if (option_arg == next_option)
530         options_left++;
531     }
532     else if (strncmp(option, "-sounds", option_len) == 0)
533     {
534       if (option_arg == NULL)
535         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
536
537       options.sounds_directory = option_arg;
538       if (option_arg == next_option)
539         options_left++;
540     }
541     else if (strncmp(option, "-music", option_len) == 0)
542     {
543       if (option_arg == NULL)
544         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
545
546       options.music_directory = option_arg;
547       if (option_arg == next_option)
548         options_left++;
549     }
550     else if (strncmp(option, "-network", option_len) == 0)
551     {
552       options.network = TRUE;
553     }
554     else if (strncmp(option, "-serveronly", option_len) == 0)
555     {
556       options.serveronly = TRUE;
557     }
558     else if (strncmp(option, "-verbose", option_len) == 0)
559     {
560       options.verbose = TRUE;
561     }
562     else if (strncmp(option, "-debug", option_len) == 0)
563     {
564       options.debug = TRUE;
565     }
566     else if (*option == '-')
567     {
568       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
569     }
570     else if (options.server_host == NULL)
571     {
572       options.server_host = *options_left;
573     }
574     else if (options.server_port == 0)
575     {
576       options.server_port = atoi(*options_left);
577       if (options.server_port < 1024)
578         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
579     }
580     else
581       Error(ERR_EXIT_HELP, "too many arguments");
582
583     options_left++;
584   }
585 }
586
587 void Error(int mode, char *format, ...)
588 {
589   char *process_name = "";
590   FILE *error = stderr;
591   char *newline = "\n";
592
593   /* display warnings only when running in verbose mode */
594   if (mode & ERR_WARN && !options.verbose)
595     return;
596
597 #if !defined(PLATFORM_UNIX)
598   newline = "\r\n";
599
600   if ((error = openErrorFile()) == NULL)
601   {
602     printf("Cannot write to error output file!%s", newline);
603     program.exit_function(1);
604   }
605 #endif
606
607   if (mode & ERR_SOUND_SERVER)
608     process_name = " sound server";
609   else if (mode & ERR_NETWORK_SERVER)
610     process_name = " network server";
611   else if (mode & ERR_NETWORK_CLIENT)
612     process_name = " network client **";
613
614   if (format)
615   {
616     va_list ap;
617
618     fprintf(error, "%s%s: ", program.command_basename, process_name);
619
620     if (mode & ERR_WARN)
621       fprintf(error, "warning: ");
622
623     va_start(ap, format);
624     vfprintf(error, format, ap);
625     va_end(ap);
626   
627     fprintf(error, "%s", newline);
628   }
629   
630   if (mode & ERR_HELP)
631     fprintf(error, "%s: Try option '--help' for more information.%s",
632             program.command_basename, newline);
633
634   if (mode & ERR_EXIT)
635     fprintf(error, "%s%s: aborting%s",
636             program.command_basename, process_name, newline);
637
638   if (error != stderr)
639     fclose(error);
640
641   if (mode & ERR_EXIT)
642   {
643     if (mode & ERR_FROM_SERVER)
644       exit(1);                          /* child process: normal exit */
645     else
646       program.exit_function(1);         /* main process: clean up stuff */
647   }
648 }
649
650 void *checked_malloc(unsigned long size)
651 {
652   void *ptr;
653
654   ptr = malloc(size);
655
656   if (ptr == NULL)
657     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
658
659   return ptr;
660 }
661
662 void *checked_calloc(unsigned long size)
663 {
664   void *ptr;
665
666   ptr = calloc(1, size);
667
668   if (ptr == NULL)
669     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
670
671   return ptr;
672 }
673
674 void *checked_realloc(void *ptr, unsigned long size)
675 {
676   ptr = realloc(ptr, size);
677
678   if (ptr == NULL)
679     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
680
681   return ptr;
682 }
683
684 inline void swap_numbers(int *i1, int *i2)
685 {
686   int help = *i1;
687
688   *i1 = *i2;
689   *i2 = help;
690 }
691
692 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
693 {
694   int help_x = *x1;
695   int help_y = *y1;
696
697   *x1 = *x2;
698   *x2 = help_x;
699
700   *y1 = *y2;
701   *y2 = help_y;
702 }
703
704 short getFile16BitInteger(FILE *file, int byte_order)
705 {
706   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
707     return ((fgetc(file) <<  8) |
708             (fgetc(file) <<  0));
709   else           /* BYTE_ORDER_LITTLE_ENDIAN */
710     return ((fgetc(file) <<  0) |
711             (fgetc(file) <<  8));
712 }
713
714 void putFile16BitInteger(FILE *file, short value, int byte_order)
715 {
716   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
717   {
718     fputc((value >>  8) & 0xff, file);
719     fputc((value >>  0) & 0xff, file);
720   }
721   else           /* BYTE_ORDER_LITTLE_ENDIAN */
722   {
723     fputc((value >>  0) & 0xff, file);
724     fputc((value >>  8) & 0xff, file);
725   }
726 }
727
728 int getFile32BitInteger(FILE *file, int byte_order)
729 {
730   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
731     return ((fgetc(file) << 24) |
732             (fgetc(file) << 16) |
733             (fgetc(file) <<  8) |
734             (fgetc(file) <<  0));
735   else           /* BYTE_ORDER_LITTLE_ENDIAN */
736     return ((fgetc(file) <<  0) |
737             (fgetc(file) <<  8) |
738             (fgetc(file) << 16) |
739             (fgetc(file) << 24));
740 }
741
742 void putFile32BitInteger(FILE *file, int value, int byte_order)
743 {
744   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
745   {
746     fputc((value >> 24) & 0xff, file);
747     fputc((value >> 16) & 0xff, file);
748     fputc((value >>  8) & 0xff, file);
749     fputc((value >>  0) & 0xff, file);
750   }
751   else           /* BYTE_ORDER_LITTLE_ENDIAN */
752   {
753     fputc((value >>  0) & 0xff, file);
754     fputc((value >>  8) & 0xff, file);
755     fputc((value >> 16) & 0xff, file);
756     fputc((value >> 24) & 0xff, file);
757   }
758 }
759
760 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
761                      int byte_order)
762 {
763   const int chunk_name_length = 4;
764
765   /* read chunk name */
766   fgets(chunk_name, chunk_name_length + 1, file);
767
768   if (chunk_size != NULL)
769   {
770     /* read chunk size */
771     *chunk_size = getFile32BitInteger(file, byte_order);
772   }
773
774   return (feof(file) || ferror(file) ? FALSE : TRUE);
775 }
776
777 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
778                   int byte_order)
779 {
780   /* write chunk name */
781   fputs(chunk_name, file);
782
783   if (chunk_size >= 0)
784   {
785     /* write chunk size */
786     putFile32BitInteger(file, chunk_size, byte_order);
787   }
788 }
789
790 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
791 {
792   while (bytes--)
793     fgetc(file);
794 }
795
796 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
797 {
798   while (bytes--)
799     fputc(0, file);
800 }
801
802 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
803 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
804 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
805
806 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
807 {
808   static struct
809   {
810     Key key;
811     char *x11name;
812     char *name;
813   } translate_key[] =
814   {
815     /* normal cursor keys */
816     { KSYM_Left,        "XK_Left",              "cursor left" },
817     { KSYM_Right,       "XK_Right",             "cursor right" },
818     { KSYM_Up,          "XK_Up",                "cursor up" },
819     { KSYM_Down,        "XK_Down",              "cursor down" },
820
821     /* keypad cursor keys */
822 #ifdef KSYM_KP_Left
823     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
824     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
825     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
826     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
827 #endif
828
829     /* other keypad keys */
830 #ifdef KSYM_KP_Enter
831     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
832     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
833     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
834     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
835     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
836     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
837 #endif
838
839     /* modifier keys */
840     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
841     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
842     { KSYM_Control_L,   "XK_Control_L",         "left control" },
843     { KSYM_Control_R,   "XK_Control_R",         "right control" },
844     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
845     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
846     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
847     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
848     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
849     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
850     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
851     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
852
853     /* some special keys */
854     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
855     { KSYM_Delete,      "XK_Delete",            "delete" },
856     { KSYM_Insert,      "XK_Insert",            "insert" },
857     { KSYM_Tab,         "XK_Tab",               "tab" },
858     { KSYM_Home,        "XK_Home",              "home" },
859     { KSYM_End,         "XK_End",               "end" },
860     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
861     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
862     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
863
864     /* ASCII 0x20 to 0x40 keys (except numbers) */
865     { KSYM_space,       "XK_space",             "space" },
866     { KSYM_exclam,      "XK_exclam",            "!" },
867     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
868     { KSYM_numbersign,  "XK_numbersign",        "#" },
869     { KSYM_dollar,      "XK_dollar",            "$" },
870     { KSYM_percent,     "XK_percent",           "%" },
871     { KSYM_ampersand,   "XK_ampersand",         "&" },
872     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
873     { KSYM_parenleft,   "XK_parenleft",         "(" },
874     { KSYM_parenright,  "XK_parenright",        ")" },
875     { KSYM_asterisk,    "XK_asterisk",          "*" },
876     { KSYM_plus,        "XK_plus",              "+" },
877     { KSYM_comma,       "XK_comma",             "," },
878     { KSYM_minus,       "XK_minus",             "-" },
879     { KSYM_period,      "XK_period",            "." },
880     { KSYM_slash,       "XK_slash",             "/" },
881     { KSYM_colon,       "XK_colon",             ":" },
882     { KSYM_semicolon,   "XK_semicolon",         ";" },
883     { KSYM_less,        "XK_less",              "<" },
884     { KSYM_equal,       "XK_equal",             "=" },
885     { KSYM_greater,     "XK_greater",           ">" },
886     { KSYM_question,    "XK_question",          "?" },
887     { KSYM_at,          "XK_at",                "@" },
888
889     /* more ASCII keys */
890     { KSYM_bracketleft, "XK_bracketleft",       "[" },
891     { KSYM_backslash,   "XK_backslash",         "backslash" },
892     { KSYM_bracketright,"XK_bracketright",      "]" },
893     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
894     { KSYM_underscore,  "XK_underscore",        "_" },
895     { KSYM_grave,       "XK_grave",             "grave" },
896     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
897     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
898     { KSYM_bar,         "XK_bar",               "bar" },
899     { KSYM_braceright,  "XK_braceright",        "brace right" },
900     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
901
902     /* special (non-ASCII) keys */
903     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
904     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
905     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ü" },
906     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
907     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
908     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
909     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
910
911     /* end-of-array identifier */
912     { 0,                NULL,                   NULL }
913   };
914
915   int i;
916
917   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
918   {
919     static char name_buffer[30];
920     Key key = *keysym;
921
922     if (key >= KSYM_A && key <= KSYM_Z)
923       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
924     else if (key >= KSYM_a && key <= KSYM_z)
925       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
926     else if (key >= KSYM_0 && key <= KSYM_9)
927       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
928     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
929       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
930     else if (key >= KSYM_F1 && key <= KSYM_F24)
931       sprintf(name_buffer, "function F%d", (int)(key - KSYM_F1 + 1));
932     else if (key == KSYM_UNDEFINED)
933       strcpy(name_buffer, "(undefined)");
934     else
935     {
936       i = 0;
937
938       do
939       {
940         if (key == translate_key[i].key)
941         {
942           strcpy(name_buffer, translate_key[i].name);
943           break;
944         }
945       }
946       while (translate_key[++i].name);
947
948       if (!translate_key[i].name)
949         strcpy(name_buffer, "(unknown)");
950     }
951
952     *name = name_buffer;
953   }
954   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
955   {
956     static char name_buffer[30];
957     Key key = *keysym;
958
959     if (key >= KSYM_A && key <= KSYM_Z)
960       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
961     else if (key >= KSYM_a && key <= KSYM_z)
962       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
963     else if (key >= KSYM_0 && key <= KSYM_9)
964       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
965     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
966       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
967     else if (key >= KSYM_F1 && key <= KSYM_F24)
968       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_F1 + 1));
969     else if (key == KSYM_UNDEFINED)
970       strcpy(name_buffer, "[undefined]");
971     else
972     {
973       i = 0;
974
975       do
976       {
977         if (key == translate_key[i].key)
978         {
979           strcpy(name_buffer, translate_key[i].x11name);
980           break;
981         }
982       }
983       while (translate_key[++i].x11name);
984
985       if (!translate_key[i].x11name)
986         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
987     }
988
989     *x11name = name_buffer;
990   }
991   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
992   {
993     Key key = KSYM_UNDEFINED;
994     char *name_ptr = *x11name;
995
996     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
997     {
998       char c = name_ptr[3];
999
1000       if (c >= 'A' && c <= 'Z')
1001         key = KSYM_A + (Key)(c - 'A');
1002       else if (c >= 'a' && c <= 'z')
1003         key = KSYM_a + (Key)(c - 'a');
1004       else if (c >= '0' && c <= '9')
1005         key = KSYM_0 + (Key)(c - '0');
1006     }
1007     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1008     {
1009       char c = name_ptr[6];
1010
1011       if (c >= '0' && c <= '9')
1012         key = KSYM_0 + (Key)(c - '0');
1013     }
1014     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1015     {
1016       char c1 = name_ptr[4];
1017       char c2 = name_ptr[5];
1018       int d = 0;
1019
1020       if ((c1 >= '0' && c1 <= '9') &&
1021           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1022         d = atoi(&name_ptr[4]);
1023
1024       if (d >=1 && d <= 24)
1025         key = KSYM_F1 + (Key)(d - 1);
1026     }
1027     else if (strncmp(name_ptr, "XK_", 3) == 0)
1028     {
1029       i = 0;
1030
1031       do
1032       {
1033         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1034         {
1035           key = translate_key[i].key;
1036           break;
1037         }
1038       }
1039       while (translate_key[++i].x11name);
1040     }
1041     else if (strncmp(name_ptr, "0x", 2) == 0)
1042     {
1043       unsigned long value = 0;
1044
1045       name_ptr += 2;
1046
1047       while (name_ptr)
1048       {
1049         char c = *name_ptr++;
1050         int d = -1;
1051
1052         if (c >= '0' && c <= '9')
1053           d = (int)(c - '0');
1054         else if (c >= 'a' && c <= 'f')
1055           d = (int)(c - 'a' + 10);
1056         else if (c >= 'A' && c <= 'F')
1057           d = (int)(c - 'A' + 10);
1058
1059         if (d == -1)
1060         {
1061           value = -1;
1062           break;
1063         }
1064
1065         value = value * 16 + d;
1066       }
1067
1068       if (value != -1)
1069         key = (Key)value;
1070     }
1071
1072     *keysym = key;
1073   }
1074 }
1075
1076 char *getKeyNameFromKey(Key key)
1077 {
1078   char *name;
1079
1080   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1081   return name;
1082 }
1083
1084 char *getX11KeyNameFromKey(Key key)
1085 {
1086   char *x11name;
1087
1088   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1089   return x11name;
1090 }
1091
1092 Key getKeyFromX11KeyName(char *x11name)
1093 {
1094   Key key;
1095
1096   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1097   return key;
1098 }
1099
1100 char getCharFromKey(Key key)
1101 {
1102   char *keyname = getKeyNameFromKey(key);
1103   char letter = 0;
1104
1105   if (strlen(keyname) == 1)
1106     letter = keyname[0];
1107   else if (strcmp(keyname, "space") == 0)
1108     letter = ' ';
1109   else if (strcmp(keyname, "circumflex") == 0)
1110     letter = '^';
1111
1112   return letter;
1113 }
1114
1115
1116 /* ========================================================================= */
1117 /* functions only needed for non-Unix (non-command-line) systems */
1118 /* ========================================================================= */
1119
1120 #if !defined(PLATFORM_UNIX)
1121
1122 #define ERROR_FILENAME          "error.out"
1123
1124 void initErrorFile()
1125 {
1126   char *filename;
1127
1128   InitUserDataDirectory();
1129
1130   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1131   unlink(filename);
1132   free(filename);
1133 }
1134
1135 FILE *openErrorFile()
1136 {
1137   char *filename;
1138   FILE *error_file;
1139
1140   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1141   error_file = fopen(filename, MODE_APPEND);
1142   free(filename);
1143
1144   return error_file;
1145 }
1146
1147 void dumpErrorFile()
1148 {
1149   char *filename;
1150   FILE *error_file;
1151
1152   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1153   error_file = fopen(filename, MODE_READ);
1154   free(filename);
1155
1156   if (error_file != NULL)
1157   {
1158     while (!feof(error_file))
1159       fputc(fgetc(error_file), stderr);
1160
1161     fclose(error_file);
1162   }
1163 }
1164 #endif
1165
1166
1167 /* ========================================================================= */
1168 /* the following is only for debugging purpose and normally not used         */
1169 /* ========================================================================= */
1170
1171 #define DEBUG_NUM_TIMESTAMPS    3
1172
1173 void debug_print_timestamp(int counter_nr, char *message)
1174 {
1175   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1176
1177   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1178     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1179
1180   counter[counter_nr][0] = Counter();
1181
1182   if (message)
1183     printf("%s %.2f seconds\n", message,
1184            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1185
1186   counter[counter_nr][1] = Counter();
1187 }