1 /***********************************************************
2 * Artsoft Retro-Game Library *
3 *----------------------------------------------------------*
4 * (c) 1994-2000 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.serveronly = FALSE;
429 options.network = FALSE;
430 options.verbose = FALSE;
431 options.debug = FALSE;
433 while (*options_left)
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);
441 if (option_len >= MAX_OPTION_LEN)
442 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
444 strcpy(option_str, option); /* copy argument into buffer */
447 if (strcmp(option, "--") == 0) /* stop scanning arguments */
450 if (strncmp(option, "--", 2) == 0) /* treat '--' like '-' */
453 option_arg = strchr(option, '=');
454 if (option_arg == NULL) /* no '=' in option */
455 option_arg = next_option;
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);
463 option_len = strlen(option);
465 if (strcmp(option, "-") == 0)
466 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
467 else if (strncmp(option, "-help", option_len) == 0)
469 printf("Usage: %s [options] [server.name [port]]\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);
480 else if (strncmp(option, "-display", option_len) == 0)
482 if (option_arg == NULL)
483 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
485 options.display_name = option_arg;
486 if (option_arg == next_option)
489 else if (strncmp(option, "-basepath", option_len) == 0)
491 if (option_arg == NULL)
492 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
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)
500 /* adjust path for level directory accordingly */
501 options.level_directory =
502 getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
504 else if (strncmp(option, "-levels", option_len) == 0)
506 if (option_arg == NULL)
507 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
509 options.level_directory = option_arg;
510 if (option_arg == next_option)
513 else if (strncmp(option, "-network", option_len) == 0)
515 options.network = TRUE;
517 else if (strncmp(option, "-serveronly", option_len) == 0)
519 options.serveronly = TRUE;
521 else if (strncmp(option, "-verbose", option_len) == 0)
523 options.verbose = TRUE;
525 else if (strncmp(option, "-debug", option_len) == 0)
527 options.debug = TRUE;
529 else if (*option == '-')
531 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
533 else if (options.server_host == NULL)
535 options.server_host = *options_left;
537 else if (options.server_port == 0)
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);
544 Error(ERR_EXIT_HELP, "too many arguments");
550 void Error(int mode, char *format, ...)
552 char *process_name = "";
553 FILE *error = stderr;
555 /* display warnings only when running in verbose mode */
556 if (mode & ERR_WARN && !options.verbose)
559 #if !defined(PLATFORM_UNIX)
560 if ((error = openErrorFile()) == NULL)
562 printf("Cannot write to error output file!\n");
563 program.exit_function(1);
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 **";
578 fprintf(error, "%s%s: ", program.command_basename, process_name);
581 fprintf(error, "warning: ");
583 va_start(ap, format);
584 vfprintf(error, format, ap);
587 fprintf(error, "\n");
591 fprintf(error, "%s: Try option '--help' for more information.\n",
592 program.command_basename);
595 fprintf(error, "%s%s: aborting\n", program.command_basename, process_name);
602 if (mode & ERR_FROM_SERVER)
603 exit(1); /* child process: normal exit */
605 program.exit_function(1); /* main process: clean up stuff */
609 void *checked_malloc(unsigned long size)
616 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
621 void *checked_calloc(unsigned long size)
625 ptr = calloc(1, size);
628 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
633 void *checked_realloc(void *ptr, unsigned long size)
635 ptr = realloc(ptr, size);
638 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
643 short getFile16BitInteger(FILE *file, int byte_order)
645 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
646 return ((fgetc(file) << 8) |
648 else /* BYTE_ORDER_LITTLE_ENDIAN */
649 return ((fgetc(file) << 0) |
653 void putFile16BitInteger(FILE *file, short value, int byte_order)
655 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
657 fputc((value >> 8) & 0xff, file);
658 fputc((value >> 0) & 0xff, file);
660 else /* BYTE_ORDER_LITTLE_ENDIAN */
662 fputc((value >> 0) & 0xff, file);
663 fputc((value >> 8) & 0xff, file);
667 int getFile32BitInteger(FILE *file, int byte_order)
669 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
670 return ((fgetc(file) << 24) |
671 (fgetc(file) << 16) |
674 else /* BYTE_ORDER_LITTLE_ENDIAN */
675 return ((fgetc(file) << 0) |
677 (fgetc(file) << 16) |
678 (fgetc(file) << 24));
681 void putFile32BitInteger(FILE *file, int value, int byte_order)
683 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
685 fputc((value >> 24) & 0xff, file);
686 fputc((value >> 16) & 0xff, file);
687 fputc((value >> 8) & 0xff, file);
688 fputc((value >> 0) & 0xff, file);
690 else /* BYTE_ORDER_LITTLE_ENDIAN */
692 fputc((value >> 0) & 0xff, file);
693 fputc((value >> 8) & 0xff, file);
694 fputc((value >> 16) & 0xff, file);
695 fputc((value >> 24) & 0xff, file);
699 void getFileChunk(FILE *file, char *chunk_buffer, int *chunk_length,
702 const int chunk_identifier_length = 4;
704 /* read chunk identifier */
705 fgets(chunk_buffer, chunk_identifier_length + 1, file);
707 /* read chunk length */
708 *chunk_length = getFile32BitInteger(file, byte_order);
711 void putFileChunk(FILE *file, char *chunk_name, int chunk_length,
714 /* write chunk identifier */
715 fputs(chunk_name, file);
717 /* write chunk length */
718 putFile32BitInteger(file, chunk_length, byte_order);
721 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
722 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
723 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 2
725 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
734 /* normal cursor keys */
735 { KSYM_Left, "XK_Left", "cursor left" },
736 { KSYM_Right, "XK_Right", "cursor right" },
737 { KSYM_Up, "XK_Up", "cursor up" },
738 { KSYM_Down, "XK_Down", "cursor down" },
740 /* keypad cursor keys */
742 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
743 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
744 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
745 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
748 /* other keypad keys */
750 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
751 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
752 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
753 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
754 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
755 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
759 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
760 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
761 { KSYM_Control_L, "XK_Control_L", "left control" },
762 { KSYM_Control_R, "XK_Control_R", "right control" },
763 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
764 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
765 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
766 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
767 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
768 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
769 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
770 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
772 /* some special keys */
773 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
774 { KSYM_Delete, "XK_Delete", "delete" },
775 { KSYM_Insert, "XK_Insert", "insert" },
776 { KSYM_Tab, "XK_Tab", "tab" },
777 { KSYM_Home, "XK_Home", "home" },
778 { KSYM_End, "XK_End", "end" },
779 { KSYM_Page_Up, "XK_Page_Up", "page up" },
780 { KSYM_Page_Down, "XK_Page_Down", "page down" },
781 { KSYM_Menu, "XK_Menu", "menu" }, /* Win-Menu */
783 /* ASCII 0x20 to 0x40 keys (except numbers) */
784 { KSYM_space, "XK_space", "space" },
785 { KSYM_exclam, "XK_exclam", "!" },
786 { KSYM_quotedbl, "XK_quotedbl", "\"" },
787 { KSYM_numbersign, "XK_numbersign", "#" },
788 { KSYM_dollar, "XK_dollar", "$" },
789 { KSYM_percent, "XK_percent", "%" },
790 { KSYM_ampersand, "XK_ampersand", "&" },
791 { KSYM_apostrophe, "XK_apostrophe", "'" },
792 { KSYM_parenleft, "XK_parenleft", "(" },
793 { KSYM_parenright, "XK_parenright", ")" },
794 { KSYM_asterisk, "XK_asterisk", "*" },
795 { KSYM_plus, "XK_plus", "+" },
796 { KSYM_comma, "XK_comma", "," },
797 { KSYM_minus, "XK_minus", "-" },
798 { KSYM_period, "XK_period", "." },
799 { KSYM_slash, "XK_slash", "/" },
800 { KSYM_colon, "XK_colon", ":" },
801 { KSYM_semicolon, "XK_semicolon", ";" },
802 { KSYM_less, "XK_less", "<" },
803 { KSYM_equal, "XK_equal", "=" },
804 { KSYM_greater, "XK_greater", ">" },
805 { KSYM_question, "XK_question", "?" },
806 { KSYM_at, "XK_at", "@" },
808 /* more ASCII keys */
809 { KSYM_bracketleft, "XK_bracketleft", "[" },
810 { KSYM_backslash, "XK_backslash", "backslash" },
811 { KSYM_bracketright,"XK_bracketright", "]" },
812 { KSYM_asciicircum, "XK_asciicircum", "circumflex" },
813 { KSYM_underscore, "XK_underscore", "_" },
814 { KSYM_grave, "XK_grave", "grave" },
815 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
816 { KSYM_braceleft, "XK_braceleft", "brace left" },
817 { KSYM_bar, "XK_bar", "bar" },
818 { KSYM_braceright, "XK_braceright", "brace right" },
819 { KSYM_asciitilde, "XK_asciitilde", "ascii tilde" },
821 /* special (non-ASCII) keys */
822 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
823 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
824 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
825 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
826 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
827 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
828 { KSYM_ssharp, "XK_ssharp", "sharp s" },
830 /* end-of-array identifier */
836 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
838 static char name_buffer[30];
841 if (key >= KSYM_A && key <= KSYM_Z)
842 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
843 else if (key >= KSYM_a && key <= KSYM_z)
844 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
845 else if (key >= KSYM_0 && key <= KSYM_9)
846 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
847 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
848 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
849 else if (key >= KSYM_F1 && key <= KSYM_F24)
850 sprintf(name_buffer, "function F%d", (int)(key - KSYM_F1 + 1));
851 else if (key == KSYM_UNDEFINED)
852 strcpy(name_buffer, "(undefined)");
859 if (key == translate_key[i].key)
861 strcpy(name_buffer, translate_key[i].name);
865 while (translate_key[++i].name);
867 if (!translate_key[i].name)
868 strcpy(name_buffer, "(unknown)");
873 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
875 static char name_buffer[30];
878 if (key >= KSYM_A && key <= KSYM_Z)
879 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
880 else if (key >= KSYM_a && key <= KSYM_z)
881 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
882 else if (key >= KSYM_0 && key <= KSYM_9)
883 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
884 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
885 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
886 else if (key >= KSYM_F1 && key <= KSYM_F24)
887 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_F1 + 1));
888 else if (key == KSYM_UNDEFINED)
889 strcpy(name_buffer, "[undefined]");
896 if (key == translate_key[i].key)
898 strcpy(name_buffer, translate_key[i].x11name);
902 while (translate_key[++i].x11name);
904 if (!translate_key[i].x11name)
905 sprintf(name_buffer, "0x%04lx", (unsigned long)key);
908 *x11name = name_buffer;
910 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
912 Key key = KSYM_UNDEFINED;
913 char *name_ptr = *x11name;
915 if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
917 char c = name_ptr[3];
919 if (c >= 'A' && c <= 'Z')
920 key = KSYM_A + (Key)(c - 'A');
921 else if (c >= 'a' && c <= 'z')
922 key = KSYM_a + (Key)(c - 'a');
923 else if (c >= '0' && c <= '9')
924 key = KSYM_0 + (Key)(c - '0');
926 else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
928 char c = name_ptr[6];
930 if (c >= '0' && c <= '9')
931 key = KSYM_0 + (Key)(c - '0');
933 else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
935 char c1 = name_ptr[4];
936 char c2 = name_ptr[5];
939 if ((c1 >= '0' && c1 <= '9') &&
940 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
941 d = atoi(&name_ptr[4]);
943 if (d >=1 && d <= 24)
944 key = KSYM_F1 + (Key)(d - 1);
946 else if (strncmp(name_ptr, "XK_", 3) == 0)
952 if (strcmp(name_ptr, translate_key[i].x11name) == 0)
954 key = translate_key[i].key;
958 while (translate_key[++i].x11name);
960 else if (strncmp(name_ptr, "0x", 2) == 0)
962 unsigned long value = 0;
968 char c = *name_ptr++;
971 if (c >= '0' && c <= '9')
973 else if (c >= 'a' && c <= 'f')
974 d = (int)(c - 'a' + 10);
975 else if (c >= 'A' && c <= 'F')
976 d = (int)(c - 'A' + 10);
984 value = value * 16 + d;
995 char *getKeyNameFromKey(Key key)
999 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1003 char *getX11KeyNameFromKey(Key key)
1007 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1011 Key getKeyFromX11KeyName(char *x11name)
1015 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1019 char getCharFromKey(Key key)
1021 char *keyname = getKeyNameFromKey(key);
1024 if (strlen(keyname) == 1)
1025 letter = keyname[0];
1026 else if (strcmp(keyname, "space") == 0)
1028 else if (strcmp(keyname, "circumflex") == 0)
1034 /* ------------------------------------------------------------------------- */
1035 /* some functions to handle lists of level directories */
1036 /* ------------------------------------------------------------------------- */
1038 struct LevelDirInfo *newLevelDirInfo()
1040 return checked_calloc(sizeof(struct LevelDirInfo));
1043 void pushLevelDirInfo(struct LevelDirInfo **node_first,
1044 struct LevelDirInfo *node_new)
1046 node_new->next = *node_first;
1047 *node_first = node_new;
1050 int numLevelDirInfo(struct LevelDirInfo *node)
1063 boolean validLevelSeries(struct LevelDirInfo *node)
1065 return (node != NULL && !node->node_group && !node->parent_link);
1068 struct LevelDirInfo *getFirstValidLevelSeries(struct LevelDirInfo *node)
1072 if (leveldir_first) /* start with first level directory entry */
1073 return getFirstValidLevelSeries(leveldir_first);
1077 else if (node->node_group) /* enter level group (step down into tree) */
1078 return getFirstValidLevelSeries(node->node_group);
1079 else if (node->parent_link) /* skip start entry of level group */
1081 if (node->next) /* get first real level series entry */
1082 return getFirstValidLevelSeries(node->next);
1083 else /* leave empty level group and go on */
1084 return getFirstValidLevelSeries(node->node_parent->next);
1086 else /* this seems to be a regular level series */
1090 struct LevelDirInfo *getLevelDirInfoFirstGroupEntry(struct LevelDirInfo *node)
1095 if (node->node_parent == NULL) /* top level group */
1096 return leveldir_first;
1097 else /* sub level group */
1098 return node->node_parent->node_group;
1101 int numLevelDirInfoInGroup(struct LevelDirInfo *node)
1103 return numLevelDirInfo(getLevelDirInfoFirstGroupEntry(node));
1106 int posLevelDirInfo(struct LevelDirInfo *node)
1108 struct LevelDirInfo *node_cmp = getLevelDirInfoFirstGroupEntry(node);
1113 if (node_cmp == node)
1117 node_cmp = node_cmp->next;
1123 struct LevelDirInfo *getLevelDirInfoFromPos(struct LevelDirInfo *node, int pos)
1125 struct LevelDirInfo *node_default = node;
1137 return node_default;
1140 struct LevelDirInfo *getLevelDirInfoFromFilenameExt(struct LevelDirInfo *node,
1143 if (filename == NULL)
1148 if (node->node_group)
1150 struct LevelDirInfo *node_group;
1152 node_group = getLevelDirInfoFromFilenameExt(node->node_group, filename);
1157 else if (!node->parent_link)
1159 if (strcmp(filename, node->filename) == 0)
1169 struct LevelDirInfo *getLevelDirInfoFromFilename(char *filename)
1171 return getLevelDirInfoFromFilenameExt(leveldir_first, filename);
1174 void dumpLevelDirInfo(struct LevelDirInfo *node, int depth)
1180 for (i=0; i<depth * 3; i++)
1183 printf("filename == '%s'\n", node->filename);
1185 if (node->node_group != NULL)
1186 dumpLevelDirInfo(node->node_group, depth + 1);
1192 void sortLevelDirInfo(struct LevelDirInfo **node_first,
1193 int (*compare_function)(const void *, const void *))
1195 int num_nodes = numLevelDirInfo(*node_first);
1196 struct LevelDirInfo **sort_array;
1197 struct LevelDirInfo *node = *node_first;
1203 /* allocate array for sorting structure pointers */
1204 sort_array = checked_calloc(num_nodes * sizeof(struct LevelDirInfo *));
1206 /* writing structure pointers to sorting array */
1207 while (i < num_nodes && node) /* double boundary check... */
1209 sort_array[i] = node;
1215 /* sorting the structure pointers in the sorting array */
1216 qsort(sort_array, num_nodes, sizeof(struct LevelDirInfo *),
1219 /* update the linkage of list elements with the sorted node array */
1220 for (i=0; i<num_nodes - 1; i++)
1221 sort_array[i]->next = sort_array[i + 1];
1222 sort_array[num_nodes - 1]->next = NULL;
1224 /* update the linkage of the main list anchor pointer */
1225 *node_first = sort_array[0];
1229 /* now recursively sort the level group structures */
1233 if (node->node_group != NULL)
1234 sortLevelDirInfo(&node->node_group, compare_function);
1240 inline void swap_numbers(int *i1, int *i2)
1248 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1261 /* ========================================================================= */
1262 /* some stuff from "files.c" */
1263 /* ========================================================================= */
1265 #define MODE_R_ALL (S_IRUSR | S_IRGRP | S_IROTH)
1266 #define MODE_W_ALL (S_IWUSR | S_IWGRP | S_IWOTH)
1267 #define MODE_X_ALL (S_IXUSR | S_IXGRP | S_IXOTH)
1268 #define USERDATA_DIR_MODE (MODE_R_ALL | MODE_X_ALL | S_IWUSR)
1270 char *getUserDataDir(void)
1272 static char *userdata_dir = NULL;
1276 char *home_dir = getHomeDir();
1277 char *data_dir = program.userdata_directory;
1279 userdata_dir = getPath2(home_dir, data_dir);
1282 return userdata_dir;
1285 void createDirectory(char *dir, char *text)
1287 if (access(dir, F_OK) != 0)
1288 #if defined(PLATFORM_WIN32)
1289 if (mkdir(dir) != 0)
1291 if (mkdir(dir, USERDATA_DIR_MODE) != 0)
1293 Error(ERR_WARN, "cannot create %s directory '%s'", text, dir);
1296 void InitUserDataDirectory()
1298 createDirectory(getUserDataDir(), "user data");
1302 /* ========================================================================= */
1303 /* functions only needed for non-Unix (non-command-line) systems */
1304 /* ========================================================================= */
1306 #if !defined(PLATFORM_UNIX)
1308 #define ERROR_FILENAME "error.out"
1310 void initErrorFile()
1314 InitUserDataDirectory();
1316 filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1321 FILE *openErrorFile()
1326 filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1327 error_file = fopen(filename, MODE_APPEND);
1333 void dumpErrorFile()
1338 filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1339 error_file = fopen(filename, MODE_READ);
1342 if (error_file != NULL)
1344 while (!feof(error_file))
1345 fputc(fgetc(error_file), stderr);
1353 /* ========================================================================= */
1354 /* the following is only for debugging purpose and normally not used */
1355 /* ========================================================================= */
1357 #define DEBUG_NUM_TIMESTAMPS 3
1359 void debug_print_timestamp(int counter_nr, char *message)
1361 static long counter[DEBUG_NUM_TIMESTAMPS][2];
1363 if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1364 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1366 counter[counter_nr][0] = Counter();
1369 printf("%s %.2f seconds\n", message,
1370 (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1372 counter[counter_nr][1] = Counter();