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