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