1 /***********************************************************
2 * Artsoft Retro-Game Library *
3 *----------------------------------------------------------*
4 * (c) 1994-2001 Artsoft Entertainment *
6 * Detmolder Strasse 189 *
9 * e-mail: info@artsoft.org *
10 *----------------------------------------------------------*
12 ***********************************************************/
16 #include <sys/types.h>
25 #if !defined(PLATFORM_WIN32)
27 #include <sys/param.h>
34 #if defined(PLATFORM_MSDOS)
35 volatile unsigned long counter = 0;
37 void increment_counter()
42 END_OF_FUNCTION(increment_counter);
46 /* maximal allowed length of a command line option */
47 #define MAX_OPTION_LEN 256
50 static unsigned long mainCounter(int mode)
52 static unsigned long base_ms = 0;
53 unsigned long current_ms;
54 unsigned long counter_ms;
56 current_ms = SDL_GetTicks();
58 /* reset base time in case of counter initializing or wrap-around */
59 if (mode == INIT_COUNTER || current_ms < base_ms)
62 counter_ms = current_ms - base_ms;
64 return counter_ms; /* return milliseconds since last init */
67 #else /* !TARGET_SDL */
69 #if defined(PLATFORM_UNIX)
70 static unsigned long mainCounter(int mode)
72 static struct timeval base_time = { 0, 0 };
73 struct timeval current_time;
74 unsigned long counter_ms;
76 gettimeofday(¤t_time, NULL);
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;
82 counter_ms = (current_time.tv_sec - base_time.tv_sec) * 1000
83 + (current_time.tv_usec - base_time.tv_usec) / 1000;
85 return counter_ms; /* return milliseconds since last init */
87 #endif /* PLATFORM_UNIX */
88 #endif /* !TARGET_SDL */
90 void InitCounter() /* set counter back to zero */
92 #if !defined(PLATFORM_MSDOS)
93 mainCounter(INIT_COUNTER);
95 LOCK_VARIABLE(counter);
96 LOCK_FUNCTION(increment_counter);
97 install_int_ex(increment_counter, BPS_TO_TIMER(100));
101 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
103 #if !defined(PLATFORM_MSDOS)
104 return mainCounter(READ_COUNTER);
106 return (counter * 10);
110 static void sleep_milliseconds(unsigned long milliseconds_delay)
112 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
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;
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 */
127 unsigned long base_counter = Counter(), actual_counter = Counter();
129 while (actual_counter < base_counter + milliseconds_delay &&
130 actual_counter >= base_counter)
131 actual_counter = Counter();
135 #if defined(TARGET_SDL)
136 SDL_Delay(milliseconds_delay);
138 struct timeval delay;
140 delay.tv_sec = milliseconds_delay / 1000;
141 delay.tv_usec = 1000 * (milliseconds_delay % 1000);
143 if (select(0, NULL, NULL, NULL, &delay) != 0)
144 Error(ERR_WARN, "sleep_milliseconds(): select() failed");
149 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
151 sleep_milliseconds(delay);
154 boolean FrameReached(unsigned long *frame_counter_var,
155 unsigned long frame_delay)
157 unsigned long actual_frame_counter = FrameCounter;
159 if (actual_frame_counter < *frame_counter_var+frame_delay &&
160 actual_frame_counter >= *frame_counter_var)
163 *frame_counter_var = actual_frame_counter;
167 boolean DelayReached(unsigned long *counter_var,
170 unsigned long actual_counter = Counter();
172 if (actual_counter < *counter_var + delay &&
173 actual_counter >= *counter_var)
176 *counter_var = actual_counter;
180 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
182 unsigned long actual_counter;
186 actual_counter = Counter();
188 if (actual_counter < *counter_var + delay &&
189 actual_counter >= *counter_var)
190 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
195 *counter_var = actual_counter;
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.
205 char *int2str(int number, int size)
207 static char shift_array[10][40];
208 static int shift_counter = 0;
209 char *s = shift_array[shift_counter];
211 shift_counter = (shift_counter + 1) % 10;
218 sprintf(s, " %09d", number);
219 return &s[strlen(s) - size];
223 sprintf(s, "%d", number);
228 unsigned int SimpleRND(unsigned int max)
230 #if defined(TARGET_SDL)
231 static unsigned long root = 654321;
232 unsigned long current_ms;
234 current_ms = SDL_GetTicks();
235 root = root * 4253261 + current_ms;
238 static unsigned long root = 654321;
239 struct timeval current_time;
241 gettimeofday(¤t_time, NULL);
242 root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
248 static unsigned int last_RND_value = 0;
250 unsigned int last_RND()
252 return last_RND_value;
256 unsigned int RND(unsigned int max)
259 return (last_RND_value = random_linux_libc() % max);
261 return (random_linux_libc() % max);
265 unsigned int InitRND(long seed)
267 #if defined(TARGET_SDL)
268 unsigned long current_ms;
270 if (seed == NEW_RANDOMIZE)
272 current_ms = SDL_GetTicks();
273 srandom_linux_libc((unsigned int) current_ms);
274 return (unsigned int) current_ms;
278 srandom_linux_libc((unsigned int) seed);
279 return (unsigned int) seed;
282 struct timeval current_time;
284 if (seed == NEW_RANDOMIZE)
286 gettimeofday(¤t_time, NULL);
287 srandom_linux_libc((unsigned int) current_time.tv_usec);
288 return (unsigned int) current_time.tv_usec;
292 srandom_linux_libc((unsigned int) seed);
293 return (unsigned int) seed;
300 #if defined(PLATFORM_WIN32)
301 return ANONYMOUS_NAME;
305 if ((pwd = getpwuid(getuid())) == NULL)
306 return ANONYMOUS_NAME;
314 #if defined(PLATFORM_UNIX)
317 if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
318 return ANONYMOUS_NAME;
321 static char real_name[1024];
322 char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
324 if (strchr(pwd->pw_gecos, 'ß') == NULL)
325 return pwd->pw_gecos;
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)
331 if (*from_ptr != 'ß')
332 *to_ptr++ = *from_ptr++;
344 #else /* !PLATFORM_UNIX */
345 return ANONYMOUS_NAME;
351 #if defined(PLATFORM_UNIX)
352 static char *home_dir = NULL;
356 if (!(home_dir = getenv("HOME")))
360 if ((pwd = getpwuid(getuid())))
361 home_dir = pwd->pw_dir;
373 char *getPath2(char *path1, char *path2)
375 char *complete_path = checked_malloc(strlen(path1) + 1 +
378 sprintf(complete_path, "%s/%s", path1, path2);
379 return complete_path;
382 char *getPath3(char *path1, char *path2, char *path3)
384 char *complete_path = checked_malloc(strlen(path1) + 1 +
388 sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
389 return complete_path;
392 char *getStringCopy(char *s)
399 s_copy = checked_malloc(strlen(s) + 1);
405 char *getStringToLower(char *s)
407 char *s_copy = checked_malloc(strlen(s) + 1);
408 char *s_ptr = s_copy;
411 *s_ptr++ = tolower(*s++);
417 void GetOptions(char *argv[])
419 char **options_left = &argv[1];
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.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
429 options.serveronly = FALSE;
430 options.network = FALSE;
431 options.verbose = FALSE;
432 options.debug = FALSE;
434 while (*options_left)
436 char option_str[MAX_OPTION_LEN];
437 char *option = options_left[0];
438 char *next_option = options_left[1];
439 char *option_arg = NULL;
440 int option_len = strlen(option);
442 if (option_len >= MAX_OPTION_LEN)
443 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
445 strcpy(option_str, option); /* copy argument into buffer */
448 if (strcmp(option, "--") == 0) /* stop scanning arguments */
451 if (strncmp(option, "--", 2) == 0) /* treat '--' like '-' */
454 option_arg = strchr(option, '=');
455 if (option_arg == NULL) /* no '=' in option */
456 option_arg = next_option;
459 *option_arg++ = '\0'; /* cut argument from option */
460 if (*option_arg == '\0') /* no argument after '=' */
461 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
464 option_len = strlen(option);
466 if (strcmp(option, "-") == 0)
467 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
468 else if (strncmp(option, "-help", option_len) == 0)
470 printf("Usage: %s [options] [server.name [port]]\n"
472 " -d, --display machine:0 X server display\n"
473 " -b, --basepath directory alternative base directory\n"
474 " -l, --level directory alternative level directory\n"
475 " -g, --graphics directory alternative graphics directory\n"
476 " -n, --network network multiplayer game\n"
477 " -s, --serveronly only start network server\n"
478 " -v, --verbose verbose mode\n"
479 " --debug display debugging information\n",
480 program.command_basename);
483 else if (strncmp(option, "-display", option_len) == 0)
485 if (option_arg == NULL)
486 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
488 options.display_name = option_arg;
489 if (option_arg == next_option)
492 else if (strncmp(option, "-basepath", option_len) == 0)
494 if (option_arg == NULL)
495 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
497 /* this should be extended to separate options for ro and rw data */
498 options.ro_base_directory = option_arg;
499 options.rw_base_directory = option_arg;
500 if (option_arg == next_option)
503 /* adjust path for level directory accordingly */
504 options.level_directory =
505 getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
507 else if (strncmp(option, "-levels", option_len) == 0)
509 if (option_arg == NULL)
510 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
512 options.level_directory = option_arg;
513 if (option_arg == next_option)
516 else if (strncmp(option, "-graphics", option_len) == 0)
518 if (option_arg == NULL)
519 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
521 options.graphics_directory = option_arg;
522 if (option_arg == next_option)
525 else if (strncmp(option, "-network", option_len) == 0)
527 options.network = TRUE;
529 else if (strncmp(option, "-serveronly", option_len) == 0)
531 options.serveronly = TRUE;
533 else if (strncmp(option, "-verbose", option_len) == 0)
535 options.verbose = TRUE;
537 else if (strncmp(option, "-debug", option_len) == 0)
539 options.debug = TRUE;
541 else if (*option == '-')
543 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
545 else if (options.server_host == NULL)
547 options.server_host = *options_left;
549 else if (options.server_port == 0)
551 options.server_port = atoi(*options_left);
552 if (options.server_port < 1024)
553 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
556 Error(ERR_EXIT_HELP, "too many arguments");
562 void Error(int mode, char *format, ...)
564 char *process_name = "";
565 FILE *error = stderr;
566 char *newline = "\n";
568 /* display warnings only when running in verbose mode */
569 if (mode & ERR_WARN && !options.verbose)
572 #if !defined(PLATFORM_UNIX)
575 if ((error = openErrorFile()) == NULL)
577 printf("Cannot write to error output file!%s", newline);
578 program.exit_function(1);
582 if (mode & ERR_SOUND_SERVER)
583 process_name = " sound server";
584 else if (mode & ERR_NETWORK_SERVER)
585 process_name = " network server";
586 else if (mode & ERR_NETWORK_CLIENT)
587 process_name = " network client **";
593 fprintf(error, "%s%s: ", program.command_basename, process_name);
596 fprintf(error, "warning: ");
598 va_start(ap, format);
599 vfprintf(error, format, ap);
602 fprintf(error, "%s", newline);
606 fprintf(error, "%s: Try option '--help' for more information.%s",
607 program.command_basename, newline);
610 fprintf(error, "%s%s: aborting%s",
611 program.command_basename, process_name, newline);
618 if (mode & ERR_FROM_SERVER)
619 exit(1); /* child process: normal exit */
621 program.exit_function(1); /* main process: clean up stuff */
625 void *checked_malloc(unsigned long size)
632 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
637 void *checked_calloc(unsigned long size)
641 ptr = calloc(1, size);
644 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
649 void *checked_realloc(void *ptr, unsigned long size)
651 ptr = realloc(ptr, size);
654 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
659 short getFile16BitInteger(FILE *file, int byte_order)
661 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
662 return ((fgetc(file) << 8) |
664 else /* BYTE_ORDER_LITTLE_ENDIAN */
665 return ((fgetc(file) << 0) |
669 void putFile16BitInteger(FILE *file, short value, int byte_order)
671 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
673 fputc((value >> 8) & 0xff, file);
674 fputc((value >> 0) & 0xff, file);
676 else /* BYTE_ORDER_LITTLE_ENDIAN */
678 fputc((value >> 0) & 0xff, file);
679 fputc((value >> 8) & 0xff, file);
683 int getFile32BitInteger(FILE *file, int byte_order)
685 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
686 return ((fgetc(file) << 24) |
687 (fgetc(file) << 16) |
690 else /* BYTE_ORDER_LITTLE_ENDIAN */
691 return ((fgetc(file) << 0) |
693 (fgetc(file) << 16) |
694 (fgetc(file) << 24));
697 void putFile32BitInteger(FILE *file, int value, int byte_order)
699 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
701 fputc((value >> 24) & 0xff, file);
702 fputc((value >> 16) & 0xff, file);
703 fputc((value >> 8) & 0xff, file);
704 fputc((value >> 0) & 0xff, file);
706 else /* BYTE_ORDER_LITTLE_ENDIAN */
708 fputc((value >> 0) & 0xff, file);
709 fputc((value >> 8) & 0xff, file);
710 fputc((value >> 16) & 0xff, file);
711 fputc((value >> 24) & 0xff, file);
715 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
718 const int chunk_name_length = 4;
720 /* read chunk name */
721 fgets(chunk_name, chunk_name_length + 1, file);
723 if (chunk_size != NULL)
725 /* read chunk size */
726 *chunk_size = getFile32BitInteger(file, byte_order);
729 return (feof(file) || ferror(file) ? FALSE : TRUE);
732 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
735 /* write chunk name */
736 fputs(chunk_name, file);
740 /* write chunk size */
741 putFile32BitInteger(file, chunk_size, byte_order);
745 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
751 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
757 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
758 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
759 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 2
761 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
770 /* normal cursor keys */
771 { KSYM_Left, "XK_Left", "cursor left" },
772 { KSYM_Right, "XK_Right", "cursor right" },
773 { KSYM_Up, "XK_Up", "cursor up" },
774 { KSYM_Down, "XK_Down", "cursor down" },
776 /* keypad cursor keys */
778 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
779 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
780 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
781 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
784 /* other keypad keys */
786 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
787 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
788 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
789 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
790 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
791 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
795 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
796 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
797 { KSYM_Control_L, "XK_Control_L", "left control" },
798 { KSYM_Control_R, "XK_Control_R", "right control" },
799 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
800 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
801 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
802 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
803 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
804 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
805 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
806 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
808 /* some special keys */
809 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
810 { KSYM_Delete, "XK_Delete", "delete" },
811 { KSYM_Insert, "XK_Insert", "insert" },
812 { KSYM_Tab, "XK_Tab", "tab" },
813 { KSYM_Home, "XK_Home", "home" },
814 { KSYM_End, "XK_End", "end" },
815 { KSYM_Page_Up, "XK_Page_Up", "page up" },
816 { KSYM_Page_Down, "XK_Page_Down", "page down" },
817 { KSYM_Menu, "XK_Menu", "menu" }, /* Win-Menu */
819 /* ASCII 0x20 to 0x40 keys (except numbers) */
820 { KSYM_space, "XK_space", "space" },
821 { KSYM_exclam, "XK_exclam", "!" },
822 { KSYM_quotedbl, "XK_quotedbl", "\"" },
823 { KSYM_numbersign, "XK_numbersign", "#" },
824 { KSYM_dollar, "XK_dollar", "$" },
825 { KSYM_percent, "XK_percent", "%" },
826 { KSYM_ampersand, "XK_ampersand", "&" },
827 { KSYM_apostrophe, "XK_apostrophe", "'" },
828 { KSYM_parenleft, "XK_parenleft", "(" },
829 { KSYM_parenright, "XK_parenright", ")" },
830 { KSYM_asterisk, "XK_asterisk", "*" },
831 { KSYM_plus, "XK_plus", "+" },
832 { KSYM_comma, "XK_comma", "," },
833 { KSYM_minus, "XK_minus", "-" },
834 { KSYM_period, "XK_period", "." },
835 { KSYM_slash, "XK_slash", "/" },
836 { KSYM_colon, "XK_colon", ":" },
837 { KSYM_semicolon, "XK_semicolon", ";" },
838 { KSYM_less, "XK_less", "<" },
839 { KSYM_equal, "XK_equal", "=" },
840 { KSYM_greater, "XK_greater", ">" },
841 { KSYM_question, "XK_question", "?" },
842 { KSYM_at, "XK_at", "@" },
844 /* more ASCII keys */
845 { KSYM_bracketleft, "XK_bracketleft", "[" },
846 { KSYM_backslash, "XK_backslash", "backslash" },
847 { KSYM_bracketright,"XK_bracketright", "]" },
848 { KSYM_asciicircum, "XK_asciicircum", "circumflex" },
849 { KSYM_underscore, "XK_underscore", "_" },
850 { KSYM_grave, "XK_grave", "grave" },
851 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
852 { KSYM_braceleft, "XK_braceleft", "brace left" },
853 { KSYM_bar, "XK_bar", "bar" },
854 { KSYM_braceright, "XK_braceright", "brace right" },
855 { KSYM_asciitilde, "XK_asciitilde", "ascii tilde" },
857 /* special (non-ASCII) keys */
858 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
859 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
860 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
861 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
862 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
863 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
864 { KSYM_ssharp, "XK_ssharp", "sharp s" },
866 /* end-of-array identifier */
872 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
874 static char name_buffer[30];
877 if (key >= KSYM_A && key <= KSYM_Z)
878 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
879 else if (key >= KSYM_a && key <= KSYM_z)
880 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
881 else if (key >= KSYM_0 && key <= KSYM_9)
882 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
883 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
884 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
885 else if (key >= KSYM_F1 && key <= KSYM_F24)
886 sprintf(name_buffer, "function F%d", (int)(key - KSYM_F1 + 1));
887 else if (key == KSYM_UNDEFINED)
888 strcpy(name_buffer, "(undefined)");
895 if (key == translate_key[i].key)
897 strcpy(name_buffer, translate_key[i].name);
901 while (translate_key[++i].name);
903 if (!translate_key[i].name)
904 strcpy(name_buffer, "(unknown)");
909 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
911 static char name_buffer[30];
914 if (key >= KSYM_A && key <= KSYM_Z)
915 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
916 else if (key >= KSYM_a && key <= KSYM_z)
917 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
918 else if (key >= KSYM_0 && key <= KSYM_9)
919 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
920 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
921 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
922 else if (key >= KSYM_F1 && key <= KSYM_F24)
923 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_F1 + 1));
924 else if (key == KSYM_UNDEFINED)
925 strcpy(name_buffer, "[undefined]");
932 if (key == translate_key[i].key)
934 strcpy(name_buffer, translate_key[i].x11name);
938 while (translate_key[++i].x11name);
940 if (!translate_key[i].x11name)
941 sprintf(name_buffer, "0x%04lx", (unsigned long)key);
944 *x11name = name_buffer;
946 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
948 Key key = KSYM_UNDEFINED;
949 char *name_ptr = *x11name;
951 if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
953 char c = name_ptr[3];
955 if (c >= 'A' && c <= 'Z')
956 key = KSYM_A + (Key)(c - 'A');
957 else if (c >= 'a' && c <= 'z')
958 key = KSYM_a + (Key)(c - 'a');
959 else if (c >= '0' && c <= '9')
960 key = KSYM_0 + (Key)(c - '0');
962 else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
964 char c = name_ptr[6];
966 if (c >= '0' && c <= '9')
967 key = KSYM_0 + (Key)(c - '0');
969 else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
971 char c1 = name_ptr[4];
972 char c2 = name_ptr[5];
975 if ((c1 >= '0' && c1 <= '9') &&
976 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
977 d = atoi(&name_ptr[4]);
979 if (d >=1 && d <= 24)
980 key = KSYM_F1 + (Key)(d - 1);
982 else if (strncmp(name_ptr, "XK_", 3) == 0)
988 if (strcmp(name_ptr, translate_key[i].x11name) == 0)
990 key = translate_key[i].key;
994 while (translate_key[++i].x11name);
996 else if (strncmp(name_ptr, "0x", 2) == 0)
998 unsigned long value = 0;
1004 char c = *name_ptr++;
1007 if (c >= '0' && c <= '9')
1009 else if (c >= 'a' && c <= 'f')
1010 d = (int)(c - 'a' + 10);
1011 else if (c >= 'A' && c <= 'F')
1012 d = (int)(c - 'A' + 10);
1020 value = value * 16 + d;
1031 char *getKeyNameFromKey(Key key)
1035 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1039 char *getX11KeyNameFromKey(Key key)
1043 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1047 Key getKeyFromX11KeyName(char *x11name)
1051 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1055 char getCharFromKey(Key key)
1057 char *keyname = getKeyNameFromKey(key);
1060 if (strlen(keyname) == 1)
1061 letter = keyname[0];
1062 else if (strcmp(keyname, "space") == 0)
1064 else if (strcmp(keyname, "circumflex") == 0)
1070 /* ------------------------------------------------------------------------- */
1071 /* some functions to handle lists of level directories */
1072 /* ------------------------------------------------------------------------- */
1074 struct LevelDirInfo *newLevelDirInfo()
1076 return checked_calloc(sizeof(struct LevelDirInfo));
1079 void pushLevelDirInfo(struct LevelDirInfo **node_first,
1080 struct LevelDirInfo *node_new)
1082 node_new->next = *node_first;
1083 *node_first = node_new;
1086 int numLevelDirInfo(struct LevelDirInfo *node)
1099 boolean validLevelSeries(struct LevelDirInfo *node)
1101 return (node != NULL && !node->node_group && !node->parent_link);
1104 struct LevelDirInfo *getFirstValidLevelSeries(struct LevelDirInfo *node)
1108 if (leveldir_first) /* start with first level directory entry */
1109 return getFirstValidLevelSeries(leveldir_first);
1113 else if (node->node_group) /* enter level group (step down into tree) */
1114 return getFirstValidLevelSeries(node->node_group);
1115 else if (node->parent_link) /* skip start entry of level group */
1117 if (node->next) /* get first real level series entry */
1118 return getFirstValidLevelSeries(node->next);
1119 else /* leave empty level group and go on */
1120 return getFirstValidLevelSeries(node->node_parent->next);
1122 else /* this seems to be a regular level series */
1126 struct LevelDirInfo *getLevelDirInfoFirstGroupEntry(struct LevelDirInfo *node)
1131 if (node->node_parent == NULL) /* top level group */
1132 return leveldir_first;
1133 else /* sub level group */
1134 return node->node_parent->node_group;
1137 int numLevelDirInfoInGroup(struct LevelDirInfo *node)
1139 return numLevelDirInfo(getLevelDirInfoFirstGroupEntry(node));
1142 int posLevelDirInfo(struct LevelDirInfo *node)
1144 struct LevelDirInfo *node_cmp = getLevelDirInfoFirstGroupEntry(node);
1149 if (node_cmp == node)
1153 node_cmp = node_cmp->next;
1159 struct LevelDirInfo *getLevelDirInfoFromPos(struct LevelDirInfo *node, int pos)
1161 struct LevelDirInfo *node_default = node;
1173 return node_default;
1176 struct LevelDirInfo *getLevelDirInfoFromFilenameExt(struct LevelDirInfo *node,
1179 if (filename == NULL)
1184 if (node->node_group)
1186 struct LevelDirInfo *node_group;
1188 node_group = getLevelDirInfoFromFilenameExt(node->node_group, filename);
1193 else if (!node->parent_link)
1195 if (strcmp(filename, node->filename) == 0)
1205 struct LevelDirInfo *getLevelDirInfoFromFilename(char *filename)
1207 return getLevelDirInfoFromFilenameExt(leveldir_first, filename);
1210 void dumpLevelDirInfo(struct LevelDirInfo *node, int depth)
1216 for (i=0; i<depth * 3; i++)
1219 printf("filename == '%s'\n", node->filename);
1221 if (node->node_group != NULL)
1222 dumpLevelDirInfo(node->node_group, depth + 1);
1228 void sortLevelDirInfo(struct LevelDirInfo **node_first,
1229 int (*compare_function)(const void *, const void *))
1231 int num_nodes = numLevelDirInfo(*node_first);
1232 struct LevelDirInfo **sort_array;
1233 struct LevelDirInfo *node = *node_first;
1239 /* allocate array for sorting structure pointers */
1240 sort_array = checked_calloc(num_nodes * sizeof(struct LevelDirInfo *));
1242 /* writing structure pointers to sorting array */
1243 while (i < num_nodes && node) /* double boundary check... */
1245 sort_array[i] = node;
1251 /* sorting the structure pointers in the sorting array */
1252 qsort(sort_array, num_nodes, sizeof(struct LevelDirInfo *),
1255 /* update the linkage of list elements with the sorted node array */
1256 for (i=0; i<num_nodes - 1; i++)
1257 sort_array[i]->next = sort_array[i + 1];
1258 sort_array[num_nodes - 1]->next = NULL;
1260 /* update the linkage of the main list anchor pointer */
1261 *node_first = sort_array[0];
1265 /* now recursively sort the level group structures */
1269 if (node->node_group != NULL)
1270 sortLevelDirInfo(&node->node_group, compare_function);
1276 inline void swap_numbers(int *i1, int *i2)
1284 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1297 /* ========================================================================= */
1298 /* some stuff from "files.c" */
1299 /* ========================================================================= */
1301 #if defined(PLATFORM_WIN32)
1303 #define S_IRGRP S_IRUSR
1306 #define S_IROTH S_IRUSR
1309 #define S_IWGRP S_IWUSR
1312 #define S_IWOTH S_IWUSR
1315 #define S_IXGRP S_IXUSR
1318 #define S_IXOTH S_IXUSR
1321 #define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP)
1326 #endif /* PLATFORM_WIN32 */
1328 /* file permissions for newly written files */
1329 #define MODE_R_ALL (S_IRUSR | S_IRGRP | S_IROTH)
1330 #define MODE_W_ALL (S_IWUSR | S_IWGRP | S_IWOTH)
1331 #define MODE_X_ALL (S_IXUSR | S_IXGRP | S_IXOTH)
1333 #define MODE_W_PRIVATE (S_IWUSR)
1334 #define MODE_W_PUBLIC (S_IWUSR | S_IWGRP)
1335 #define MODE_W_PUBLIC_DIR (S_IWUSR | S_IWGRP | S_ISGID)
1337 #define DIR_PERMS_PRIVATE (MODE_R_ALL | MODE_X_ALL | MODE_W_PRIVATE)
1338 #define DIR_PERMS_PUBLIC (MODE_R_ALL | MODE_X_ALL | MODE_W_PUBLIC_DIR)
1340 #define FILE_PERMS_PRIVATE (MODE_R_ALL | MODE_W_PRIVATE)
1341 #define FILE_PERMS_PUBLIC (MODE_R_ALL | MODE_W_PUBLIC)
1343 char *getUserDataDir(void)
1345 static char *userdata_dir = NULL;
1349 char *home_dir = getHomeDir();
1350 char *data_dir = program.userdata_directory;
1352 userdata_dir = getPath2(home_dir, data_dir);
1355 return userdata_dir;
1360 return getUserDataDir();
1363 static mode_t posix_umask(mode_t mask)
1365 #if defined(PLATFORM_UNIX)
1372 static int posix_mkdir(const char *pathname, mode_t mode)
1374 #if defined(PLATFORM_WIN32)
1375 return mkdir(pathname);
1377 return mkdir(pathname, mode);
1381 void createDirectory(char *dir, char *text, int permission_class)
1383 /* leave "other" permissions in umask untouched, but ensure group parts
1384 of USERDATA_DIR_MODE are not masked */
1385 mode_t dir_mode = (permission_class == PERMS_PRIVATE ?
1386 DIR_PERMS_PRIVATE : DIR_PERMS_PUBLIC);
1387 mode_t normal_umask = posix_umask(0);
1388 mode_t group_umask = ~(dir_mode & S_IRWXG);
1389 posix_umask(normal_umask & group_umask);
1391 if (access(dir, F_OK) != 0)
1392 if (posix_mkdir(dir, dir_mode) != 0)
1393 Error(ERR_WARN, "cannot create %s directory '%s'", text, dir);
1395 posix_umask(normal_umask); /* reset normal umask */
1398 void InitUserDataDirectory()
1400 createDirectory(getUserDataDir(), "user data", PERMS_PRIVATE);
1403 void SetFilePermissions(char *filename, int permission_class)
1405 chmod(filename, (permission_class == PERMS_PRIVATE ?
1406 FILE_PERMS_PRIVATE : FILE_PERMS_PUBLIC));
1409 int getFileVersionFromCookieString(const char *cookie)
1411 const char *ptr_cookie1, *ptr_cookie2;
1412 const char *pattern1 = "_FILE_VERSION_";
1413 const char *pattern2 = "?.?";
1414 const int len_cookie = strlen(cookie);
1415 const int len_pattern1 = strlen(pattern1);
1416 const int len_pattern2 = strlen(pattern2);
1417 const int len_pattern = len_pattern1 + len_pattern2;
1418 int version_major, version_minor;
1420 if (len_cookie <= len_pattern)
1423 ptr_cookie1 = &cookie[len_cookie - len_pattern];
1424 ptr_cookie2 = &cookie[len_cookie - len_pattern2];
1426 if (strncmp(ptr_cookie1, pattern1, len_pattern1) != 0)
1429 if (ptr_cookie2[0] < '0' || ptr_cookie2[0] > '9' ||
1430 ptr_cookie2[1] != '.' ||
1431 ptr_cookie2[2] < '0' || ptr_cookie2[2] > '9')
1434 version_major = ptr_cookie2[0] - '0';
1435 version_minor = ptr_cookie2[2] - '0';
1437 return VERSION_IDENT(version_major, version_minor, 0);
1440 boolean checkCookieString(const char *cookie, const char *template)
1442 const char *pattern = "_FILE_VERSION_?.?";
1443 const int len_cookie = strlen(cookie);
1444 const int len_template = strlen(template);
1445 const int len_pattern = strlen(pattern);
1447 if (len_cookie != len_template)
1450 if (strncmp(cookie, template, len_cookie - len_pattern) != 0)
1456 /* ------------------------------------------------------------------------- */
1457 /* setup file stuff */
1458 /* ------------------------------------------------------------------------- */
1460 static char *string_tolower(char *s)
1462 static char s_lower[100];
1465 if (strlen(s) >= 100)
1470 for (i=0; i<strlen(s_lower); i++)
1471 s_lower[i] = tolower(s_lower[i]);
1476 int get_string_integer_value(char *s)
1478 static char *number_text[][3] =
1480 { "0", "zero", "null", },
1481 { "1", "one", "first" },
1482 { "2", "two", "second" },
1483 { "3", "three", "third" },
1484 { "4", "four", "fourth" },
1485 { "5", "five", "fifth" },
1486 { "6", "six", "sixth" },
1487 { "7", "seven", "seventh" },
1488 { "8", "eight", "eighth" },
1489 { "9", "nine", "ninth" },
1490 { "10", "ten", "tenth" },
1491 { "11", "eleven", "eleventh" },
1492 { "12", "twelve", "twelfth" },
1497 for (i=0; i<13; i++)
1499 if (strcmp(string_tolower(s), number_text[i][j]) == 0)
1505 boolean get_string_boolean_value(char *s)
1507 if (strcmp(string_tolower(s), "true") == 0 ||
1508 strcmp(string_tolower(s), "yes") == 0 ||
1509 strcmp(string_tolower(s), "on") == 0 ||
1510 get_string_integer_value(s) == 1)
1516 char *getFormattedSetupEntry(char *token, char *value)
1519 static char entry[MAX_LINE_LEN];
1521 sprintf(entry, "%s:", token);
1522 for (i=strlen(entry); i<TOKEN_VALUE_POSITION; i++)
1526 strcat(entry, value);
1531 void freeSetupFileList(struct SetupFileList *setup_file_list)
1533 if (!setup_file_list)
1536 if (setup_file_list->token)
1537 free(setup_file_list->token);
1538 if (setup_file_list->value)
1539 free(setup_file_list->value);
1540 if (setup_file_list->next)
1541 freeSetupFileList(setup_file_list->next);
1542 free(setup_file_list);
1545 static struct SetupFileList *newSetupFileList(char *token, char *value)
1547 struct SetupFileList *new = checked_malloc(sizeof(struct SetupFileList));
1549 new->token = checked_malloc(strlen(token) + 1);
1550 strcpy(new->token, token);
1552 new->value = checked_malloc(strlen(value) + 1);
1553 strcpy(new->value, value);
1560 char *getTokenValue(struct SetupFileList *setup_file_list, char *token)
1562 if (!setup_file_list)
1565 if (strcmp(setup_file_list->token, token) == 0)
1566 return setup_file_list->value;
1568 return getTokenValue(setup_file_list->next, token);
1571 static void setTokenValue(struct SetupFileList *setup_file_list,
1572 char *token, char *value)
1574 if (!setup_file_list)
1577 if (strcmp(setup_file_list->token, token) == 0)
1579 free(setup_file_list->value);
1580 setup_file_list->value = checked_malloc(strlen(value) + 1);
1581 strcpy(setup_file_list->value, value);
1583 else if (setup_file_list->next == NULL)
1584 setup_file_list->next = newSetupFileList(token, value);
1586 setTokenValue(setup_file_list->next, token, value);
1590 static void printSetupFileList(struct SetupFileList *setup_file_list)
1592 if (!setup_file_list)
1595 printf("token: '%s'\n", setup_file_list->token);
1596 printf("value: '%s'\n", setup_file_list->value);
1598 printSetupFileList(setup_file_list->next);
1602 struct SetupFileList *loadSetupFileList(char *filename)
1605 char line[MAX_LINE_LEN];
1606 char *token, *value, *line_ptr;
1607 struct SetupFileList *setup_file_list = newSetupFileList("", "");
1608 struct SetupFileList *first_valid_list_entry;
1612 if (!(file = fopen(filename, MODE_READ)))
1614 Error(ERR_WARN, "cannot open configuration file '%s'", filename);
1620 /* read next line of input file */
1621 if (!fgets(line, MAX_LINE_LEN, file))
1624 /* cut trailing comment or whitespace from input line */
1625 for (line_ptr = line; *line_ptr; line_ptr++)
1627 if (*line_ptr == '#' || *line_ptr == '\n' || *line_ptr == '\r')
1634 /* cut trailing whitespaces from input line */
1635 for (line_ptr = &line[strlen(line)]; line_ptr > line; line_ptr--)
1636 if ((*line_ptr == ' ' || *line_ptr == '\t') && line_ptr[1] == '\0')
1639 /* ignore empty lines */
1643 line_len = strlen(line);
1645 /* cut leading whitespaces from token */
1646 for (token = line; *token; token++)
1647 if (*token != ' ' && *token != '\t')
1650 /* find end of token */
1651 for (line_ptr = token; *line_ptr; line_ptr++)
1653 if (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == ':')
1660 if (line_ptr < line + line_len)
1661 value = line_ptr + 1;
1665 /* cut leading whitespaces from value */
1666 for (; *value; value++)
1667 if (*value != ' ' && *value != '\t')
1670 if (*token && *value)
1671 setTokenValue(setup_file_list, token, value);
1676 first_valid_list_entry = setup_file_list->next;
1678 /* free empty list header */
1679 setup_file_list->next = NULL;
1680 freeSetupFileList(setup_file_list);
1682 if (first_valid_list_entry == NULL)
1683 Error(ERR_WARN, "configuration file '%s' is empty", filename);
1685 return first_valid_list_entry;
1688 void checkSetupFileListIdentifier(struct SetupFileList *setup_file_list,
1691 if (!setup_file_list)
1694 if (strcmp(setup_file_list->token, TOKEN_STR_FILE_IDENTIFIER) == 0)
1696 if (strcmp(setup_file_list->value, identifier) != 0)
1698 Error(ERR_WARN, "configuration file has wrong version");
1705 if (setup_file_list->next)
1706 checkSetupFileListIdentifier(setup_file_list->next, identifier);
1709 Error(ERR_WARN, "configuration file has no version information");
1715 /* ========================================================================= */
1716 /* functions only needed for non-Unix (non-command-line) systems */
1717 /* ========================================================================= */
1719 #if !defined(PLATFORM_UNIX)
1721 #define ERROR_FILENAME "error.out"
1723 void initErrorFile()
1727 InitUserDataDirectory();
1729 filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1734 FILE *openErrorFile()
1739 filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1740 error_file = fopen(filename, MODE_APPEND);
1746 void dumpErrorFile()
1751 filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1752 error_file = fopen(filename, MODE_READ);
1755 if (error_file != NULL)
1757 while (!feof(error_file))
1758 fputc(fgetc(error_file), stderr);
1766 /* ========================================================================= */
1767 /* the following is only for debugging purpose and normally not used */
1768 /* ========================================================================= */
1770 #define DEBUG_NUM_TIMESTAMPS 3
1772 void debug_print_timestamp(int counter_nr, char *message)
1774 static long counter[DEBUG_NUM_TIMESTAMPS][2];
1776 if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1777 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1779 counter[counter_nr][0] = Counter();
1782 printf("%s %.2f seconds\n", message,
1783 (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1785 counter[counter_nr][1] = Counter();