rnd-20020402-1-src
[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 /* used by SetError() and GetError() to store internal error messages */
588 static char internal_error[1024];       /* this is bad */
589
590 void SetError(char *format, ...)
591 {
592   va_list ap;
593
594   va_start(ap, format);
595   vsprintf(internal_error, format, ap);
596   va_end(ap);
597 }
598
599 char *GetError()
600 {
601   return internal_error;
602 }
603
604 void Error(int mode, char *format, ...)
605 {
606   char *process_name = "";
607   FILE *error = stderr;
608   char *newline = "\n";
609
610   /* display warnings only when running in verbose mode */
611   if (mode & ERR_WARN && !options.verbose)
612     return;
613
614 #if !defined(PLATFORM_UNIX)
615   newline = "\r\n";
616
617   if ((error = openErrorFile()) == NULL)
618   {
619     printf("Cannot write to error output file!%s", newline);
620     program.exit_function(1);
621   }
622 #endif
623
624   if (mode & ERR_SOUND_SERVER)
625     process_name = " sound server";
626   else if (mode & ERR_NETWORK_SERVER)
627     process_name = " network server";
628   else if (mode & ERR_NETWORK_CLIENT)
629     process_name = " network client **";
630
631   if (format)
632   {
633     va_list ap;
634
635     fprintf(error, "%s%s: ", program.command_basename, process_name);
636
637     if (mode & ERR_WARN)
638       fprintf(error, "warning: ");
639
640     va_start(ap, format);
641     vfprintf(error, format, ap);
642     va_end(ap);
643   
644     fprintf(error, "%s", newline);
645   }
646   
647   if (mode & ERR_HELP)
648     fprintf(error, "%s: Try option '--help' for more information.%s",
649             program.command_basename, newline);
650
651   if (mode & ERR_EXIT)
652     fprintf(error, "%s%s: aborting%s",
653             program.command_basename, process_name, newline);
654
655   if (error != stderr)
656     fclose(error);
657
658   if (mode & ERR_EXIT)
659   {
660     if (mode & ERR_FROM_SERVER)
661       exit(1);                          /* child process: normal exit */
662     else
663       program.exit_function(1);         /* main process: clean up stuff */
664   }
665 }
666
667 void *checked_malloc(unsigned long size)
668 {
669   void *ptr;
670
671   ptr = malloc(size);
672
673   if (ptr == NULL)
674     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
675
676   return ptr;
677 }
678
679 void *checked_calloc(unsigned long size)
680 {
681   void *ptr;
682
683   ptr = calloc(1, size);
684
685   if (ptr == NULL)
686     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
687
688   return ptr;
689 }
690
691 void *checked_realloc(void *ptr, unsigned long size)
692 {
693   ptr = realloc(ptr, size);
694
695   if (ptr == NULL)
696     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
697
698   return ptr;
699 }
700
701 inline void swap_numbers(int *i1, int *i2)
702 {
703   int help = *i1;
704
705   *i1 = *i2;
706   *i2 = help;
707 }
708
709 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
710 {
711   int help_x = *x1;
712   int help_y = *y1;
713
714   *x1 = *x2;
715   *x2 = help_x;
716
717   *y1 = *y2;
718   *y2 = help_y;
719 }
720
721 short getFile16BitInteger(FILE *file, int byte_order)
722 {
723   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
724     return ((fgetc(file) <<  8) |
725             (fgetc(file) <<  0));
726   else           /* BYTE_ORDER_LITTLE_ENDIAN */
727     return ((fgetc(file) <<  0) |
728             (fgetc(file) <<  8));
729 }
730
731 void putFile16BitInteger(FILE *file, short value, int byte_order)
732 {
733   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
734   {
735     fputc((value >>  8) & 0xff, file);
736     fputc((value >>  0) & 0xff, file);
737   }
738   else           /* BYTE_ORDER_LITTLE_ENDIAN */
739   {
740     fputc((value >>  0) & 0xff, file);
741     fputc((value >>  8) & 0xff, file);
742   }
743 }
744
745 int getFile32BitInteger(FILE *file, int byte_order)
746 {
747   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
748     return ((fgetc(file) << 24) |
749             (fgetc(file) << 16) |
750             (fgetc(file) <<  8) |
751             (fgetc(file) <<  0));
752   else           /* BYTE_ORDER_LITTLE_ENDIAN */
753     return ((fgetc(file) <<  0) |
754             (fgetc(file) <<  8) |
755             (fgetc(file) << 16) |
756             (fgetc(file) << 24));
757 }
758
759 void putFile32BitInteger(FILE *file, int value, int byte_order)
760 {
761   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
762   {
763     fputc((value >> 24) & 0xff, file);
764     fputc((value >> 16) & 0xff, file);
765     fputc((value >>  8) & 0xff, file);
766     fputc((value >>  0) & 0xff, file);
767   }
768   else           /* BYTE_ORDER_LITTLE_ENDIAN */
769   {
770     fputc((value >>  0) & 0xff, file);
771     fputc((value >>  8) & 0xff, file);
772     fputc((value >> 16) & 0xff, file);
773     fputc((value >> 24) & 0xff, file);
774   }
775 }
776
777 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
778                      int byte_order)
779 {
780   const int chunk_name_length = 4;
781
782   /* read chunk name */
783   fgets(chunk_name, chunk_name_length + 1, file);
784
785   if (chunk_size != NULL)
786   {
787     /* read chunk size */
788     *chunk_size = getFile32BitInteger(file, byte_order);
789   }
790
791   return (feof(file) || ferror(file) ? FALSE : TRUE);
792 }
793
794 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
795                   int byte_order)
796 {
797   /* write chunk name */
798   fputs(chunk_name, file);
799
800   if (chunk_size >= 0)
801   {
802     /* write chunk size */
803     putFile32BitInteger(file, chunk_size, byte_order);
804   }
805 }
806
807 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
808 {
809   while (bytes--)
810     fgetc(file);
811 }
812
813 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
814 {
815   while (bytes--)
816     fputc(0, file);
817 }
818
819 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
820 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
821 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
822 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
823
824 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
825 {
826   static struct
827   {
828     Key key;
829     char *x11name;
830     char *name;
831   } translate_key[] =
832   {
833     /* normal cursor keys */
834     { KSYM_Left,        "XK_Left",              "cursor left" },
835     { KSYM_Right,       "XK_Right",             "cursor right" },
836     { KSYM_Up,          "XK_Up",                "cursor up" },
837     { KSYM_Down,        "XK_Down",              "cursor down" },
838
839     /* keypad cursor keys */
840 #ifdef KSYM_KP_Left
841     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
842     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
843     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
844     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
845 #endif
846
847     /* other keypad keys */
848 #ifdef KSYM_KP_Enter
849     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
850     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
851     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
852     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
853     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
854     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
855 #endif
856
857     /* modifier keys */
858     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
859     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
860     { KSYM_Control_L,   "XK_Control_L",         "left control" },
861     { KSYM_Control_R,   "XK_Control_R",         "right control" },
862     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
863     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
864     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
865     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
866     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
867     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
868     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
869     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
870
871     /* some special keys */
872     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
873     { KSYM_Delete,      "XK_Delete",            "delete" },
874     { KSYM_Insert,      "XK_Insert",            "insert" },
875     { KSYM_Tab,         "XK_Tab",               "tab" },
876     { KSYM_Home,        "XK_Home",              "home" },
877     { KSYM_End,         "XK_End",               "end" },
878     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
879     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
880     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
881
882     /* ASCII 0x20 to 0x40 keys (except numbers) */
883     { KSYM_space,       "XK_space",             "space" },
884     { KSYM_exclam,      "XK_exclam",            "!" },
885     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
886     { KSYM_numbersign,  "XK_numbersign",        "#" },
887     { KSYM_dollar,      "XK_dollar",            "$" },
888     { KSYM_percent,     "XK_percent",           "%" },
889     { KSYM_ampersand,   "XK_ampersand",         "&" },
890     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
891     { KSYM_parenleft,   "XK_parenleft",         "(" },
892     { KSYM_parenright,  "XK_parenright",        ")" },
893     { KSYM_asterisk,    "XK_asterisk",          "*" },
894     { KSYM_plus,        "XK_plus",              "+" },
895     { KSYM_comma,       "XK_comma",             "," },
896     { KSYM_minus,       "XK_minus",             "-" },
897     { KSYM_period,      "XK_period",            "." },
898     { KSYM_slash,       "XK_slash",             "/" },
899     { KSYM_colon,       "XK_colon",             ":" },
900     { KSYM_semicolon,   "XK_semicolon",         ";" },
901     { KSYM_less,        "XK_less",              "<" },
902     { KSYM_equal,       "XK_equal",             "=" },
903     { KSYM_greater,     "XK_greater",           ">" },
904     { KSYM_question,    "XK_question",          "?" },
905     { KSYM_at,          "XK_at",                "@" },
906
907     /* more ASCII keys */
908     { KSYM_bracketleft, "XK_bracketleft",       "[" },
909     { KSYM_backslash,   "XK_backslash",         "backslash" },
910     { KSYM_bracketright,"XK_bracketright",      "]" },
911     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
912     { KSYM_underscore,  "XK_underscore",        "_" },
913     { KSYM_grave,       "XK_grave",             "grave" },
914     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
915     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
916     { KSYM_bar,         "XK_bar",               "bar" },
917     { KSYM_braceright,  "XK_braceright",        "brace right" },
918     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
919
920     /* special (non-ASCII) keys */
921     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
922     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
923     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
924     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
925     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
926     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
927     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
928
929     /* end-of-array identifier */
930     { 0,                NULL,                   NULL }
931   };
932
933   int i;
934
935   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
936   {
937     static char name_buffer[30];
938     Key key = *keysym;
939
940     if (key >= KSYM_A && key <= KSYM_Z)
941       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
942     else if (key >= KSYM_a && key <= KSYM_z)
943       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
944     else if (key >= KSYM_0 && key <= KSYM_9)
945       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
946     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
947       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
948     else if (key >= KSYM_F1 && key <= KSYM_F24)
949       sprintf(name_buffer, "function F%d", (int)(key - KSYM_F1 + 1));
950     else if (key == KSYM_UNDEFINED)
951       strcpy(name_buffer, "(undefined)");
952     else
953     {
954       i = 0;
955
956       do
957       {
958         if (key == translate_key[i].key)
959         {
960           strcpy(name_buffer, translate_key[i].name);
961           break;
962         }
963       }
964       while (translate_key[++i].name);
965
966       if (!translate_key[i].name)
967         strcpy(name_buffer, "(unknown)");
968     }
969
970     *name = name_buffer;
971   }
972   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
973   {
974     static char name_buffer[30];
975     Key key = *keysym;
976
977     if (key >= KSYM_A && key <= KSYM_Z)
978       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
979     else if (key >= KSYM_a && key <= KSYM_z)
980       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
981     else if (key >= KSYM_0 && key <= KSYM_9)
982       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
983     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
984       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
985     else if (key >= KSYM_F1 && key <= KSYM_F24)
986       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_F1 + 1));
987     else if (key == KSYM_UNDEFINED)
988       strcpy(name_buffer, "[undefined]");
989     else
990     {
991       i = 0;
992
993       do
994       {
995         if (key == translate_key[i].key)
996         {
997           strcpy(name_buffer, translate_key[i].x11name);
998           break;
999         }
1000       }
1001       while (translate_key[++i].x11name);
1002
1003       if (!translate_key[i].x11name)
1004         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1005     }
1006
1007     *x11name = name_buffer;
1008   }
1009   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1010   {
1011     Key key = KSYM_UNDEFINED;
1012
1013     i = 0;
1014     do
1015     {
1016       if (strcmp(translate_key[i].name, *name) == 0)
1017       {
1018         key = translate_key[i].key;
1019         break;
1020       }
1021     }
1022     while (translate_key[++i].x11name);
1023
1024     if (key == KSYM_UNDEFINED)
1025       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1026
1027     *keysym = key;
1028   }
1029   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1030   {
1031     Key key = KSYM_UNDEFINED;
1032     char *name_ptr = *x11name;
1033
1034     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1035     {
1036       char c = name_ptr[3];
1037
1038       if (c >= 'A' && c <= 'Z')
1039         key = KSYM_A + (Key)(c - 'A');
1040       else if (c >= 'a' && c <= 'z')
1041         key = KSYM_a + (Key)(c - 'a');
1042       else if (c >= '0' && c <= '9')
1043         key = KSYM_0 + (Key)(c - '0');
1044     }
1045     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1046     {
1047       char c = name_ptr[6];
1048
1049       if (c >= '0' && c <= '9')
1050         key = KSYM_0 + (Key)(c - '0');
1051     }
1052     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1053     {
1054       char c1 = name_ptr[4];
1055       char c2 = name_ptr[5];
1056       int d = 0;
1057
1058       if ((c1 >= '0' && c1 <= '9') &&
1059           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1060         d = atoi(&name_ptr[4]);
1061
1062       if (d >=1 && d <= 24)
1063         key = KSYM_F1 + (Key)(d - 1);
1064     }
1065     else if (strncmp(name_ptr, "XK_", 3) == 0)
1066     {
1067       i = 0;
1068
1069       do
1070       {
1071         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1072         {
1073           key = translate_key[i].key;
1074           break;
1075         }
1076       }
1077       while (translate_key[++i].x11name);
1078     }
1079     else if (strncmp(name_ptr, "0x", 2) == 0)
1080     {
1081       unsigned long value = 0;
1082
1083       name_ptr += 2;
1084
1085       while (name_ptr)
1086       {
1087         char c = *name_ptr++;
1088         int d = -1;
1089
1090         if (c >= '0' && c <= '9')
1091           d = (int)(c - '0');
1092         else if (c >= 'a' && c <= 'f')
1093           d = (int)(c - 'a' + 10);
1094         else if (c >= 'A' && c <= 'F')
1095           d = (int)(c - 'A' + 10);
1096
1097         if (d == -1)
1098         {
1099           value = -1;
1100           break;
1101         }
1102
1103         value = value * 16 + d;
1104       }
1105
1106       if (value != -1)
1107         key = (Key)value;
1108     }
1109
1110     *keysym = key;
1111   }
1112 }
1113
1114 char *getKeyNameFromKey(Key key)
1115 {
1116   char *name;
1117
1118   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1119   return name;
1120 }
1121
1122 char *getX11KeyNameFromKey(Key key)
1123 {
1124   char *x11name;
1125
1126   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1127   return x11name;
1128 }
1129
1130 Key getKeyFromKeyName(char *name)
1131 {
1132   Key key;
1133
1134   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1135   return key;
1136 }
1137
1138 Key getKeyFromX11KeyName(char *x11name)
1139 {
1140   Key key;
1141
1142   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1143   return key;
1144 }
1145
1146 char getCharFromKey(Key key)
1147 {
1148   char *keyname = getKeyNameFromKey(key);
1149   char letter = 0;
1150
1151   if (strlen(keyname) == 1)
1152     letter = keyname[0];
1153   else if (strcmp(keyname, "space") == 0)
1154     letter = ' ';
1155   else if (strcmp(keyname, "circumflex") == 0)
1156     letter = '^';
1157
1158   return letter;
1159 }
1160
1161
1162 /* ========================================================================= */
1163 /* functions for checking filenames                                          */
1164 /* ========================================================================= */
1165
1166 boolean FileIsGraphic(char *filename)
1167 {
1168   if (strlen(filename) > 4 &&
1169       strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1170     return TRUE;
1171
1172   return FALSE;
1173 }
1174
1175 boolean FileIsSound(char *filename)
1176 {
1177   if (strlen(filename) > 4 &&
1178       strcmp(&filename[strlen(filename) - 4], ".wav") == 0)
1179     return TRUE;
1180
1181   return FALSE;
1182 }
1183
1184 boolean FileIsMusic(char *filename)
1185 {
1186   if (strlen(filename) > 4 &&
1187       (strcmp(&filename[strlen(filename) - 4], ".mod") == 0 ||
1188        strcmp(&filename[strlen(filename) - 4], ".MOD") == 0 ||
1189        strncmp(filename, "mod.", 4) == 0 ||
1190        strncmp(filename, "MOD.", 4) == 0))
1191     return TRUE;
1192
1193   return FALSE;
1194 }
1195
1196 /* ========================================================================= */
1197 /* functions only needed for non-Unix (non-command-line) systems */
1198 /* ========================================================================= */
1199
1200 #if !defined(PLATFORM_UNIX)
1201
1202 #define ERROR_FILENAME          "error.out"
1203
1204 void initErrorFile()
1205 {
1206   char *filename;
1207
1208   InitUserDataDirectory();
1209
1210   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1211   unlink(filename);
1212   free(filename);
1213 }
1214
1215 FILE *openErrorFile()
1216 {
1217   char *filename;
1218   FILE *error_file;
1219
1220   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1221   error_file = fopen(filename, MODE_APPEND);
1222   free(filename);
1223
1224   return error_file;
1225 }
1226
1227 void dumpErrorFile()
1228 {
1229   char *filename;
1230   FILE *error_file;
1231
1232   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1233   error_file = fopen(filename, MODE_READ);
1234   free(filename);
1235
1236   if (error_file != NULL)
1237   {
1238     while (!feof(error_file))
1239       fputc(fgetc(error_file), stderr);
1240
1241     fclose(error_file);
1242   }
1243 }
1244 #endif
1245
1246
1247 /* ========================================================================= */
1248 /* the following is only for debugging purpose and normally not used         */
1249 /* ========================================================================= */
1250
1251 #define DEBUG_NUM_TIMESTAMPS    3
1252
1253 void debug_print_timestamp(int counter_nr, char *message)
1254 {
1255   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1256
1257   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1258     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1259
1260   counter[counter_nr][0] = Counter();
1261
1262   if (message)
1263     printf("%s %.2f seconds\n", message,
1264            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1265
1266   counter[counter_nr][1] = Counter();
1267 }