1 /***********************************************************
2 * Artsoft Retro-Game Library *
3 *----------------------------------------------------------*
4 * (c) 1994-2002 Artsoft Entertainment *
6 * Detmolder Strasse 189 *
9 * e-mail: info@artsoft.org *
10 *----------------------------------------------------------*
12 ***********************************************************/
16 #include <sys/types.h>
24 #if !defined(PLATFORM_WIN32)
26 #include <sys/param.h>
36 /* ------------------------------------------------------------------------- */
37 /* some generic helper functions */
38 /* ------------------------------------------------------------------------- */
40 void fprintf_line(FILE *stream, char *line_string, int line_length)
44 for (i = 0; i < line_length; i++)
45 fprintf(stream, "%s", line_string);
47 fprintf(stream, "\n");
50 void printf_line(char *line_string, int line_length)
52 fprintf_line(stdout, line_string, line_length);
55 /* int2str() returns a number converted to a string;
56 the used memory is static, but will be overwritten by later calls,
57 so if you want to save the result, copy it to a private string buffer;
58 there can be 10 local calls of int2str() without buffering the result --
59 the 11th call will then destroy the result from the first call and so on.
62 char *int2str(int number, int size)
64 static char shift_array[10][40];
65 static int shift_counter = 0;
66 char *s = shift_array[shift_counter];
68 shift_counter = (shift_counter + 1) % 10;
75 sprintf(s, " %09d", number);
76 return &s[strlen(s) - size];
80 sprintf(s, "%d", number);
85 /* something similar to "int2str()" above, but allocates its own memory
86 and has a different interface; we cannot use "itoa()", because this
87 seems to be already defined when cross-compiling to the win32 target */
89 char *i_to_a(unsigned int i)
91 static char *a = NULL;
96 if (i > 2147483647) /* yes, this is a kludge */
99 a = checked_malloc(10 + 1);
107 /* ------------------------------------------------------------------------- */
108 /* counter functions */
109 /* ------------------------------------------------------------------------- */
111 #if defined(PLATFORM_MSDOS)
112 volatile unsigned long counter = 0;
114 void increment_counter()
119 END_OF_FUNCTION(increment_counter);
123 /* maximal allowed length of a command line option */
124 #define MAX_OPTION_LEN 256
127 static unsigned long mainCounter(int mode)
129 static unsigned long base_ms = 0;
130 unsigned long current_ms;
131 unsigned long counter_ms;
133 current_ms = SDL_GetTicks();
135 /* reset base time in case of counter initializing or wrap-around */
136 if (mode == INIT_COUNTER || current_ms < base_ms)
137 base_ms = current_ms;
139 counter_ms = current_ms - base_ms;
141 return counter_ms; /* return milliseconds since last init */
144 #else /* !TARGET_SDL */
146 #if defined(PLATFORM_UNIX)
147 static unsigned long mainCounter(int mode)
149 static struct timeval base_time = { 0, 0 };
150 struct timeval current_time;
151 unsigned long counter_ms;
153 gettimeofday(¤t_time, NULL);
155 /* reset base time in case of counter initializing or wrap-around */
156 if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
157 base_time = current_time;
159 counter_ms = (current_time.tv_sec - base_time.tv_sec) * 1000
160 + (current_time.tv_usec - base_time.tv_usec) / 1000;
162 return counter_ms; /* return milliseconds since last init */
164 #endif /* PLATFORM_UNIX */
165 #endif /* !TARGET_SDL */
167 void InitCounter() /* set counter back to zero */
169 #if !defined(PLATFORM_MSDOS)
170 mainCounter(INIT_COUNTER);
172 LOCK_VARIABLE(counter);
173 LOCK_FUNCTION(increment_counter);
174 install_int_ex(increment_counter, BPS_TO_TIMER(100));
178 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
180 #if !defined(PLATFORM_MSDOS)
181 return mainCounter(READ_COUNTER);
183 return (counter * 10);
187 static void sleep_milliseconds(unsigned long milliseconds_delay)
189 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
192 #if defined(PLATFORM_MSDOS)
193 /* don't use select() to perform waiting operations under DOS
194 environment; always use a busy loop for waiting instead */
195 do_busy_waiting = TRUE;
201 /* we want to wait only a few ms -- if we assume that we have a
202 kernel timer resolution of 10 ms, we would wait far to long;
203 therefore it's better to do a short interval of busy waiting
204 to get our sleeping time more accurate */
206 unsigned long base_counter = Counter(), actual_counter = Counter();
208 while (actual_counter < base_counter + milliseconds_delay &&
209 actual_counter >= base_counter)
210 actual_counter = Counter();
214 #if defined(TARGET_SDL)
215 SDL_Delay(milliseconds_delay);
216 #elif defined(TARGET_ALLEGRO)
217 rest(milliseconds_delay);
219 struct timeval delay;
221 delay.tv_sec = milliseconds_delay / 1000;
222 delay.tv_usec = 1000 * (milliseconds_delay % 1000);
224 if (select(0, NULL, NULL, NULL, &delay) != 0)
225 Error(ERR_WARN, "sleep_milliseconds(): select() failed");
230 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
232 sleep_milliseconds(delay);
235 boolean FrameReached(unsigned long *frame_counter_var,
236 unsigned long frame_delay)
238 unsigned long actual_frame_counter = FrameCounter;
240 if (actual_frame_counter >= *frame_counter_var &&
241 actual_frame_counter < *frame_counter_var + frame_delay)
244 *frame_counter_var = actual_frame_counter;
249 boolean DelayReached(unsigned long *counter_var,
252 unsigned long actual_counter = Counter();
254 if (actual_counter >= *counter_var &&
255 actual_counter < *counter_var + delay)
258 *counter_var = actual_counter;
263 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
265 unsigned long actual_counter;
269 actual_counter = Counter();
271 if (actual_counter >= *counter_var &&
272 actual_counter < *counter_var + delay)
273 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
278 *counter_var = actual_counter;
282 /* ------------------------------------------------------------------------- */
283 /* random generator functions */
284 /* ------------------------------------------------------------------------- */
287 unsigned int SimpleRND(unsigned int max)
289 return (random_linux_libc(RND_FREE) % max);
292 unsigned int InitSimpleRND(long seed)
294 if (seed == NEW_RANDOMIZE)
296 struct timeval current_time;
298 gettimeofday(¤t_time, NULL);
299 seed = (long)current_time.tv_usec;
302 srandom_linux_libc(RND_FREE, (unsigned int) seed);
304 return (unsigned int) seed;
307 unsigned int RND(unsigned int max)
309 return (random_linux_libc(RND_GAME) % max);
312 unsigned int InitRND(long seed)
314 if (seed == NEW_RANDOMIZE)
316 struct timeval current_time;
318 gettimeofday(¤t_time, NULL);
319 seed = (long)current_time.tv_usec;
322 srandom_linux_libc(RND_GAME, (unsigned int) seed);
324 return (unsigned int) seed;
328 unsigned int init_random_number(int nr, long seed)
330 if (seed == NEW_RANDOMIZE)
332 #if defined(TARGET_SDL)
333 seed = (long)SDL_GetTicks();
335 struct timeval current_time;
337 gettimeofday(¤t_time, NULL);
338 seed = (long)current_time.tv_usec;
342 srandom_linux_libc(nr, (unsigned int) seed);
344 return (unsigned int) seed;
348 unsigned int get_random_number(int nr, unsigned int max)
350 return (max > 0 ? random_linux_libc(nr) % max : 0);
353 unsigned int get_random_number(int nr, unsigned int max)
355 unsigned int rnd = (max > 0 ? random_linux_libc(nr) % max : 0);
357 if (nr == 0 && FrameCounter < 2)
358 printf("::: %d [%d]\n", rnd, FrameCounter);
361 if (nr == 0 && FrameCounter < 2 && rnd == 8)
370 /* ------------------------------------------------------------------------- */
371 /* system info functions */
372 /* ------------------------------------------------------------------------- */
374 #if !defined(PLATFORM_MSDOS)
375 static char *get_corrected_real_name(char *real_name)
377 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
378 char *from_ptr = real_name;
379 char *to_ptr = real_name_new;
381 if (strchr(real_name, 'ß') == NULL) /* name does not contain 'ß' */
383 strncpy(real_name_new, real_name, MAX_USERNAME_LEN);
384 real_name_new[MAX_USERNAME_LEN] = '\0';
386 return real_name_new;
389 /* the user's real name may contain a 'ß' character (german sharp s),
390 which has no equivalent in upper case letters (which our fonts use) */
391 while (*from_ptr && (long)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
393 if (*from_ptr != 'ß')
394 *to_ptr++ = *from_ptr++;
405 return real_name_new;
411 static char *login_name = NULL;
413 #if defined(PLATFORM_WIN32)
414 if (login_name == NULL)
416 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
417 login_name = checked_malloc(buffer_size);
419 if (GetUserName(login_name, &buffer_size) == 0)
420 strcpy(login_name, ANONYMOUS_NAME);
423 if (login_name == NULL)
427 if ((pwd = getpwuid(getuid())) == NULL)
428 login_name = ANONYMOUS_NAME;
430 login_name = getStringCopy(pwd->pw_name);
439 static char *real_name = NULL;
441 #if defined(PLATFORM_WIN32)
442 if (real_name == NULL)
444 static char buffer[MAX_USERNAME_LEN + 1];
445 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
447 if (GetUserName(buffer, &buffer_size) != 0)
448 real_name = get_corrected_real_name(buffer);
450 real_name = ANONYMOUS_NAME;
452 #elif defined(PLATFORM_UNIX)
453 if (real_name == NULL)
457 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
458 real_name = get_corrected_real_name(pwd->pw_gecos);
460 real_name = ANONYMOUS_NAME;
463 real_name = ANONYMOUS_NAME;
471 static char *dir = NULL;
473 #if defined(PLATFORM_WIN32)
476 dir = checked_malloc(MAX_PATH + 1);
478 if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, dir)))
481 #elif defined(PLATFORM_UNIX)
484 if ((dir = getenv("HOME")) == NULL)
488 if ((pwd = getpwuid(getuid())) != NULL)
489 dir = getStringCopy(pwd->pw_dir);
502 /* ------------------------------------------------------------------------- */
503 /* various string functions */
504 /* ------------------------------------------------------------------------- */
506 char *getPath2(char *path1, char *path2)
508 char *complete_path = checked_malloc(strlen(path1) + 1 +
511 sprintf(complete_path, "%s/%s", path1, path2);
513 return complete_path;
516 char *getPath3(char *path1, char *path2, char *path3)
518 char *complete_path = checked_malloc(strlen(path1) + 1 +
522 sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
524 return complete_path;
527 char *getStringCat2(char *s1, char *s2)
529 char *complete_string = checked_malloc(strlen(s1) + strlen(s2) + 1);
531 sprintf(complete_string, "%s%s", s1, s2);
533 return complete_string;
536 char *getStringCopy(char *s)
543 s_copy = checked_malloc(strlen(s) + 1);
549 char *getStringToLower(char *s)
551 char *s_copy = checked_malloc(strlen(s) + 1);
552 char *s_ptr = s_copy;
555 *s_ptr++ = tolower(*s++);
561 void setString(char **old_value, char *new_value)
563 if (*old_value != NULL)
566 *old_value = getStringCopy(new_value);
570 /* ------------------------------------------------------------------------- */
571 /* command line option handling functions */
572 /* ------------------------------------------------------------------------- */
574 void GetOptions(char *argv[], void (*print_usage_function)(void))
576 char **options_left = &argv[1];
578 /* initialize global program options */
579 options.display_name = NULL;
580 options.server_host = NULL;
581 options.server_port = 0;
582 options.ro_base_directory = RO_BASE_PATH;
583 options.rw_base_directory = RW_BASE_PATH;
584 options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
585 options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
586 options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
587 options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
588 options.docs_directory = RO_BASE_PATH "/" DOCS_DIRECTORY;
589 options.execute_command = NULL;
590 options.serveronly = FALSE;
591 options.network = FALSE;
592 options.verbose = FALSE;
593 options.debug = FALSE;
595 #if !defined(PLATFORM_UNIX)
596 if (*options_left == NULL) /* no options given -- enable verbose mode */
597 options.verbose = TRUE;
600 while (*options_left)
602 char option_str[MAX_OPTION_LEN];
603 char *option = options_left[0];
604 char *next_option = options_left[1];
605 char *option_arg = NULL;
606 int option_len = strlen(option);
608 if (option_len >= MAX_OPTION_LEN)
609 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
611 strcpy(option_str, option); /* copy argument into buffer */
614 if (strcmp(option, "--") == 0) /* stop scanning arguments */
617 if (strncmp(option, "--", 2) == 0) /* treat '--' like '-' */
620 option_arg = strchr(option, '=');
621 if (option_arg == NULL) /* no '=' in option */
622 option_arg = next_option;
625 *option_arg++ = '\0'; /* cut argument from option */
626 if (*option_arg == '\0') /* no argument after '=' */
627 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
630 option_len = strlen(option);
632 if (strcmp(option, "-") == 0)
633 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
634 else if (strncmp(option, "-help", option_len) == 0)
636 print_usage_function();
640 else if (strncmp(option, "-display", option_len) == 0)
642 if (option_arg == NULL)
643 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
645 options.display_name = option_arg;
646 if (option_arg == next_option)
649 else if (strncmp(option, "-basepath", option_len) == 0)
651 if (option_arg == NULL)
652 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
654 /* this should be extended to separate options for ro and rw data */
655 options.ro_base_directory = option_arg;
656 options.rw_base_directory = option_arg;
657 if (option_arg == next_option)
660 /* adjust path for level directory accordingly */
661 options.level_directory =
662 getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
664 else if (strncmp(option, "-levels", option_len) == 0)
666 if (option_arg == NULL)
667 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
669 options.level_directory = option_arg;
670 if (option_arg == next_option)
673 else if (strncmp(option, "-graphics", option_len) == 0)
675 if (option_arg == NULL)
676 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
678 options.graphics_directory = option_arg;
679 if (option_arg == next_option)
682 else if (strncmp(option, "-sounds", option_len) == 0)
684 if (option_arg == NULL)
685 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
687 options.sounds_directory = option_arg;
688 if (option_arg == next_option)
691 else if (strncmp(option, "-music", option_len) == 0)
693 if (option_arg == NULL)
694 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
696 options.music_directory = option_arg;
697 if (option_arg == next_option)
700 else if (strncmp(option, "-network", option_len) == 0)
702 options.network = TRUE;
704 else if (strncmp(option, "-serveronly", option_len) == 0)
706 options.serveronly = TRUE;
708 else if (strncmp(option, "-verbose", option_len) == 0)
710 options.verbose = TRUE;
712 else if (strncmp(option, "-debug", option_len) == 0)
714 options.debug = TRUE;
716 else if (strncmp(option, "-execute", option_len) == 0)
718 if (option_arg == NULL)
719 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
721 options.execute_command = option_arg;
722 if (option_arg == next_option)
725 else if (*option == '-')
727 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
729 else if (options.server_host == NULL)
731 options.server_host = *options_left;
733 else if (options.server_port == 0)
735 options.server_port = atoi(*options_left);
736 if (options.server_port < 1024)
737 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
740 Error(ERR_EXIT_HELP, "too many arguments");
747 /* ------------------------------------------------------------------------- */
748 /* error handling functions */
749 /* ------------------------------------------------------------------------- */
751 /* used by SetError() and GetError() to store internal error messages */
752 static char internal_error[1024]; /* this is bad */
754 void SetError(char *format, ...)
758 va_start(ap, format);
759 vsprintf(internal_error, format, ap);
765 return internal_error;
768 void Error(int mode, char *format, ...)
770 static boolean last_line_was_separator = FALSE;
771 char *process_name = "";
772 FILE *error = stderr;
773 char *newline = "\n";
775 /* display warnings only when running in verbose mode */
776 if (mode & ERR_WARN && !options.verbose)
779 if (mode == ERR_RETURN_LINE)
781 if (!last_line_was_separator)
782 fprintf_line(error, format, 79);
784 last_line_was_separator = TRUE;
789 last_line_was_separator = FALSE;
791 #if defined(PLATFORM_MSDOS)
794 if ((error = openErrorFile()) == NULL)
796 printf("Cannot write to error output file!%s", newline);
797 program.exit_function(1);
801 if (mode & ERR_SOUND_SERVER)
802 process_name = " sound server";
803 else if (mode & ERR_NETWORK_SERVER)
804 process_name = " network server";
805 else if (mode & ERR_NETWORK_CLIENT)
806 process_name = " network client **";
812 fprintf(error, "%s%s: ", program.command_basename, process_name);
815 fprintf(error, "warning: ");
817 va_start(ap, format);
818 vfprintf(error, format, ap);
821 fprintf(error, "%s", newline);
825 fprintf(error, "%s: Try option '--help' for more information.%s",
826 program.command_basename, newline);
829 fprintf(error, "%s%s: aborting%s",
830 program.command_basename, process_name, newline);
837 if (mode & ERR_FROM_SERVER)
838 exit(1); /* child process: normal exit */
840 program.exit_function(1); /* main process: clean up stuff */
845 /* ------------------------------------------------------------------------- */
846 /* memory allocation functions */
847 /* ------------------------------------------------------------------------- */
849 void *checked_malloc(unsigned long size)
856 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
861 void *checked_calloc(unsigned long size)
865 ptr = calloc(1, size);
868 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
873 void *checked_realloc(void *ptr, unsigned long size)
875 ptr = realloc(ptr, size);
878 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
884 /* ------------------------------------------------------------------------- */
885 /* various helper functions */
886 /* ------------------------------------------------------------------------- */
888 inline void swap_numbers(int *i1, int *i2)
896 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
908 short getFile16BitInteger(FILE *file, int byte_order)
910 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
911 return ((fgetc(file) << 8) |
913 else /* BYTE_ORDER_LITTLE_ENDIAN */
914 return ((fgetc(file) << 0) |
918 void putFile16BitInteger(FILE *file, short value, int byte_order)
920 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
922 fputc((value >> 8) & 0xff, file);
923 fputc((value >> 0) & 0xff, file);
925 else /* BYTE_ORDER_LITTLE_ENDIAN */
927 fputc((value >> 0) & 0xff, file);
928 fputc((value >> 8) & 0xff, file);
932 int getFile32BitInteger(FILE *file, int byte_order)
934 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
935 return ((fgetc(file) << 24) |
936 (fgetc(file) << 16) |
939 else /* BYTE_ORDER_LITTLE_ENDIAN */
940 return ((fgetc(file) << 0) |
942 (fgetc(file) << 16) |
943 (fgetc(file) << 24));
946 void putFile32BitInteger(FILE *file, int value, int byte_order)
948 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
950 fputc((value >> 24) & 0xff, file);
951 fputc((value >> 16) & 0xff, file);
952 fputc((value >> 8) & 0xff, file);
953 fputc((value >> 0) & 0xff, file);
955 else /* BYTE_ORDER_LITTLE_ENDIAN */
957 fputc((value >> 0) & 0xff, file);
958 fputc((value >> 8) & 0xff, file);
959 fputc((value >> 16) & 0xff, file);
960 fputc((value >> 24) & 0xff, file);
964 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
967 const int chunk_name_length = 4;
969 /* read chunk name */
970 fgets(chunk_name, chunk_name_length + 1, file);
972 if (chunk_size != NULL)
974 /* read chunk size */
975 *chunk_size = getFile32BitInteger(file, byte_order);
978 return (feof(file) || ferror(file) ? FALSE : TRUE);
981 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
984 /* write chunk name */
985 fputs(chunk_name, file);
989 /* write chunk size */
990 putFile32BitInteger(file, chunk_size, byte_order);
994 int getFileVersion(FILE *file)
996 int version_major = fgetc(file);
997 int version_minor = fgetc(file);
998 int version_patch = fgetc(file);
999 int version_build = fgetc(file);
1001 return VERSION_IDENT(version_major, version_minor, version_patch,
1005 void putFileVersion(FILE *file, int version)
1007 int version_major = VERSION_MAJOR(version);
1008 int version_minor = VERSION_MINOR(version);
1009 int version_patch = VERSION_PATCH(version);
1010 int version_build = VERSION_BUILD(version);
1012 fputc(version_major, file);
1013 fputc(version_minor, file);
1014 fputc(version_patch, file);
1015 fputc(version_build, file);
1018 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
1020 while (bytes-- && !feof(file))
1024 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
1031 /* ------------------------------------------------------------------------- */
1032 /* functions to translate key identifiers between different format */
1033 /* ------------------------------------------------------------------------- */
1035 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1036 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1037 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1038 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1040 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1049 /* normal cursor keys */
1050 { KSYM_Left, "XK_Left", "cursor left" },
1051 { KSYM_Right, "XK_Right", "cursor right" },
1052 { KSYM_Up, "XK_Up", "cursor up" },
1053 { KSYM_Down, "XK_Down", "cursor down" },
1055 /* keypad cursor keys */
1057 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1058 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1059 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1060 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1063 /* other keypad keys */
1064 #ifdef KSYM_KP_Enter
1065 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1066 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1067 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1068 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1069 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1070 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1074 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1075 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1076 { KSYM_Control_L, "XK_Control_L", "left control" },
1077 { KSYM_Control_R, "XK_Control_R", "right control" },
1078 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1079 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1080 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1081 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1082 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1083 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1084 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1085 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1087 /* some special keys */
1088 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1089 { KSYM_Delete, "XK_Delete", "delete" },
1090 { KSYM_Insert, "XK_Insert", "insert" },
1091 { KSYM_Tab, "XK_Tab", "tab" },
1092 { KSYM_Home, "XK_Home", "home" },
1093 { KSYM_End, "XK_End", "end" },
1094 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1095 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1096 { KSYM_Menu, "XK_Menu", "menu" }, /* Win-Menu */
1098 /* ASCII 0x20 to 0x40 keys (except numbers) */
1099 { KSYM_space, "XK_space", "space" },
1100 { KSYM_exclam, "XK_exclam", "!" },
1101 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1102 { KSYM_numbersign, "XK_numbersign", "#" },
1103 { KSYM_dollar, "XK_dollar", "$" },
1104 { KSYM_percent, "XK_percent", "%" },
1105 { KSYM_ampersand, "XK_ampersand", "&" },
1106 { KSYM_apostrophe, "XK_apostrophe", "'" },
1107 { KSYM_parenleft, "XK_parenleft", "(" },
1108 { KSYM_parenright, "XK_parenright", ")" },
1109 { KSYM_asterisk, "XK_asterisk", "*" },
1110 { KSYM_plus, "XK_plus", "+" },
1111 { KSYM_comma, "XK_comma", "," },
1112 { KSYM_minus, "XK_minus", "-" },
1113 { KSYM_period, "XK_period", "." },
1114 { KSYM_slash, "XK_slash", "/" },
1115 { KSYM_colon, "XK_colon", ":" },
1116 { KSYM_semicolon, "XK_semicolon", ";" },
1117 { KSYM_less, "XK_less", "<" },
1118 { KSYM_equal, "XK_equal", "=" },
1119 { KSYM_greater, "XK_greater", ">" },
1120 { KSYM_question, "XK_question", "?" },
1121 { KSYM_at, "XK_at", "@" },
1123 /* more ASCII keys */
1124 { KSYM_bracketleft, "XK_bracketleft", "[" },
1125 { KSYM_backslash, "XK_backslash", "backslash" },
1126 { KSYM_bracketright,"XK_bracketright", "]" },
1127 { KSYM_asciicircum, "XK_asciicircum", "circumflex" },
1128 { KSYM_underscore, "XK_underscore", "_" },
1129 { KSYM_grave, "XK_grave", "grave" },
1130 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1131 { KSYM_braceleft, "XK_braceleft", "brace left" },
1132 { KSYM_bar, "XK_bar", "bar" },
1133 { KSYM_braceright, "XK_braceright", "brace right" },
1134 { KSYM_asciitilde, "XK_asciitilde", "ascii tilde" },
1136 /* special (non-ASCII) keys */
1137 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
1138 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
1139 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
1140 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
1141 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
1142 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
1143 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1145 /* end-of-array identifier */
1151 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1153 static char name_buffer[30];
1156 if (key >= KSYM_A && key <= KSYM_Z)
1157 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1158 else if (key >= KSYM_a && key <= KSYM_z)
1159 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1160 else if (key >= KSYM_0 && key <= KSYM_9)
1161 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1162 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1163 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1164 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1165 sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1166 else if (key == KSYM_UNDEFINED)
1167 strcpy(name_buffer, "(undefined)");
1174 if (key == translate_key[i].key)
1176 strcpy(name_buffer, translate_key[i].name);
1180 while (translate_key[++i].name);
1182 if (!translate_key[i].name)
1183 strcpy(name_buffer, "(unknown)");
1186 *name = name_buffer;
1188 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1190 static char name_buffer[30];
1193 if (key >= KSYM_A && key <= KSYM_Z)
1194 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1195 else if (key >= KSYM_a && key <= KSYM_z)
1196 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1197 else if (key >= KSYM_0 && key <= KSYM_9)
1198 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1199 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1200 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1201 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1202 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1203 else if (key == KSYM_UNDEFINED)
1204 strcpy(name_buffer, "[undefined]");
1211 if (key == translate_key[i].key)
1213 strcpy(name_buffer, translate_key[i].x11name);
1217 while (translate_key[++i].x11name);
1219 if (!translate_key[i].x11name)
1220 sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1223 *x11name = name_buffer;
1225 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1227 Key key = KSYM_UNDEFINED;
1232 if (strcmp(translate_key[i].name, *name) == 0)
1234 key = translate_key[i].key;
1238 while (translate_key[++i].x11name);
1240 if (key == KSYM_UNDEFINED)
1241 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1245 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1247 Key key = KSYM_UNDEFINED;
1248 char *name_ptr = *x11name;
1250 if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1252 char c = name_ptr[3];
1254 if (c >= 'A' && c <= 'Z')
1255 key = KSYM_A + (Key)(c - 'A');
1256 else if (c >= 'a' && c <= 'z')
1257 key = KSYM_a + (Key)(c - 'a');
1258 else if (c >= '0' && c <= '9')
1259 key = KSYM_0 + (Key)(c - '0');
1261 else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1263 char c = name_ptr[6];
1265 if (c >= '0' && c <= '9')
1266 key = KSYM_0 + (Key)(c - '0');
1268 else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1270 char c1 = name_ptr[4];
1271 char c2 = name_ptr[5];
1274 if ((c1 >= '0' && c1 <= '9') &&
1275 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1276 d = atoi(&name_ptr[4]);
1278 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1279 key = KSYM_F1 + (Key)(d - 1);
1281 else if (strncmp(name_ptr, "XK_", 3) == 0)
1287 if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1289 key = translate_key[i].key;
1293 while (translate_key[++i].x11name);
1295 else if (strncmp(name_ptr, "0x", 2) == 0)
1297 unsigned long value = 0;
1303 char c = *name_ptr++;
1306 if (c >= '0' && c <= '9')
1308 else if (c >= 'a' && c <= 'f')
1309 d = (int)(c - 'a' + 10);
1310 else if (c >= 'A' && c <= 'F')
1311 d = (int)(c - 'A' + 10);
1319 value = value * 16 + d;
1330 char *getKeyNameFromKey(Key key)
1334 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1338 char *getX11KeyNameFromKey(Key key)
1342 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1346 Key getKeyFromKeyName(char *name)
1350 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1354 Key getKeyFromX11KeyName(char *x11name)
1358 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1362 char getCharFromKey(Key key)
1364 char *keyname = getKeyNameFromKey(key);
1367 if (strlen(keyname) == 1)
1368 letter = keyname[0];
1369 else if (strcmp(keyname, "space") == 0)
1371 else if (strcmp(keyname, "circumflex") == 0)
1378 /* ------------------------------------------------------------------------- */
1379 /* functions to translate string identifiers to integer or boolean value */
1380 /* ------------------------------------------------------------------------- */
1382 int get_integer_from_string(char *s)
1384 static char *number_text[][3] =
1386 { "0", "zero", "null", },
1387 { "1", "one", "first" },
1388 { "2", "two", "second" },
1389 { "3", "three", "third" },
1390 { "4", "four", "fourth" },
1391 { "5", "five", "fifth" },
1392 { "6", "six", "sixth" },
1393 { "7", "seven", "seventh" },
1394 { "8", "eight", "eighth" },
1395 { "9", "nine", "ninth" },
1396 { "10", "ten", "tenth" },
1397 { "11", "eleven", "eleventh" },
1398 { "12", "twelve", "twelfth" },
1400 { NULL, NULL, NULL },
1404 char *s_lower = getStringToLower(s);
1407 for (i = 0; number_text[i][0] != NULL; i++)
1408 for (j = 0; j < 3; j++)
1409 if (strcmp(s_lower, number_text[i][j]) == 0)
1414 if (strcmp(s_lower, "false") == 0)
1416 else if (strcmp(s_lower, "true") == 0)
1427 boolean get_boolean_from_string(char *s)
1429 char *s_lower = getStringToLower(s);
1430 boolean result = FALSE;
1432 if (strcmp(s_lower, "true") == 0 ||
1433 strcmp(s_lower, "yes") == 0 ||
1434 strcmp(s_lower, "on") == 0 ||
1435 get_integer_from_string(s) == 1)
1444 /* ------------------------------------------------------------------------- */
1445 /* functions for generic lists */
1446 /* ------------------------------------------------------------------------- */
1448 ListNode *newListNode()
1450 return checked_calloc(sizeof(ListNode));
1453 void addNodeToList(ListNode **node_first, char *key, void *content)
1455 ListNode *node_new = newListNode();
1458 printf("LIST: adding node with key '%s'\n", key);
1461 node_new->key = getStringCopy(key);
1462 node_new->content = content;
1463 node_new->next = *node_first;
1464 *node_first = node_new;
1467 void deleteNodeFromList(ListNode **node_first, char *key,
1468 void (*destructor_function)(void *))
1470 if (node_first == NULL || *node_first == NULL)
1474 printf("[CHECKING LIST KEY '%s' == '%s']\n",
1475 (*node_first)->key, key);
1478 if (strcmp((*node_first)->key, key) == 0)
1481 printf("[DELETING LIST ENTRY]\n");
1484 free((*node_first)->key);
1485 if (destructor_function)
1486 destructor_function((*node_first)->content);
1487 *node_first = (*node_first)->next;
1490 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1493 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1495 if (node_first == NULL)
1498 if (strcmp(node_first->key, key) == 0)
1501 return getNodeFromKey(node_first->next, key);
1504 int getNumNodes(ListNode *node_first)
1506 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1509 void dumpList(ListNode *node_first)
1511 ListNode *node = node_first;
1515 printf("['%s' (%d)]\n", node->key,
1516 ((struct ListNodeInfo *)node->content)->num_references);
1520 printf("[%d nodes]\n", getNumNodes(node_first));
1524 /* ------------------------------------------------------------------------- */
1525 /* functions for checking files and filenames */
1526 /* ------------------------------------------------------------------------- */
1528 boolean fileExists(char *filename)
1531 printf("checking file '%s'\n", filename);
1534 return (access(filename, F_OK) == 0);
1537 boolean fileHasPrefix(char *basename, char *prefix)
1539 static char *basename_lower = NULL;
1540 int basename_length, prefix_length;
1542 if (basename_lower != NULL)
1543 free(basename_lower);
1545 if (basename == NULL || prefix == NULL)
1548 basename_lower = getStringToLower(basename);
1549 basename_length = strlen(basename_lower);
1550 prefix_length = strlen(prefix);
1552 if (basename_length > prefix_length + 1 &&
1553 basename_lower[prefix_length] == '.' &&
1554 strncmp(basename_lower, prefix, prefix_length) == 0)
1560 boolean fileHasSuffix(char *basename, char *suffix)
1562 static char *basename_lower = NULL;
1563 int basename_length, suffix_length;
1565 if (basename_lower != NULL)
1566 free(basename_lower);
1568 if (basename == NULL || suffix == NULL)
1571 basename_lower = getStringToLower(basename);
1572 basename_length = strlen(basename_lower);
1573 suffix_length = strlen(suffix);
1575 if (basename_length > suffix_length + 1 &&
1576 basename_lower[basename_length - suffix_length - 1] == '.' &&
1577 strcmp(&basename_lower[basename_length - suffix_length], suffix) == 0)
1583 boolean FileIsGraphic(char *filename)
1585 char *basename = strrchr(filename, '/');
1587 basename = (basename != NULL ? basename + 1 : filename);
1589 return fileHasSuffix(basename, "pcx");
1592 boolean FileIsSound(char *filename)
1594 char *basename = strrchr(filename, '/');
1596 basename = (basename != NULL ? basename + 1 : filename);
1598 return fileHasSuffix(basename, "wav");
1601 boolean FileIsMusic(char *filename)
1603 char *basename = strrchr(filename, '/');
1605 basename = (basename != NULL ? basename + 1 : filename);
1607 if (FileIsSound(basename))
1610 #if defined(TARGET_SDL)
1611 if (fileHasPrefix(basename, "mod") ||
1612 fileHasSuffix(basename, "mod") ||
1613 fileHasSuffix(basename, "s3m") ||
1614 fileHasSuffix(basename, "it") ||
1615 fileHasSuffix(basename, "xm") ||
1616 fileHasSuffix(basename, "midi") ||
1617 fileHasSuffix(basename, "mid") ||
1618 fileHasSuffix(basename, "mp3") ||
1619 fileHasSuffix(basename, "ogg"))
1626 boolean FileIsArtworkType(char *basename, int type)
1628 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1629 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1630 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1636 /* ------------------------------------------------------------------------- */
1637 /* functions for loading artwork configuration information */
1638 /* ------------------------------------------------------------------------- */
1640 /* This function checks if a string <s> of the format "string1, string2, ..."
1641 exactly contains a string <s_contained>. */
1643 static boolean string_has_parameter(char *s, char *s_contained)
1647 if (s == NULL || s_contained == NULL)
1650 if (strlen(s_contained) > strlen(s))
1653 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
1655 char next_char = s[strlen(s_contained)];
1657 /* check if next character is delimiter or whitespace */
1658 return (next_char == ',' || next_char == '\0' ||
1659 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
1662 /* check if string contains another parameter string after a comma */
1663 substring = strchr(s, ',');
1664 if (substring == NULL) /* string does not contain a comma */
1667 /* advance string pointer to next character after the comma */
1670 /* skip potential whitespaces after the comma */
1671 while (*substring == ' ' || *substring == '\t')
1674 return string_has_parameter(substring, s_contained);
1677 int get_parameter_value(char *suffix, char *value_raw, int type)
1679 char *value = getStringToLower(value_raw);
1680 int result = 0; /* probably a save default value */
1682 if (strcmp(suffix, ".direction") == 0)
1684 result = (strcmp(value, "left") == 0 ? MV_LEFT :
1685 strcmp(value, "right") == 0 ? MV_RIGHT :
1686 strcmp(value, "up") == 0 ? MV_UP :
1687 strcmp(value, "down") == 0 ? MV_DOWN : MV_NO_MOVING);
1689 else if (strcmp(suffix, ".anim_mode") == 0)
1691 result = (string_has_parameter(value, "none") ? ANIM_NONE :
1692 string_has_parameter(value, "loop") ? ANIM_LOOP :
1693 string_has_parameter(value, "linear") ? ANIM_LINEAR :
1694 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
1695 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
1696 string_has_parameter(value, "random") ? ANIM_RANDOM :
1697 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
1698 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
1701 if (string_has_parameter(value, "reverse"))
1702 result |= ANIM_REVERSE;
1704 else /* generic parameter of type integer or boolean */
1706 result = (strcmp(value, ARG_UNDEFINED) == 0 ? ARG_UNDEFINED_VALUE :
1707 type == TYPE_INTEGER ? get_integer_from_string(value) :
1708 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
1709 ARG_UNDEFINED_VALUE);
1717 int get_auto_parameter_value(char *token, char *value_raw)
1721 if (token == NULL || value_raw == NULL)
1722 return ARG_UNDEFINED_VALUE;
1724 suffix = strrchr(token, '.');
1728 return get_parameter_value(suffix, value_raw, TYPE_INTEGER);
1731 static void FreeCustomArtworkList(struct ArtworkListInfo *,
1732 struct ListNodeInfo ***, int *);
1734 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
1735 struct ConfigInfo *suffix_list,
1736 char **ignore_tokens,
1737 int num_file_list_entries)
1739 struct FileInfo *file_list;
1740 int num_file_list_entries_found = 0;
1741 int num_suffix_list_entries = 0;
1745 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
1747 for (i = 0; suffix_list[i].token != NULL; i++)
1748 num_suffix_list_entries++;
1750 /* always start with reliable default values */
1751 for (i = 0; i < num_file_list_entries; i++)
1753 file_list[i].token = NULL;
1755 file_list[i].default_filename = NULL;
1756 file_list[i].filename = NULL;
1758 if (num_suffix_list_entries > 0)
1760 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1762 file_list[i].default_parameter = checked_calloc(parameter_array_size);
1763 file_list[i].parameter = checked_calloc(parameter_array_size);
1765 for (j = 0; j < num_suffix_list_entries; j++)
1767 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
1768 setString(&file_list[i].parameter[j], suffix_list[j].value);
1774 for (i = 0; config_list[i].token != NULL; i++)
1776 int len_config_token = strlen(config_list[i].token);
1777 int len_config_value = strlen(config_list[i].value);
1778 boolean is_file_entry = TRUE;
1780 for (j = 0; suffix_list[j].token != NULL; j++)
1782 int len_suffix = strlen(suffix_list[j].token);
1784 if (len_suffix < len_config_token &&
1785 strcmp(&config_list[i].token[len_config_token - len_suffix],
1786 suffix_list[j].token) == 0)
1788 setString(&file_list[list_pos].default_parameter[j],
1789 config_list[i].value);
1791 is_file_entry = FALSE;
1796 /* the following tokens are no file definitions, but other config tokens */
1797 for (j = 0; ignore_tokens[j] != NULL; j++)
1798 if (strcmp(config_list[i].token, ignore_tokens[j]) == 0)
1799 is_file_entry = FALSE;
1806 if (list_pos >= num_file_list_entries)
1809 /* simple sanity check if this is really a file definition */
1810 if (strcmp(&config_list[i].value[len_config_value - 4], ".pcx") != 0 &&
1811 strcmp(&config_list[i].value[len_config_value - 4], ".wav") != 0 &&
1812 strcmp(config_list[i].value, UNDEFINED_FILENAME) != 0)
1814 Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
1815 config_list[i].token, config_list[i].value);
1816 Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
1819 file_list[list_pos].token = config_list[i].token;
1820 file_list[list_pos].default_filename = config_list[i].value;
1824 num_file_list_entries_found = list_pos + 1;
1825 if (num_file_list_entries_found != num_file_list_entries)
1827 Error(ERR_RETURN_LINE, "-");
1828 Error(ERR_RETURN, "inconsistant config list information:");
1829 Error(ERR_RETURN, "- should be: %d (according to 'src/conf_gfx.h')",
1830 num_file_list_entries);
1831 Error(ERR_RETURN, "- found to be: %d (according to 'src/conf_gfx.c')",
1832 num_file_list_entries_found);
1833 Error(ERR_EXIT, "please fix");
1839 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
1841 int len_token = strlen(token);
1842 int len_suffix = strlen(suffix);
1845 if (IS_PARENT_PROCESS())
1846 printf(":::::::::: check '%s' for '%s' ::::::::::\n", token, suffix);
1849 if (start_pos < 0) /* compare suffix from end of string */
1850 start_pos += len_token;
1852 if (start_pos < 0 || start_pos + len_suffix > len_token)
1855 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
1858 if (token[start_pos + len_suffix] == '\0')
1861 if (token[start_pos + len_suffix] == '.')
1867 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN]"
1869 static void read_token_parameters(SetupFileHash *setup_file_hash,
1870 struct ConfigInfo *suffix_list,
1871 struct FileInfo *file_list_entry)
1873 /* check for config token that is the base token without any suffixes */
1874 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
1875 char *known_token_value = KNOWN_TOKEN_VALUE;
1878 if (filename != NULL)
1880 setString(&file_list_entry->filename, filename);
1882 /* when file definition found, set all parameters to default values */
1883 for (i = 0; suffix_list[i].token != NULL; i++)
1884 setString(&file_list_entry->parameter[i], suffix_list[i].value);
1886 file_list_entry->redefined = TRUE;
1888 /* mark config file token as well known from default config */
1889 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
1894 if (strcmp(file_list_entry->filename,
1895 file_list_entry->default_filename) != 0)
1896 printf("___ resetting '%s' to default\n", file_list_entry->token);
1898 setString(&file_list_entry->filename, file_list_entry->default_filename);
1902 /* check for config tokens that can be build by base token and suffixes */
1903 for (i = 0; suffix_list[i].token != NULL; i++)
1905 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
1906 char *value = getHashEntry(setup_file_hash, token);
1910 setString(&file_list_entry->parameter[i], value);
1912 /* mark config file token as well known from default config */
1913 setHashEntry(setup_file_hash, token, known_token_value);
1920 static void add_dynamic_file_list_entry(struct FileInfo **list,
1921 int *num_list_entries,
1922 SetupFileHash *extra_file_hash,
1923 struct ConfigInfo *suffix_list,
1924 int num_suffix_list_entries,
1927 struct FileInfo *new_list_entry;
1928 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1931 if (IS_PARENT_PROCESS())
1932 printf("===> found dynamic definition '%s'\n", token);
1935 (*num_list_entries)++;
1936 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
1937 new_list_entry = &(*list)[*num_list_entries - 1];
1939 new_list_entry->token = getStringCopy(token);
1940 new_list_entry->filename = NULL;
1941 new_list_entry->parameter = checked_calloc(parameter_array_size);
1943 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
1946 static void add_property_mapping(struct PropertyMapping **list,
1947 int *num_list_entries,
1948 int base_index, int ext1_index,
1949 int ext2_index, int ext3_index,
1952 struct PropertyMapping *new_list_entry;
1954 (*num_list_entries)++;
1955 *list = checked_realloc(*list,
1956 *num_list_entries * sizeof(struct PropertyMapping));
1957 new_list_entry = &(*list)[*num_list_entries - 1];
1959 new_list_entry->base_index = base_index;
1960 new_list_entry->ext1_index = ext1_index;
1961 new_list_entry->ext2_index = ext2_index;
1962 new_list_entry->ext3_index = ext3_index;
1964 new_list_entry->artwork_index = artwork_index;
1967 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
1970 struct FileInfo *file_list = artwork_info->file_list;
1971 struct ConfigInfo *suffix_list = artwork_info->suffix_list;
1972 char **base_prefixes = artwork_info->base_prefixes;
1973 char **ext1_suffixes = artwork_info->ext1_suffixes;
1974 char **ext2_suffixes = artwork_info->ext2_suffixes;
1975 char **ext3_suffixes = artwork_info->ext3_suffixes;
1976 char **ignore_tokens = artwork_info->ignore_tokens;
1977 int num_file_list_entries = artwork_info->num_file_list_entries;
1978 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
1979 int num_base_prefixes = artwork_info->num_base_prefixes;
1980 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
1981 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
1982 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
1983 int num_ignore_tokens = artwork_info->num_ignore_tokens;
1984 SetupFileHash *setup_file_hash, *extra_file_hash;
1985 char *known_token_value = KNOWN_TOKEN_VALUE;
1988 if (filename == NULL)
1992 printf("::: LoadArtworkConfigFromFilename: '%s'\n", filename);
1995 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
1998 /* read parameters for all known config file tokens */
1999 for (i = 0; i < num_file_list_entries; i++)
2000 read_token_parameters(setup_file_hash, suffix_list, &file_list[i]);
2002 /* set all tokens that can be ignored here to "known" keyword */
2003 for (i = 0; i < num_ignore_tokens; i++)
2004 setHashEntry(setup_file_hash, ignore_tokens[i], known_token_value);
2006 /* copy all unknown config file tokens to extra config list */
2007 extra_file_hash = newSetupFileHash();
2008 BEGIN_HASH_ITERATION(setup_file_hash, itr)
2010 if (strcmp(HASH_ITERATION_VALUE(itr), known_token_value) != 0)
2011 setHashEntry(extra_file_hash,
2012 HASH_ITERATION_TOKEN(itr), HASH_ITERATION_VALUE(itr));
2014 END_HASH_ITERATION(setup_file_hash, itr)
2016 /* at this point, we do not need the config file hash anymore -- free it */
2017 freeSetupFileHash(setup_file_hash);
2019 /* now try to determine valid, dynamically defined config tokens */
2021 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2023 struct FileInfo **dynamic_file_list =
2024 &artwork_info->dynamic_file_list;
2025 int *num_dynamic_file_list_entries =
2026 &artwork_info->num_dynamic_file_list_entries;
2027 struct PropertyMapping **property_mapping =
2028 &artwork_info->property_mapping;
2029 int *num_property_mapping_entries =
2030 &artwork_info->num_property_mapping_entries;
2031 int current_summarized_file_list_entry =
2032 artwork_info->num_file_list_entries +
2033 artwork_info->num_dynamic_file_list_entries;
2034 char *token = HASH_ITERATION_TOKEN(itr);
2035 int len_token = strlen(token);
2037 boolean base_prefix_found = FALSE;
2038 boolean parameter_suffix_found = FALSE;
2040 /* skip all parameter definitions (handled by read_token_parameters()) */
2041 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2043 int len_suffix = strlen(suffix_list[i].token);
2045 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2046 parameter_suffix_found = TRUE;
2050 if (IS_PARENT_PROCESS())
2052 if (parameter_suffix_found)
2053 printf("---> skipping token '%s' (parameter token)\n", token);
2055 printf("---> examining token '%s': search prefix ...\n", token);
2059 if (parameter_suffix_found)
2062 /* ---------- step 0: search for matching base prefix ---------- */
2065 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2067 char *base_prefix = base_prefixes[i];
2068 int len_base_prefix = strlen(base_prefix);
2069 boolean ext1_suffix_found = FALSE;
2070 boolean ext2_suffix_found = FALSE;
2071 boolean ext3_suffix_found = FALSE;
2072 boolean exact_match = FALSE;
2073 int base_index = -1;
2074 int ext1_index = -1;
2075 int ext2_index = -1;
2076 int ext3_index = -1;
2078 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2080 if (!base_prefix_found)
2085 if (start_pos + len_base_prefix == len_token) /* exact match */
2089 add_dynamic_file_list_entry(dynamic_file_list,
2090 num_dynamic_file_list_entries,
2093 num_suffix_list_entries,
2095 add_property_mapping(property_mapping,
2096 num_property_mapping_entries,
2097 base_index, -1, -1, -1,
2098 current_summarized_file_list_entry);
2103 if (IS_PARENT_PROCESS())
2104 printf("---> examining token '%s': search 1st suffix ...\n", token);
2107 /* ---------- step 1: search for matching first suffix ---------- */
2109 start_pos += len_base_prefix;
2110 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
2112 char *ext1_suffix = ext1_suffixes[j];
2113 int len_ext1_suffix = strlen(ext1_suffix);
2115 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2117 if (!ext1_suffix_found)
2122 if (start_pos + len_ext1_suffix == len_token) /* exact match */
2126 add_dynamic_file_list_entry(dynamic_file_list,
2127 num_dynamic_file_list_entries,
2130 num_suffix_list_entries,
2132 add_property_mapping(property_mapping,
2133 num_property_mapping_entries,
2134 base_index, ext1_index, -1, -1,
2135 current_summarized_file_list_entry);
2139 start_pos += len_ext1_suffix;
2146 if (IS_PARENT_PROCESS())
2147 printf("---> examining token '%s': search 2nd suffix ...\n", token);
2150 /* ---------- step 2: search for matching second suffix ---------- */
2152 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
2154 char *ext2_suffix = ext2_suffixes[k];
2155 int len_ext2_suffix = strlen(ext2_suffix);
2157 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
2159 if (!ext2_suffix_found)
2164 if (start_pos + len_ext2_suffix == len_token) /* exact match */
2168 add_dynamic_file_list_entry(dynamic_file_list,
2169 num_dynamic_file_list_entries,
2172 num_suffix_list_entries,
2174 add_property_mapping(property_mapping,
2175 num_property_mapping_entries,
2176 base_index, ext1_index, ext2_index, -1,
2177 current_summarized_file_list_entry);
2181 start_pos += len_ext2_suffix;
2188 if (IS_PARENT_PROCESS())
2189 printf("---> examining token '%s': search 3rd suffix ...\n",token);
2192 /* ---------- step 3: search for matching third suffix ---------- */
2194 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
2196 char *ext3_suffix = ext3_suffixes[l];
2197 int len_ext3_suffix = strlen(ext3_suffix);
2199 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
2201 if (!ext3_suffix_found)
2206 if (start_pos + len_ext3_suffix == len_token) /* exact match */
2210 add_dynamic_file_list_entry(dynamic_file_list,
2211 num_dynamic_file_list_entries,
2214 num_suffix_list_entries,
2216 add_property_mapping(property_mapping,
2217 num_property_mapping_entries,
2218 base_index, ext1_index, ext2_index, ext3_index,
2219 current_summarized_file_list_entry);
2225 END_HASH_ITERATION(extra_file_hash, itr)
2227 if (artwork_info->num_dynamic_file_list_entries > 0)
2229 artwork_info->dynamic_artwork_list =
2230 checked_calloc(artwork_info->num_dynamic_file_list_entries *
2231 artwork_info->sizeof_artwork_list_entry);
2234 if (extra_file_hash != NULL && options.verbose && IS_PARENT_PROCESS())
2236 SetupFileList *setup_file_list, *list;
2237 boolean dynamic_tokens_found = FALSE;
2238 boolean unknown_tokens_found = FALSE;
2240 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
2241 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
2243 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2245 if (strcmp(HASH_ITERATION_VALUE(itr), known_token_value) == 0)
2246 dynamic_tokens_found = TRUE;
2248 unknown_tokens_found = TRUE;
2250 END_HASH_ITERATION(extra_file_hash, itr)
2252 if (options.debug && dynamic_tokens_found)
2254 Error(ERR_RETURN_LINE, "-");
2255 Error(ERR_RETURN, "dynamic token(s) found in config file:");
2256 Error(ERR_RETURN, "- config file: '%s'", filename);
2258 for (list = setup_file_list; list != NULL; list = list->next)
2260 char *value = getHashEntry(extra_file_hash, list->token);
2262 if (value != NULL && strcmp(value, known_token_value) == 0)
2263 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2266 Error(ERR_RETURN_LINE, "-");
2269 if (unknown_tokens_found)
2271 Error(ERR_RETURN_LINE, "-");
2272 Error(ERR_RETURN, "warning: unknown token(s) found in config file:");
2273 Error(ERR_RETURN, "- config file: '%s'", filename);
2275 for (list = setup_file_list; list != NULL; list = list->next)
2277 char *value = getHashEntry(extra_file_hash, list->token);
2279 if (value != NULL && strcmp(value, known_token_value) != 0)
2280 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2283 Error(ERR_RETURN_LINE, "-");
2286 freeSetupFileList(setup_file_list);
2289 freeSetupFileHash(extra_file_hash);
2292 for (i = 0; i < num_file_list_entries; i++)
2294 printf("'%s' ", file_list[i].token);
2295 if (file_list[i].filename)
2296 printf("-> '%s'\n", file_list[i].filename);
2298 printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
2303 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
2305 struct FileInfo *file_list = artwork_info->file_list;
2306 int num_file_list_entries = artwork_info->num_file_list_entries;
2307 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2308 char *filename_base = UNDEFINED_FILENAME, *filename_local;
2312 printf("GOT CUSTOM ARTWORK CONFIG FILE '%s'\n", filename);
2315 DrawInitText("Loading artwork config:", 120, FC_GREEN);
2316 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
2318 /* always start with reliable default values */
2319 for (i = 0; i < num_file_list_entries; i++)
2321 setString(&file_list[i].filename, file_list[i].default_filename);
2323 for (j = 0; j < num_suffix_list_entries; j++)
2324 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
2326 file_list[i].redefined = FALSE;
2329 /* free previous dynamic artwork file array */
2330 if (artwork_info->dynamic_file_list != NULL)
2332 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
2334 free(artwork_info->dynamic_file_list[i].token);
2335 free(artwork_info->dynamic_file_list[i].filename);
2336 free(artwork_info->dynamic_file_list[i].parameter);
2339 free(artwork_info->dynamic_file_list);
2340 artwork_info->dynamic_file_list = NULL;
2342 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2343 &artwork_info->num_dynamic_file_list_entries);
2346 /* free previous property mapping */
2347 if (artwork_info->property_mapping != NULL)
2349 free(artwork_info->property_mapping);
2351 artwork_info->property_mapping = NULL;
2352 artwork_info->num_property_mapping_entries = 0;
2355 if (!SETUP_OVERRIDE_ARTWORK(setup, artwork_info->type))
2357 /* first look for special artwork configured in level series config */
2358 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
2360 if (fileExists(filename_base))
2361 LoadArtworkConfigFromFilename(artwork_info, filename_base);
2364 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
2366 if (filename_local != NULL && strcmp(filename_base, filename_local) != 0)
2367 LoadArtworkConfigFromFilename(artwork_info, filename_local);
2370 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
2371 struct ListNodeInfo **listnode)
2375 char *filename = (*listnode)->source_filename;
2378 printf("[decrementing reference counter of artwork '%s']\n", filename);
2381 if (--(*listnode)->num_references <= 0)
2384 printf("[deleting artwork '%s']\n", filename);
2387 deleteNodeFromList(&artwork_info->content_list, filename,
2388 artwork_info->free_artwork);
2395 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
2396 struct ListNodeInfo **listnode,
2401 "Loading graphics:",
2407 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
2409 if (filename == NULL)
2411 int error_mode = ERR_WARN;
2414 /* we can get away without sounds and music, but not without graphics */
2415 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2416 error_mode = ERR_EXIT;
2419 Error(error_mode, "cannot find artwork file '%s'", basename);
2423 /* check if the old and the new artwork file are the same */
2424 if (*listnode && strcmp((*listnode)->source_filename, filename) == 0)
2426 /* The old and new artwork are the same (have the same filename and path).
2427 This usually means that this artwork does not exist in this artwork set
2428 and a fallback to the existing artwork is done. */
2431 printf("[artwork '%s' already exists (same list entry)]\n", filename);
2437 /* delete existing artwork file entry */
2438 deleteArtworkListEntry(artwork_info, listnode);
2440 /* check if the new artwork file already exists in the list of artworks */
2441 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
2444 printf("[artwork '%s' already exists (other list entry)]\n", filename);
2447 *listnode = (struct ListNodeInfo *)node->content;
2448 (*listnode)->num_references++;
2454 printf("::: %s: '%s'\n", init_text[artwork_info->type], basename);
2457 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
2458 DrawInitText(basename, 150, FC_YELLOW);
2460 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
2463 printf("[adding new artwork '%s']\n", filename);
2466 (*listnode)->num_references = 1;
2467 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
2472 int error_mode = ERR_WARN;
2475 /* we can get away without sounds and music, but not without graphics */
2476 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2477 error_mode = ERR_EXIT;
2480 Error(error_mode, "cannot load artwork file '%s'", basename);
2485 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
2486 struct ListNodeInfo **listnode,
2490 printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
2493 if (strcmp(basename, UNDEFINED_FILENAME) == 0)
2495 deleteArtworkListEntry(artwork_info, listnode);
2499 replaceArtworkListEntry(artwork_info, listnode, basename);
2502 static void LoadArtworkToList(struct ArtworkListInfo *artwork_info,
2503 struct ListNodeInfo **listnode,
2504 char *basename, int list_pos)
2507 if (artwork_info->artwork_list == NULL ||
2508 list_pos >= artwork_info->num_file_list_entries)
2513 printf("loading artwork '%s' ... [%d]\n",
2514 basename, getNumNodes(artwork_info->content_list));
2518 LoadCustomArtwork(artwork_info, listnode, basename);
2520 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[list_pos],
2525 printf("loading artwork '%s' done [%d]\n",
2526 basename, getNumNodes(artwork_info->content_list));
2530 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
2532 struct FileInfo *file_list = artwork_info->file_list;
2533 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
2534 int num_file_list_entries = artwork_info->num_file_list_entries;
2535 int num_dynamic_file_list_entries =
2536 artwork_info->num_dynamic_file_list_entries;
2540 printf("DEBUG: reloading %d static artwork files ...\n",
2541 num_file_list_entries);
2544 for (i = 0; i < num_file_list_entries; i++)
2547 if (strcmp(file_list[i].token, "background") == 0)
2548 printf("::: '%s' -> '%s'\n", file_list[i].token, file_list[i].filename);
2551 LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2552 file_list[i].filename, i);
2555 if (artwork_info->artwork_list[i] == NULL &&
2556 strcmp(file_list[i].default_filename, file_list[i].filename) != 0)
2558 Error(ERR_WARN, "trying default artwork file '%s'",
2559 file_list[i].default_filename);
2561 LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2562 file_list[i].default_filename, i);
2568 printf("DEBUG: reloading %d dynamic artwork files ...\n",
2569 num_dynamic_file_list_entries);
2572 for (i = 0; i < num_dynamic_file_list_entries; i++)
2573 LoadArtworkToList(artwork_info, &artwork_info->dynamic_artwork_list[i],
2574 dynamic_file_list[i].filename, i);
2577 dumpList(artwork_info->content_list);
2581 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
2582 struct ListNodeInfo ***list,
2583 int *num_list_entries)
2590 for (i = 0; i < *num_list_entries; i++)
2591 deleteArtworkListEntry(artwork_info, &(*list)[i]);
2595 *num_list_entries = 0;
2598 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
2600 if (artwork_info == NULL)
2604 printf("%s: FREEING ARTWORK ...\n",
2605 IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2608 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
2609 &artwork_info->num_file_list_entries);
2611 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2612 &artwork_info->num_dynamic_file_list_entries);
2615 printf("%s: FREEING ARTWORK -- DONE\n",
2616 IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2621 /* ------------------------------------------------------------------------- */
2622 /* functions only needed for non-Unix (non-command-line) systems */
2623 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
2624 /* ------------------------------------------------------------------------- */
2626 #if defined(PLATFORM_MSDOS)
2628 #define ERROR_FILENAME "stderr.txt"
2630 void initErrorFile()
2632 unlink(ERROR_FILENAME);
2635 FILE *openErrorFile()
2637 return fopen(ERROR_FILENAME, MODE_APPEND);
2640 void dumpErrorFile()
2642 FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
2644 if (error_file != NULL)
2646 while (!feof(error_file))
2647 fputc(fgetc(error_file), stderr);
2655 /* ------------------------------------------------------------------------- */
2656 /* the following is only for debugging purpose and normally not used */
2657 /* ------------------------------------------------------------------------- */
2659 #define DEBUG_NUM_TIMESTAMPS 3
2661 void debug_print_timestamp(int counter_nr, char *message)
2663 static long counter[DEBUG_NUM_TIMESTAMPS][2];
2665 if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
2666 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
2668 counter[counter_nr][0] = Counter();
2671 printf("%s %.2f seconds\n", message,
2672 (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
2674 counter[counter_nr][1] = Counter();
2677 void debug_print_parent_only(char *format, ...)
2679 if (!IS_PARENT_PROCESS())
2686 va_start(ap, format);
2687 vprintf(format, ap);