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);
86 /* ------------------------------------------------------------------------- */
87 /* counter functions */
88 /* ------------------------------------------------------------------------- */
90 #if defined(PLATFORM_MSDOS)
91 volatile unsigned long counter = 0;
93 void increment_counter()
98 END_OF_FUNCTION(increment_counter);
102 /* maximal allowed length of a command line option */
103 #define MAX_OPTION_LEN 256
106 static unsigned long mainCounter(int mode)
108 static unsigned long base_ms = 0;
109 unsigned long current_ms;
110 unsigned long counter_ms;
112 current_ms = SDL_GetTicks();
114 /* reset base time in case of counter initializing or wrap-around */
115 if (mode == INIT_COUNTER || current_ms < base_ms)
116 base_ms = current_ms;
118 counter_ms = current_ms - base_ms;
120 return counter_ms; /* return milliseconds since last init */
123 #else /* !TARGET_SDL */
125 #if defined(PLATFORM_UNIX)
126 static unsigned long mainCounter(int mode)
128 static struct timeval base_time = { 0, 0 };
129 struct timeval current_time;
130 unsigned long counter_ms;
132 gettimeofday(¤t_time, NULL);
134 /* reset base time in case of counter initializing or wrap-around */
135 if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
136 base_time = current_time;
138 counter_ms = (current_time.tv_sec - base_time.tv_sec) * 1000
139 + (current_time.tv_usec - base_time.tv_usec) / 1000;
141 return counter_ms; /* return milliseconds since last init */
143 #endif /* PLATFORM_UNIX */
144 #endif /* !TARGET_SDL */
146 void InitCounter() /* set counter back to zero */
148 #if !defined(PLATFORM_MSDOS)
149 mainCounter(INIT_COUNTER);
151 LOCK_VARIABLE(counter);
152 LOCK_FUNCTION(increment_counter);
153 install_int_ex(increment_counter, BPS_TO_TIMER(100));
157 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
159 #if !defined(PLATFORM_MSDOS)
160 return mainCounter(READ_COUNTER);
162 return (counter * 10);
166 static void sleep_milliseconds(unsigned long milliseconds_delay)
168 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
171 #if defined(PLATFORM_MSDOS)
172 /* don't use select() to perform waiting operations under DOS
173 environment; always use a busy loop for waiting instead */
174 do_busy_waiting = TRUE;
180 /* we want to wait only a few ms -- if we assume that we have a
181 kernel timer resolution of 10 ms, we would wait far to long;
182 therefore it's better to do a short interval of busy waiting
183 to get our sleeping time more accurate */
185 unsigned long base_counter = Counter(), actual_counter = Counter();
187 while (actual_counter < base_counter + milliseconds_delay &&
188 actual_counter >= base_counter)
189 actual_counter = Counter();
193 #if defined(TARGET_SDL)
194 SDL_Delay(milliseconds_delay);
195 #elif defined(TARGET_ALLEGRO)
196 rest(milliseconds_delay);
198 struct timeval delay;
200 delay.tv_sec = milliseconds_delay / 1000;
201 delay.tv_usec = 1000 * (milliseconds_delay % 1000);
203 if (select(0, NULL, NULL, NULL, &delay) != 0)
204 Error(ERR_WARN, "sleep_milliseconds(): select() failed");
209 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
211 sleep_milliseconds(delay);
214 boolean FrameReached(unsigned long *frame_counter_var,
215 unsigned long frame_delay)
217 unsigned long actual_frame_counter = FrameCounter;
219 if (actual_frame_counter >= *frame_counter_var &&
220 actual_frame_counter < *frame_counter_var + frame_delay)
223 *frame_counter_var = actual_frame_counter;
228 boolean DelayReached(unsigned long *counter_var,
231 unsigned long actual_counter = Counter();
233 if (actual_counter >= *counter_var &&
234 actual_counter < *counter_var + delay)
237 *counter_var = actual_counter;
242 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
244 unsigned long actual_counter;
248 actual_counter = Counter();
250 if (actual_counter >= *counter_var &&
251 actual_counter < *counter_var + delay)
252 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
257 *counter_var = actual_counter;
261 /* ------------------------------------------------------------------------- */
262 /* random generator functions */
263 /* ------------------------------------------------------------------------- */
266 unsigned int SimpleRND(unsigned int max)
268 return (random_linux_libc(RND_FREE) % max);
271 unsigned int InitSimpleRND(long seed)
273 if (seed == NEW_RANDOMIZE)
275 struct timeval current_time;
277 gettimeofday(¤t_time, NULL);
278 seed = (long)current_time.tv_usec;
281 srandom_linux_libc(RND_FREE, (unsigned int) seed);
283 return (unsigned int) seed;
286 unsigned int RND(unsigned int max)
288 return (random_linux_libc(RND_GAME) % max);
291 unsigned int InitRND(long seed)
293 if (seed == NEW_RANDOMIZE)
295 struct timeval current_time;
297 gettimeofday(¤t_time, NULL);
298 seed = (long)current_time.tv_usec;
301 srandom_linux_libc(RND_GAME, (unsigned int) seed);
303 return (unsigned int) seed;
307 unsigned int init_random_number(int nr, long seed)
309 if (seed == NEW_RANDOMIZE)
311 #if defined(TARGET_SDL)
312 seed = (long)SDL_GetTicks();
314 struct timeval current_time;
316 gettimeofday(¤t_time, NULL);
317 seed = (long)current_time.tv_usec;
321 srandom_linux_libc(nr, (unsigned int) seed);
323 return (unsigned int) seed;
326 unsigned int get_random_number(int nr, unsigned int max)
328 return (max > 0 ? random_linux_libc(nr) % max : 0);
332 /* ------------------------------------------------------------------------- */
333 /* system info functions */
334 /* ------------------------------------------------------------------------- */
336 #if !defined(PLATFORM_MSDOS)
337 static char *get_corrected_real_name(char *real_name)
339 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
340 char *from_ptr = real_name;
341 char *to_ptr = real_name_new;
343 if (strchr(real_name, 'ß') == NULL) /* name does not contain 'ß' */
345 strncpy(real_name_new, real_name, MAX_USERNAME_LEN);
346 real_name_new[MAX_USERNAME_LEN] = '\0';
348 return real_name_new;
351 /* the user's real name may contain a 'ß' character (german sharp s),
352 which has no equivalent in upper case letters (which our fonts use) */
353 while (*from_ptr && (long)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
355 if (*from_ptr != 'ß')
356 *to_ptr++ = *from_ptr++;
367 return real_name_new;
373 static char *login_name = NULL;
375 #if defined(PLATFORM_WIN32)
376 if (login_name == NULL)
378 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
379 login_name = checked_malloc(buffer_size);
381 if (GetUserName(login_name, &buffer_size) == 0)
382 strcpy(login_name, ANONYMOUS_NAME);
385 if (login_name == NULL)
389 if ((pwd = getpwuid(getuid())) == NULL)
390 login_name = ANONYMOUS_NAME;
392 login_name = getStringCopy(pwd->pw_name);
401 static char *real_name = NULL;
403 #if defined(PLATFORM_WIN32)
404 if (real_name == NULL)
406 static char buffer[MAX_USERNAME_LEN + 1];
407 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
409 if (GetUserName(buffer, &buffer_size) != 0)
410 real_name = get_corrected_real_name(buffer);
412 real_name = ANONYMOUS_NAME;
414 #elif defined(PLATFORM_UNIX)
415 if (real_name == NULL)
419 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
420 real_name = get_corrected_real_name(pwd->pw_gecos);
422 real_name = ANONYMOUS_NAME;
425 real_name = ANONYMOUS_NAME;
433 static char *dir = NULL;
435 #if defined(PLATFORM_WIN32)
438 dir = checked_malloc(MAX_PATH + 1);
440 if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, dir)))
443 #elif defined(PLATFORM_UNIX)
446 if ((dir = getenv("HOME")) == NULL)
450 if ((pwd = getpwuid(getuid())) != NULL)
451 dir = getStringCopy(pwd->pw_dir);
464 /* ------------------------------------------------------------------------- */
465 /* various string functions */
466 /* ------------------------------------------------------------------------- */
468 char *getPath2(char *path1, char *path2)
470 char *complete_path = checked_malloc(strlen(path1) + 1 +
473 sprintf(complete_path, "%s/%s", path1, path2);
475 return complete_path;
478 char *getPath3(char *path1, char *path2, char *path3)
480 char *complete_path = checked_malloc(strlen(path1) + 1 +
484 sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
486 return complete_path;
489 char *getStringCat2(char *s1, char *s2)
491 char *complete_string = checked_malloc(strlen(s1) + strlen(s2) + 1);
493 sprintf(complete_string, "%s%s", s1, s2);
495 return complete_string;
498 char *getStringCopy(char *s)
505 s_copy = checked_malloc(strlen(s) + 1);
511 char *getStringToLower(char *s)
513 char *s_copy = checked_malloc(strlen(s) + 1);
514 char *s_ptr = s_copy;
517 *s_ptr++ = tolower(*s++);
523 void setString(char **old_value, char *new_value)
525 if (*old_value != NULL)
528 *old_value = getStringCopy(new_value);
532 /* ------------------------------------------------------------------------- */
533 /* command line option handling functions */
534 /* ------------------------------------------------------------------------- */
536 static void printUsage()
539 "Usage: %s [OPTION]... [HOSTNAME [PORT]]\n"
542 " -d, --display HOSTNAME[:SCREEN] specify X server display\n"
543 " -b, --basepath DIRECTORY alternative base DIRECTORY\n"
544 " -l, --level DIRECTORY alternative level DIRECTORY\n"
545 " -g, --graphics DIRECTORY alternative graphics DIRECTORY\n"
546 " -s, --sounds DIRECTORY alternative sounds DIRECTORY\n"
547 " -m, --music DIRECTORY alternative music DIRECTORY\n"
548 " -n, --network network multiplayer game\n"
549 " --serveronly only start network server\n"
550 " -v, --verbose verbose mode\n"
551 " --debug display debugging information\n"
552 " -e, --execute COMMAND execute batch COMMAND:\n"
554 "Valid commands for '--execute' option:\n"
555 " \"print graphicsinfo.conf\" print default graphics config\n"
556 " \"print soundsinfo.conf\" print default sounds config\n"
557 " \"print musicinfo.conf\" print default music config\n"
558 " \"dump level FILE\" dump level data from FILE\n"
559 " \"dump tape FILE\" dump tape data from FILE\n"
560 " \"autoplay LEVELDIR\" play level tapes for LEVELDIR\n"
562 program.command_basename);
565 void GetOptions(char *argv[])
567 char **options_left = &argv[1];
569 /* initialize global program options */
570 options.display_name = NULL;
571 options.server_host = NULL;
572 options.server_port = 0;
573 options.ro_base_directory = RO_BASE_PATH;
574 options.rw_base_directory = RW_BASE_PATH;
575 options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
576 options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
577 options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
578 options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
579 options.docs_directory = RO_BASE_PATH "/" DOCS_DIRECTORY;
580 options.execute_command = NULL;
581 options.serveronly = FALSE;
582 options.network = FALSE;
583 options.verbose = FALSE;
584 options.debug = FALSE;
586 #if !defined(PLATFORM_UNIX)
587 if (*options_left == NULL) /* no options given -- enable verbose mode */
588 options.verbose = TRUE;
591 while (*options_left)
593 char option_str[MAX_OPTION_LEN];
594 char *option = options_left[0];
595 char *next_option = options_left[1];
596 char *option_arg = NULL;
597 int option_len = strlen(option);
599 if (option_len >= MAX_OPTION_LEN)
600 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
602 strcpy(option_str, option); /* copy argument into buffer */
605 if (strcmp(option, "--") == 0) /* stop scanning arguments */
608 if (strncmp(option, "--", 2) == 0) /* treat '--' like '-' */
611 option_arg = strchr(option, '=');
612 if (option_arg == NULL) /* no '=' in option */
613 option_arg = next_option;
616 *option_arg++ = '\0'; /* cut argument from option */
617 if (*option_arg == '\0') /* no argument after '=' */
618 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
621 option_len = strlen(option);
623 if (strcmp(option, "-") == 0)
624 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
625 else if (strncmp(option, "-help", option_len) == 0)
631 else if (strncmp(option, "-display", option_len) == 0)
633 if (option_arg == NULL)
634 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
636 options.display_name = option_arg;
637 if (option_arg == next_option)
640 else if (strncmp(option, "-basepath", option_len) == 0)
642 if (option_arg == NULL)
643 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
645 /* this should be extended to separate options for ro and rw data */
646 options.ro_base_directory = option_arg;
647 options.rw_base_directory = option_arg;
648 if (option_arg == next_option)
651 /* adjust path for level directory accordingly */
652 options.level_directory =
653 getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
655 else if (strncmp(option, "-levels", option_len) == 0)
657 if (option_arg == NULL)
658 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
660 options.level_directory = option_arg;
661 if (option_arg == next_option)
664 else if (strncmp(option, "-graphics", option_len) == 0)
666 if (option_arg == NULL)
667 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
669 options.graphics_directory = option_arg;
670 if (option_arg == next_option)
673 else if (strncmp(option, "-sounds", option_len) == 0)
675 if (option_arg == NULL)
676 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
678 options.sounds_directory = option_arg;
679 if (option_arg == next_option)
682 else if (strncmp(option, "-music", option_len) == 0)
684 if (option_arg == NULL)
685 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
687 options.music_directory = option_arg;
688 if (option_arg == next_option)
691 else if (strncmp(option, "-network", option_len) == 0)
693 options.network = TRUE;
695 else if (strncmp(option, "-serveronly", option_len) == 0)
697 options.serveronly = TRUE;
699 else if (strncmp(option, "-verbose", option_len) == 0)
701 options.verbose = TRUE;
703 else if (strncmp(option, "-debug", option_len) == 0)
705 options.debug = TRUE;
707 else if (strncmp(option, "-execute", option_len) == 0)
709 if (option_arg == NULL)
710 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
712 options.execute_command = option_arg;
713 if (option_arg == next_option)
716 else if (*option == '-')
718 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
720 else if (options.server_host == NULL)
722 options.server_host = *options_left;
724 else if (options.server_port == 0)
726 options.server_port = atoi(*options_left);
727 if (options.server_port < 1024)
728 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
731 Error(ERR_EXIT_HELP, "too many arguments");
738 /* ------------------------------------------------------------------------- */
739 /* error handling functions */
740 /* ------------------------------------------------------------------------- */
742 /* used by SetError() and GetError() to store internal error messages */
743 static char internal_error[1024]; /* this is bad */
745 void SetError(char *format, ...)
749 va_start(ap, format);
750 vsprintf(internal_error, format, ap);
756 return internal_error;
759 void Error(int mode, char *format, ...)
761 static boolean last_line_was_separator = FALSE;
762 char *process_name = "";
763 FILE *error = stderr;
764 char *newline = "\n";
766 /* display warnings only when running in verbose mode */
767 if (mode & ERR_WARN && !options.verbose)
770 if (mode == ERR_RETURN_LINE)
772 if (!last_line_was_separator)
773 fprintf_line(error, format, 79);
775 last_line_was_separator = TRUE;
780 last_line_was_separator = FALSE;
782 #if defined(PLATFORM_MSDOS)
785 if ((error = openErrorFile()) == NULL)
787 printf("Cannot write to error output file!%s", newline);
788 program.exit_function(1);
792 if (mode & ERR_SOUND_SERVER)
793 process_name = " sound server";
794 else if (mode & ERR_NETWORK_SERVER)
795 process_name = " network server";
796 else if (mode & ERR_NETWORK_CLIENT)
797 process_name = " network client **";
803 fprintf(error, "%s%s: ", program.command_basename, process_name);
806 fprintf(error, "warning: ");
808 va_start(ap, format);
809 vfprintf(error, format, ap);
812 fprintf(error, "%s", newline);
816 fprintf(error, "%s: Try option '--help' for more information.%s",
817 program.command_basename, newline);
820 fprintf(error, "%s%s: aborting%s",
821 program.command_basename, process_name, newline);
828 if (mode & ERR_FROM_SERVER)
829 exit(1); /* child process: normal exit */
831 program.exit_function(1); /* main process: clean up stuff */
836 /* ------------------------------------------------------------------------- */
837 /* memory allocation functions */
838 /* ------------------------------------------------------------------------- */
840 void *checked_malloc(unsigned long size)
847 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
852 void *checked_calloc(unsigned long size)
856 ptr = calloc(1, size);
859 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
864 void *checked_realloc(void *ptr, unsigned long size)
866 ptr = realloc(ptr, size);
869 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
875 /* ------------------------------------------------------------------------- */
876 /* various helper functions */
877 /* ------------------------------------------------------------------------- */
879 inline void swap_numbers(int *i1, int *i2)
887 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
899 short getFile16BitInteger(FILE *file, int byte_order)
901 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
902 return ((fgetc(file) << 8) |
904 else /* BYTE_ORDER_LITTLE_ENDIAN */
905 return ((fgetc(file) << 0) |
909 void putFile16BitInteger(FILE *file, short value, int byte_order)
911 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
913 fputc((value >> 8) & 0xff, file);
914 fputc((value >> 0) & 0xff, file);
916 else /* BYTE_ORDER_LITTLE_ENDIAN */
918 fputc((value >> 0) & 0xff, file);
919 fputc((value >> 8) & 0xff, file);
923 int getFile32BitInteger(FILE *file, int byte_order)
925 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
926 return ((fgetc(file) << 24) |
927 (fgetc(file) << 16) |
930 else /* BYTE_ORDER_LITTLE_ENDIAN */
931 return ((fgetc(file) << 0) |
933 (fgetc(file) << 16) |
934 (fgetc(file) << 24));
937 void putFile32BitInteger(FILE *file, int value, int byte_order)
939 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
941 fputc((value >> 24) & 0xff, file);
942 fputc((value >> 16) & 0xff, file);
943 fputc((value >> 8) & 0xff, file);
944 fputc((value >> 0) & 0xff, file);
946 else /* BYTE_ORDER_LITTLE_ENDIAN */
948 fputc((value >> 0) & 0xff, file);
949 fputc((value >> 8) & 0xff, file);
950 fputc((value >> 16) & 0xff, file);
951 fputc((value >> 24) & 0xff, file);
955 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
958 const int chunk_name_length = 4;
960 /* read chunk name */
961 fgets(chunk_name, chunk_name_length + 1, file);
963 if (chunk_size != NULL)
965 /* read chunk size */
966 *chunk_size = getFile32BitInteger(file, byte_order);
969 return (feof(file) || ferror(file) ? FALSE : TRUE);
972 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
975 /* write chunk name */
976 fputs(chunk_name, file);
980 /* write chunk size */
981 putFile32BitInteger(file, chunk_size, byte_order);
985 int getFileVersion(FILE *file)
987 int version_major, version_minor, version_patch, version_release;
989 version_major = fgetc(file);
990 version_minor = fgetc(file);
991 version_patch = fgetc(file);
992 version_release = fgetc(file);
994 return RELEASE_IDENT(version_major, version_minor, version_patch,
998 void putFileVersion(FILE *file, int version)
1000 int version_major = VERSION_MAJOR(version);
1001 int version_minor = VERSION_MINOR(version);
1002 int version_patch = VERSION_PATCH(version);
1003 int version_release = VERSION_RELEASE(version);
1005 fputc(version_major, file);
1006 fputc(version_minor, file);
1007 fputc(version_patch, file);
1008 fputc(version_release, file);
1011 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
1013 while (bytes-- && !feof(file))
1017 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
1024 /* ------------------------------------------------------------------------- */
1025 /* functions to translate key identifiers between different format */
1026 /* ------------------------------------------------------------------------- */
1028 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1029 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1030 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1031 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1033 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1042 /* normal cursor keys */
1043 { KSYM_Left, "XK_Left", "cursor left" },
1044 { KSYM_Right, "XK_Right", "cursor right" },
1045 { KSYM_Up, "XK_Up", "cursor up" },
1046 { KSYM_Down, "XK_Down", "cursor down" },
1048 /* keypad cursor keys */
1050 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1051 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1052 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1053 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1056 /* other keypad keys */
1057 #ifdef KSYM_KP_Enter
1058 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1059 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1060 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1061 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1062 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1063 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1067 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1068 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1069 { KSYM_Control_L, "XK_Control_L", "left control" },
1070 { KSYM_Control_R, "XK_Control_R", "right control" },
1071 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1072 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1073 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1074 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1075 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1076 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1077 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1078 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1080 /* some special keys */
1081 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1082 { KSYM_Delete, "XK_Delete", "delete" },
1083 { KSYM_Insert, "XK_Insert", "insert" },
1084 { KSYM_Tab, "XK_Tab", "tab" },
1085 { KSYM_Home, "XK_Home", "home" },
1086 { KSYM_End, "XK_End", "end" },
1087 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1088 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1089 { KSYM_Menu, "XK_Menu", "menu" }, /* Win-Menu */
1091 /* ASCII 0x20 to 0x40 keys (except numbers) */
1092 { KSYM_space, "XK_space", "space" },
1093 { KSYM_exclam, "XK_exclam", "!" },
1094 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1095 { KSYM_numbersign, "XK_numbersign", "#" },
1096 { KSYM_dollar, "XK_dollar", "$" },
1097 { KSYM_percent, "XK_percent", "%" },
1098 { KSYM_ampersand, "XK_ampersand", "&" },
1099 { KSYM_apostrophe, "XK_apostrophe", "'" },
1100 { KSYM_parenleft, "XK_parenleft", "(" },
1101 { KSYM_parenright, "XK_parenright", ")" },
1102 { KSYM_asterisk, "XK_asterisk", "*" },
1103 { KSYM_plus, "XK_plus", "+" },
1104 { KSYM_comma, "XK_comma", "," },
1105 { KSYM_minus, "XK_minus", "-" },
1106 { KSYM_period, "XK_period", "." },
1107 { KSYM_slash, "XK_slash", "/" },
1108 { KSYM_colon, "XK_colon", ":" },
1109 { KSYM_semicolon, "XK_semicolon", ";" },
1110 { KSYM_less, "XK_less", "<" },
1111 { KSYM_equal, "XK_equal", "=" },
1112 { KSYM_greater, "XK_greater", ">" },
1113 { KSYM_question, "XK_question", "?" },
1114 { KSYM_at, "XK_at", "@" },
1116 /* more ASCII keys */
1117 { KSYM_bracketleft, "XK_bracketleft", "[" },
1118 { KSYM_backslash, "XK_backslash", "backslash" },
1119 { KSYM_bracketright,"XK_bracketright", "]" },
1120 { KSYM_asciicircum, "XK_asciicircum", "circumflex" },
1121 { KSYM_underscore, "XK_underscore", "_" },
1122 { KSYM_grave, "XK_grave", "grave" },
1123 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1124 { KSYM_braceleft, "XK_braceleft", "brace left" },
1125 { KSYM_bar, "XK_bar", "bar" },
1126 { KSYM_braceright, "XK_braceright", "brace right" },
1127 { KSYM_asciitilde, "XK_asciitilde", "ascii tilde" },
1129 /* special (non-ASCII) keys */
1130 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
1131 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
1132 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
1133 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
1134 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
1135 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
1136 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1138 /* end-of-array identifier */
1144 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1146 static char name_buffer[30];
1149 if (key >= KSYM_A && key <= KSYM_Z)
1150 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1151 else if (key >= KSYM_a && key <= KSYM_z)
1152 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1153 else if (key >= KSYM_0 && key <= KSYM_9)
1154 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1155 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1156 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1157 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1158 sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1159 else if (key == KSYM_UNDEFINED)
1160 strcpy(name_buffer, "(undefined)");
1167 if (key == translate_key[i].key)
1169 strcpy(name_buffer, translate_key[i].name);
1173 while (translate_key[++i].name);
1175 if (!translate_key[i].name)
1176 strcpy(name_buffer, "(unknown)");
1179 *name = name_buffer;
1181 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1183 static char name_buffer[30];
1186 if (key >= KSYM_A && key <= KSYM_Z)
1187 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1188 else if (key >= KSYM_a && key <= KSYM_z)
1189 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1190 else if (key >= KSYM_0 && key <= KSYM_9)
1191 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1192 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1193 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1194 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1195 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1196 else if (key == KSYM_UNDEFINED)
1197 strcpy(name_buffer, "[undefined]");
1204 if (key == translate_key[i].key)
1206 strcpy(name_buffer, translate_key[i].x11name);
1210 while (translate_key[++i].x11name);
1212 if (!translate_key[i].x11name)
1213 sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1216 *x11name = name_buffer;
1218 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1220 Key key = KSYM_UNDEFINED;
1225 if (strcmp(translate_key[i].name, *name) == 0)
1227 key = translate_key[i].key;
1231 while (translate_key[++i].x11name);
1233 if (key == KSYM_UNDEFINED)
1234 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1238 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1240 Key key = KSYM_UNDEFINED;
1241 char *name_ptr = *x11name;
1243 if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1245 char c = name_ptr[3];
1247 if (c >= 'A' && c <= 'Z')
1248 key = KSYM_A + (Key)(c - 'A');
1249 else if (c >= 'a' && c <= 'z')
1250 key = KSYM_a + (Key)(c - 'a');
1251 else if (c >= '0' && c <= '9')
1252 key = KSYM_0 + (Key)(c - '0');
1254 else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1256 char c = name_ptr[6];
1258 if (c >= '0' && c <= '9')
1259 key = KSYM_0 + (Key)(c - '0');
1261 else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1263 char c1 = name_ptr[4];
1264 char c2 = name_ptr[5];
1267 if ((c1 >= '0' && c1 <= '9') &&
1268 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1269 d = atoi(&name_ptr[4]);
1271 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1272 key = KSYM_F1 + (Key)(d - 1);
1274 else if (strncmp(name_ptr, "XK_", 3) == 0)
1280 if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1282 key = translate_key[i].key;
1286 while (translate_key[++i].x11name);
1288 else if (strncmp(name_ptr, "0x", 2) == 0)
1290 unsigned long value = 0;
1296 char c = *name_ptr++;
1299 if (c >= '0' && c <= '9')
1301 else if (c >= 'a' && c <= 'f')
1302 d = (int)(c - 'a' + 10);
1303 else if (c >= 'A' && c <= 'F')
1304 d = (int)(c - 'A' + 10);
1312 value = value * 16 + d;
1323 char *getKeyNameFromKey(Key key)
1327 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1331 char *getX11KeyNameFromKey(Key key)
1335 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1339 Key getKeyFromKeyName(char *name)
1343 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1347 Key getKeyFromX11KeyName(char *x11name)
1351 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1355 char getCharFromKey(Key key)
1357 char *keyname = getKeyNameFromKey(key);
1360 if (strlen(keyname) == 1)
1361 letter = keyname[0];
1362 else if (strcmp(keyname, "space") == 0)
1364 else if (strcmp(keyname, "circumflex") == 0)
1371 /* ------------------------------------------------------------------------- */
1372 /* functions to translate string identifiers to integer or boolean value */
1373 /* ------------------------------------------------------------------------- */
1375 int get_integer_from_string(char *s)
1377 static char *number_text[][3] =
1379 { "0", "zero", "null", },
1380 { "1", "one", "first" },
1381 { "2", "two", "second" },
1382 { "3", "three", "third" },
1383 { "4", "four", "fourth" },
1384 { "5", "five", "fifth" },
1385 { "6", "six", "sixth" },
1386 { "7", "seven", "seventh" },
1387 { "8", "eight", "eighth" },
1388 { "9", "nine", "ninth" },
1389 { "10", "ten", "tenth" },
1390 { "11", "eleven", "eleventh" },
1391 { "12", "twelve", "twelfth" },
1395 char *s_lower = getStringToLower(s);
1398 for (i=0; i<13; i++)
1400 if (strcmp(s_lower, number_text[i][j]) == 0)
1411 boolean get_boolean_from_string(char *s)
1413 char *s_lower = getStringToLower(s);
1414 boolean result = FALSE;
1416 if (strcmp(s_lower, "true") == 0 ||
1417 strcmp(s_lower, "yes") == 0 ||
1418 strcmp(s_lower, "on") == 0 ||
1419 get_integer_from_string(s) == 1)
1428 /* ------------------------------------------------------------------------- */
1429 /* functions for generic lists */
1430 /* ------------------------------------------------------------------------- */
1432 ListNode *newListNode()
1434 return checked_calloc(sizeof(ListNode));
1437 void addNodeToList(ListNode **node_first, char *key, void *content)
1439 ListNode *node_new = newListNode();
1442 printf("LIST: adding node with key '%s'\n", key);
1445 node_new->key = getStringCopy(key);
1446 node_new->content = content;
1447 node_new->next = *node_first;
1448 *node_first = node_new;
1451 void deleteNodeFromList(ListNode **node_first, char *key,
1452 void (*destructor_function)(void *))
1454 if (node_first == NULL || *node_first == NULL)
1458 printf("[CHECKING LIST KEY '%s' == '%s']\n",
1459 (*node_first)->key, key);
1462 if (strcmp((*node_first)->key, key) == 0)
1465 printf("[DELETING LIST ENTRY]\n");
1468 free((*node_first)->key);
1469 if (destructor_function)
1470 destructor_function((*node_first)->content);
1471 *node_first = (*node_first)->next;
1474 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1477 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1479 if (node_first == NULL)
1482 if (strcmp(node_first->key, key) == 0)
1485 return getNodeFromKey(node_first->next, key);
1488 int getNumNodes(ListNode *node_first)
1490 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1493 void dumpList(ListNode *node_first)
1495 ListNode *node = node_first;
1499 printf("['%s' (%d)]\n", node->key,
1500 ((struct ListNodeInfo *)node->content)->num_references);
1504 printf("[%d nodes]\n", getNumNodes(node_first));
1508 /* ------------------------------------------------------------------------- */
1509 /* functions for checking files and filenames */
1510 /* ------------------------------------------------------------------------- */
1512 boolean fileExists(char *filename)
1515 printf("checking file '%s'\n", filename);
1518 return (access(filename, F_OK) == 0);
1521 boolean FileIsGraphic(char *filename)
1523 if (strlen(filename) > 4 &&
1524 strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1530 boolean FileIsSound(char *basename)
1532 if (strlen(basename) > 4 &&
1533 strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1539 boolean FileIsMusic(char *basename)
1541 /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1543 if (FileIsSound(basename))
1546 #if defined(TARGET_SDL)
1547 if (strlen(basename) > 4 &&
1548 (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1549 strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1550 strncmp(basename, "mod.", 4) == 0 ||
1551 strncmp(basename, "MOD.", 4) == 0))
1558 boolean FileIsArtworkType(char *basename, int type)
1560 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1561 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1562 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1568 /* ------------------------------------------------------------------------- */
1569 /* functions for loading artwork configuration information */
1570 /* ------------------------------------------------------------------------- */
1572 /* This function checks if a string <s> of the format "string1, string2, ..."
1573 exactly contains a string <s_contained>. */
1575 static boolean string_has_parameter(char *s, char *s_contained)
1579 if (s == NULL || s_contained == NULL)
1582 if (strlen(s_contained) > strlen(s))
1585 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
1587 char next_char = s[strlen(s_contained)];
1589 /* check if next character is delimiter or whitespace */
1590 return (next_char == ',' || next_char == '\0' ||
1591 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
1594 /* check if string contains another parameter string after a comma */
1595 substring = strchr(s, ',');
1596 if (substring == NULL) /* string does not contain a comma */
1599 /* advance string pointer to next character after the comma */
1602 /* skip potential whitespaces after the comma */
1603 while (*substring == ' ' || *substring == '\t')
1606 return string_has_parameter(substring, s_contained);
1609 int get_parameter_value(char *token, char *value_raw, int type)
1611 char *value = getStringToLower(value_raw);
1612 int result = 0; /* probably a save default value */
1614 if (strcmp(token, ".direction") == 0)
1616 result = (strcmp(value, "left") == 0 ? MV_LEFT :
1617 strcmp(value, "right") == 0 ? MV_RIGHT :
1618 strcmp(value, "up") == 0 ? MV_UP :
1619 strcmp(value, "down") == 0 ? MV_DOWN : MV_NO_MOVING);
1621 else if (strcmp(token, ".anim_mode") == 0)
1623 result = (string_has_parameter(value, "loop") ? ANIM_LOOP :
1624 string_has_parameter(value, "linear") ? ANIM_LINEAR :
1625 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
1626 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
1627 string_has_parameter(value, "random") ? ANIM_RANDOM :
1628 string_has_parameter(value, "none") ? ANIM_NONE :
1631 if (string_has_parameter(value, "reverse"))
1632 result |= ANIM_REVERSE;
1634 else /* generic parameter of type integer or boolean */
1636 result = (strcmp(value, ARG_UNDEFINED) == 0 ? ARG_UNDEFINED_VALUE :
1637 type == TYPE_INTEGER ? get_integer_from_string(value) :
1638 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
1639 ARG_UNDEFINED_VALUE);
1647 static void FreeCustomArtworkList(struct ArtworkListInfo *,
1648 struct ListNodeInfo ***, int *);
1650 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
1651 struct ConfigInfo *suffix_list,
1652 char **ignore_tokens,
1653 int num_file_list_entries)
1655 struct FileInfo *file_list;
1656 int num_file_list_entries_found = 0;
1657 int num_suffix_list_entries = 0;
1661 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
1663 for (i=0; suffix_list[i].token != NULL; i++)
1664 num_suffix_list_entries++;
1666 /* always start with reliable default values */
1667 for (i=0; i<num_file_list_entries; i++)
1669 file_list[i].token = NULL;
1671 file_list[i].default_filename = NULL;
1672 file_list[i].filename = NULL;
1674 if (num_suffix_list_entries > 0)
1676 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1678 file_list[i].default_parameter = checked_calloc(parameter_array_size);
1679 file_list[i].parameter = checked_calloc(parameter_array_size);
1681 for (j=0; j<num_suffix_list_entries; j++)
1683 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
1684 setString(&file_list[i].parameter[j], suffix_list[j].value);
1690 for (i=0; config_list[i].token != NULL; i++)
1692 int len_config_token = strlen(config_list[i].token);
1693 int len_config_value = strlen(config_list[i].value);
1694 boolean is_file_entry = TRUE;
1696 for (j=0; suffix_list[j].token != NULL; j++)
1698 int len_suffix = strlen(suffix_list[j].token);
1700 if (len_suffix < len_config_token &&
1701 strcmp(&config_list[i].token[len_config_token - len_suffix],
1702 suffix_list[j].token) == 0)
1704 setString(&file_list[list_pos].default_parameter[j],
1705 config_list[i].value);
1707 is_file_entry = FALSE;
1712 /* the following tokens are no file definitions, but other config tokens */
1713 for (j=0; ignore_tokens[j] != NULL; j++)
1714 if (strcmp(config_list[i].token, ignore_tokens[j]) == 0)
1715 is_file_entry = FALSE;
1722 if (list_pos >= num_file_list_entries)
1725 /* simple sanity check if this is really a file definition */
1726 if (strcmp(&config_list[i].value[len_config_value - 4], ".pcx") != 0 &&
1727 strcmp(&config_list[i].value[len_config_value - 4], ".wav") != 0 &&
1728 strcmp(config_list[i].value, UNDEFINED_FILENAME) != 0)
1730 Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
1731 config_list[i].token, config_list[i].value);
1732 Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
1735 file_list[list_pos].token = config_list[i].token;
1736 file_list[list_pos].default_filename = config_list[i].value;
1740 num_file_list_entries_found = list_pos + 1;
1741 if (num_file_list_entries_found != num_file_list_entries)
1743 Error(ERR_RETURN_LINE, "-");
1744 Error(ERR_RETURN, "inconsistant config list information:");
1745 Error(ERR_RETURN, "- should be: %d (according to 'src/conf_gfx.h')",
1746 num_file_list_entries);
1747 Error(ERR_RETURN, "- found to be: %d (according to 'src/conf_gfx.c')",
1748 num_file_list_entries_found);
1749 Error(ERR_EXIT, "please fix");
1755 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
1757 int len_token = strlen(token);
1758 int len_suffix = strlen(suffix);
1761 if (IS_PARENT_PROCESS())
1762 printf(":::::::::: check '%s' for '%s' ::::::::::\n", token, suffix);
1765 if (start_pos < 0) /* compare suffix from end of string */
1766 start_pos += len_token;
1768 if (start_pos < 0 || start_pos + len_suffix > len_token)
1771 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
1774 if (token[start_pos + len_suffix] == '\0')
1777 if (token[start_pos + len_suffix] == '.')
1783 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN]"
1785 static void read_token_parameters(SetupFileHash *setup_file_hash,
1786 struct ConfigInfo *suffix_list,
1787 struct FileInfo *file_list_entry)
1789 /* check for config token that is the base token without any suffixes */
1790 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
1791 char *known_token_value = KNOWN_TOKEN_VALUE;
1794 if (filename != NULL)
1796 setString(&file_list_entry->filename, filename);
1798 /* when file definition found, set all parameters to default values */
1799 for (i=0; suffix_list[i].token != NULL; i++)
1800 setString(&file_list_entry->parameter[i], suffix_list[i].value);
1802 file_list_entry->redefined = TRUE;
1804 /* mark config file token as well known from default config */
1805 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
1810 if (strcmp(file_list_entry->filename,
1811 file_list_entry->default_filename) != 0)
1812 printf("___ resetting '%s' to default\n", file_list_entry->token);
1814 setString(&file_list_entry->filename, file_list_entry->default_filename);
1818 /* check for config tokens that can be build by base token and suffixes */
1819 for (i=0; suffix_list[i].token != NULL; i++)
1821 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
1822 char *value = getHashEntry(setup_file_hash, token);
1826 setString(&file_list_entry->parameter[i], value);
1828 /* mark config file token as well known from default config */
1829 setHashEntry(setup_file_hash, token, known_token_value);
1836 static void add_dynamic_file_list_entry(struct FileInfo **list,
1837 int *num_list_entries,
1838 SetupFileHash *extra_file_hash,
1839 struct ConfigInfo *suffix_list,
1840 int num_suffix_list_entries,
1843 struct FileInfo *new_list_entry;
1844 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1847 if (IS_PARENT_PROCESS())
1848 printf("===> found dynamic definition '%s'\n", token);
1851 (*num_list_entries)++;
1852 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
1853 new_list_entry = &(*list)[*num_list_entries - 1];
1855 new_list_entry->token = getStringCopy(token);
1856 new_list_entry->filename = NULL;
1857 new_list_entry->parameter = checked_calloc(parameter_array_size);
1859 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
1862 static void add_property_mapping(struct PropertyMapping **list,
1863 int *num_list_entries,
1864 int base_index, int ext1_index,
1865 int ext2_index, int ext3_index,
1868 struct PropertyMapping *new_list_entry;
1870 (*num_list_entries)++;
1871 *list = checked_realloc(*list,
1872 *num_list_entries * sizeof(struct PropertyMapping));
1873 new_list_entry = &(*list)[*num_list_entries - 1];
1875 new_list_entry->base_index = base_index;
1876 new_list_entry->ext1_index = ext1_index;
1877 new_list_entry->ext2_index = ext2_index;
1878 new_list_entry->ext3_index = ext3_index;
1880 new_list_entry->artwork_index = artwork_index;
1883 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
1886 struct FileInfo *file_list = artwork_info->file_list;
1887 struct ConfigInfo *suffix_list = artwork_info->suffix_list;
1888 char **base_prefixes = artwork_info->base_prefixes;
1889 char **ext1_suffixes = artwork_info->ext1_suffixes;
1890 char **ext2_suffixes = artwork_info->ext2_suffixes;
1891 char **ext3_suffixes = artwork_info->ext3_suffixes;
1892 char **ignore_tokens = artwork_info->ignore_tokens;
1893 int num_file_list_entries = artwork_info->num_file_list_entries;
1894 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
1895 int num_base_prefixes = artwork_info->num_base_prefixes;
1896 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
1897 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
1898 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
1899 int num_ignore_tokens = artwork_info->num_ignore_tokens;
1900 SetupFileHash *setup_file_hash, *extra_file_hash;
1901 char *known_token_value = KNOWN_TOKEN_VALUE;
1904 if (filename == NULL)
1908 printf("::: LoadArtworkConfigFromFilename: '%s'\n", filename);
1911 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
1914 /* read parameters for all known config file tokens */
1915 for (i=0; i<num_file_list_entries; i++)
1916 read_token_parameters(setup_file_hash, suffix_list, &file_list[i]);
1918 /* set all tokens that can be ignored here to "known" keyword */
1919 for (i=0; i < num_ignore_tokens; i++)
1920 setHashEntry(setup_file_hash, ignore_tokens[i], known_token_value);
1922 /* copy all unknown config file tokens to extra config list */
1923 extra_file_hash = newSetupFileHash();
1924 BEGIN_HASH_ITERATION(setup_file_hash, itr)
1926 if (strcmp(HASH_ITERATION_VALUE(itr), known_token_value) != 0)
1927 setHashEntry(extra_file_hash,
1928 HASH_ITERATION_TOKEN(itr), HASH_ITERATION_VALUE(itr));
1930 END_HASH_ITERATION(setup_file_hash, itr)
1932 /* at this point, we do not need the config file hash anymore -- free it */
1933 freeSetupFileHash(setup_file_hash);
1935 /* now try to determine valid, dynamically defined config tokens */
1937 BEGIN_HASH_ITERATION(extra_file_hash, itr)
1939 struct FileInfo **dynamic_file_list =
1940 &artwork_info->dynamic_file_list;
1941 int *num_dynamic_file_list_entries =
1942 &artwork_info->num_dynamic_file_list_entries;
1943 struct PropertyMapping **property_mapping =
1944 &artwork_info->property_mapping;
1945 int *num_property_mapping_entries =
1946 &artwork_info->num_property_mapping_entries;
1947 int current_summarized_file_list_entry =
1948 artwork_info->num_file_list_entries +
1949 artwork_info->num_dynamic_file_list_entries;
1950 char *token = HASH_ITERATION_TOKEN(itr);
1951 int len_token = strlen(token);
1953 boolean base_prefix_found = FALSE;
1954 boolean parameter_suffix_found = FALSE;
1956 /* skip all parameter definitions (handled by read_token_parameters()) */
1957 for (i=0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
1959 int len_suffix = strlen(suffix_list[i].token);
1961 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
1962 parameter_suffix_found = TRUE;
1966 if (IS_PARENT_PROCESS())
1968 if (parameter_suffix_found)
1969 printf("---> skipping token '%s' (parameter token)\n", token);
1971 printf("---> examining token '%s': search prefix ...\n", token);
1975 if (parameter_suffix_found)
1978 /* ---------- step 0: search for matching base prefix ---------- */
1981 for (i=0; i<num_base_prefixes && !base_prefix_found; i++)
1983 char *base_prefix = base_prefixes[i];
1984 int len_base_prefix = strlen(base_prefix);
1985 boolean ext1_suffix_found = FALSE;
1986 boolean ext2_suffix_found = FALSE;
1987 boolean ext3_suffix_found = FALSE;
1988 boolean exact_match = FALSE;
1989 int base_index = -1;
1990 int ext1_index = -1;
1991 int ext2_index = -1;
1992 int ext3_index = -1;
1994 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
1996 if (!base_prefix_found)
2001 if (start_pos + len_base_prefix == len_token) /* exact match */
2005 add_dynamic_file_list_entry(dynamic_file_list,
2006 num_dynamic_file_list_entries,
2009 num_suffix_list_entries,
2011 add_property_mapping(property_mapping,
2012 num_property_mapping_entries,
2013 base_index, -1, -1, -1,
2014 current_summarized_file_list_entry);
2019 if (IS_PARENT_PROCESS())
2020 printf("---> examining token '%s': search 1st suffix ...\n", token);
2023 /* ---------- step 1: search for matching first suffix ---------- */
2025 start_pos += len_base_prefix;
2026 for (j=0; j<num_ext1_suffixes && !ext1_suffix_found; j++)
2028 char *ext1_suffix = ext1_suffixes[j];
2029 int len_ext1_suffix = strlen(ext1_suffix);
2031 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2033 if (!ext1_suffix_found)
2038 if (start_pos + len_ext1_suffix == len_token) /* exact match */
2042 add_dynamic_file_list_entry(dynamic_file_list,
2043 num_dynamic_file_list_entries,
2046 num_suffix_list_entries,
2048 add_property_mapping(property_mapping,
2049 num_property_mapping_entries,
2050 base_index, ext1_index, -1, -1,
2051 current_summarized_file_list_entry);
2055 start_pos += len_ext1_suffix;
2062 if (IS_PARENT_PROCESS())
2063 printf("---> examining token '%s': search 2nd suffix ...\n", token);
2066 /* ---------- step 2: search for matching second suffix ---------- */
2068 for (k=0; k<num_ext2_suffixes && !ext2_suffix_found; k++)
2070 char *ext2_suffix = ext2_suffixes[k];
2071 int len_ext2_suffix = strlen(ext2_suffix);
2073 ext2_suffix_found = token_suffix_match(token, ext2_suffix,start_pos);
2075 if (!ext2_suffix_found)
2080 if (start_pos + len_ext2_suffix == len_token) /* exact match */
2084 add_dynamic_file_list_entry(dynamic_file_list,
2085 num_dynamic_file_list_entries,
2088 num_suffix_list_entries,
2090 add_property_mapping(property_mapping,
2091 num_property_mapping_entries,
2092 base_index, ext1_index, ext2_index, -1,
2093 current_summarized_file_list_entry);
2097 start_pos += len_ext2_suffix;
2104 if (IS_PARENT_PROCESS())
2105 printf("---> examining token '%s': search 3rd suffix ...\n",token);
2108 /* ---------- step 3: search for matching third suffix ---------- */
2110 for (l=0; l<num_ext3_suffixes && !ext3_suffix_found; l++)
2112 char *ext3_suffix = ext3_suffixes[l];
2113 int len_ext3_suffix = strlen(ext3_suffix);
2115 ext3_suffix_found =token_suffix_match(token,ext3_suffix,start_pos);
2117 if (!ext3_suffix_found)
2122 if (start_pos + len_ext3_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, ext2_index, ext3_index,
2135 current_summarized_file_list_entry);
2141 END_HASH_ITERATION(extra_file_hash, itr)
2143 if (artwork_info->num_dynamic_file_list_entries > 0)
2145 artwork_info->dynamic_artwork_list =
2146 checked_calloc(artwork_info->num_dynamic_file_list_entries *
2147 artwork_info->sizeof_artwork_list_entry);
2150 if (extra_file_hash != NULL && options.verbose && IS_PARENT_PROCESS())
2152 SetupFileList *setup_file_list, *list;
2153 boolean dynamic_tokens_found = FALSE;
2154 boolean unknown_tokens_found = FALSE;
2156 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
2157 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
2159 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2161 if (strcmp(HASH_ITERATION_VALUE(itr), known_token_value) == 0)
2162 dynamic_tokens_found = TRUE;
2164 unknown_tokens_found = TRUE;
2166 END_HASH_ITERATION(extra_file_hash, itr)
2169 if (dynamic_tokens_found)
2171 Error(ERR_RETURN_LINE, "-");
2172 Error(ERR_RETURN, "dynamic token(s) found in config file:");
2173 Error(ERR_RETURN, "- config file: '%s'", filename);
2175 for (list = setup_file_list; list != NULL; list = list->next)
2177 char *value = getHashEntry(extra_file_hash, list->token);
2179 if (value != NULL && strcmp(value, known_token_value) == 0)
2180 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2183 Error(ERR_RETURN_LINE, "-");
2187 if (unknown_tokens_found)
2189 Error(ERR_RETURN_LINE, "-");
2190 Error(ERR_RETURN, "warning: unknown token(s) found in config file:");
2191 Error(ERR_RETURN, "- config file: '%s'", filename);
2193 for (list = setup_file_list; list != NULL; list = list->next)
2195 char *value = getHashEntry(extra_file_hash, list->token);
2197 if (value != NULL && strcmp(value, known_token_value) != 0)
2198 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2201 Error(ERR_RETURN_LINE, "-");
2204 freeSetupFileList(setup_file_list);
2207 freeSetupFileHash(extra_file_hash);
2210 for (i=0; i<num_file_list_entries; i++)
2212 printf("'%s' ", file_list[i].token);
2213 if (file_list[i].filename)
2214 printf("-> '%s'\n", file_list[i].filename);
2216 printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
2221 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
2223 struct FileInfo *file_list = artwork_info->file_list;
2224 int num_file_list_entries = artwork_info->num_file_list_entries;
2225 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2226 char *filename_base = UNDEFINED_FILENAME, *filename_local;
2230 printf("GOT CUSTOM ARTWORK CONFIG FILE '%s'\n", filename);
2233 /* always start with reliable default values */
2234 for (i=0; i<num_file_list_entries; i++)
2236 setString(&file_list[i].filename, file_list[i].default_filename);
2238 for (j=0; j<num_suffix_list_entries; j++)
2239 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
2241 file_list[i].redefined = FALSE;
2244 /* free previous dynamic artwork file array */
2245 if (artwork_info->dynamic_file_list != NULL)
2247 for (i=0; i<artwork_info->num_dynamic_file_list_entries; i++)
2249 free(artwork_info->dynamic_file_list[i].token);
2250 free(artwork_info->dynamic_file_list[i].filename);
2251 free(artwork_info->dynamic_file_list[i].parameter);
2254 free(artwork_info->dynamic_file_list);
2255 artwork_info->dynamic_file_list = NULL;
2257 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2258 &artwork_info->num_dynamic_file_list_entries);
2261 /* free previous property mapping */
2262 if (artwork_info->property_mapping != NULL)
2264 free(artwork_info->property_mapping);
2266 artwork_info->property_mapping = NULL;
2267 artwork_info->num_property_mapping_entries = 0;
2270 if (!SETUP_OVERRIDE_ARTWORK(setup, artwork_info->type))
2272 /* first look for special artwork configured in level series config */
2273 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
2275 if (fileExists(filename_base))
2276 LoadArtworkConfigFromFilename(artwork_info, filename_base);
2279 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
2281 if (filename_local != NULL && strcmp(filename_base, filename_local) != 0)
2282 LoadArtworkConfigFromFilename(artwork_info, filename_local);
2285 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
2286 struct ListNodeInfo **listnode)
2290 char *filename = (*listnode)->source_filename;
2293 printf("[decrementing reference counter of artwork '%s']\n", filename);
2296 if (--(*listnode)->num_references <= 0)
2299 printf("[deleting artwork '%s']\n", filename);
2302 deleteNodeFromList(&artwork_info->content_list, filename,
2303 artwork_info->free_artwork);
2310 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
2311 struct ListNodeInfo **listnode,
2316 "Loading graphics:",
2322 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
2324 if (filename == NULL)
2326 int error_mode = ERR_WARN;
2329 /* we can get away without sounds and music, but not without graphics */
2330 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2331 error_mode = ERR_EXIT;
2334 Error(error_mode, "cannot find artwork file '%s'", basename);
2338 /* check if the old and the new artwork file are the same */
2339 if (*listnode && strcmp((*listnode)->source_filename, filename) == 0)
2341 /* The old and new artwork are the same (have the same filename and path).
2342 This usually means that this artwork does not exist in this artwork set
2343 and a fallback to the existing artwork is done. */
2346 printf("[artwork '%s' already exists (same list entry)]\n", filename);
2352 /* delete existing artwork file entry */
2353 deleteArtworkListEntry(artwork_info, listnode);
2355 /* check if the new artwork file already exists in the list of artworks */
2356 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
2359 printf("[artwork '%s' already exists (other list entry)]\n", filename);
2362 *listnode = (struct ListNodeInfo *)node->content;
2363 (*listnode)->num_references++;
2369 printf("::: %s: '%s'\n", init_text[artwork_info->type], basename);
2372 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
2373 DrawInitText(basename, 150, FC_YELLOW);
2375 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
2378 printf("[adding new artwork '%s']\n", filename);
2381 (*listnode)->num_references = 1;
2382 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
2387 int error_mode = ERR_WARN;
2390 /* we can get away without sounds and music, but not without graphics */
2391 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2392 error_mode = ERR_EXIT;
2395 Error(error_mode, "cannot load artwork file '%s'", basename);
2400 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
2401 struct ListNodeInfo **listnode,
2405 printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
2408 if (strcmp(basename, UNDEFINED_FILENAME) == 0)
2410 deleteArtworkListEntry(artwork_info, listnode);
2414 replaceArtworkListEntry(artwork_info, listnode, basename);
2417 static void LoadArtworkToList(struct ArtworkListInfo *artwork_info,
2418 struct ListNodeInfo **listnode,
2419 char *basename, int list_pos)
2422 if (artwork_info->artwork_list == NULL ||
2423 list_pos >= artwork_info->num_file_list_entries)
2428 printf("loading artwork '%s' ... [%d]\n",
2429 basename, getNumNodes(artwork_info->content_list));
2433 LoadCustomArtwork(artwork_info, listnode, basename);
2435 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[list_pos],
2440 printf("loading artwork '%s' done [%d]\n",
2441 basename, getNumNodes(artwork_info->content_list));
2445 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
2447 struct FileInfo *file_list = artwork_info->file_list;
2448 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
2449 int num_file_list_entries = artwork_info->num_file_list_entries;
2450 int num_dynamic_file_list_entries =
2451 artwork_info->num_dynamic_file_list_entries;
2455 printf("DEBUG: reloading %d static artwork files ...\n",
2456 num_file_list_entries);
2459 for(i=0; i<num_file_list_entries; i++)
2462 if (strcmp(file_list[i].token, "background") == 0)
2463 printf("::: '%s' -> '%s'\n", file_list[i].token, file_list[i].filename);
2466 LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2467 file_list[i].filename, i);
2470 if (artwork_info->artwork_list[i] == NULL &&
2471 strcmp(file_list[i].default_filename, file_list[i].filename) != 0)
2473 Error(ERR_WARN, "trying default artwork file '%s'",
2474 file_list[i].default_filename);
2476 LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2477 file_list[i].default_filename, i);
2483 printf("DEBUG: reloading %d dynamic artwork files ...\n",
2484 num_dynamic_file_list_entries);
2487 for(i=0; i<num_dynamic_file_list_entries; i++)
2488 LoadArtworkToList(artwork_info, &artwork_info->dynamic_artwork_list[i],
2489 dynamic_file_list[i].filename, i);
2492 dumpList(artwork_info->content_list);
2496 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
2497 struct ListNodeInfo ***list,
2498 int *num_list_entries)
2505 for(i=0; i<*num_list_entries; i++)
2506 deleteArtworkListEntry(artwork_info, &(*list)[i]);
2510 *num_list_entries = 0;
2513 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
2515 if (artwork_info == NULL)
2519 printf("%s: FREEING ARTWORK ...\n",
2520 IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2523 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
2524 &artwork_info->num_file_list_entries);
2526 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2527 &artwork_info->num_dynamic_file_list_entries);
2530 printf("%s: FREEING ARTWORK -- DONE\n",
2531 IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2536 /* ------------------------------------------------------------------------- */
2537 /* functions only needed for non-Unix (non-command-line) systems */
2538 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
2539 /* ------------------------------------------------------------------------- */
2541 #if defined(PLATFORM_MSDOS)
2543 #define ERROR_FILENAME "stderr.txt"
2545 void initErrorFile()
2547 unlink(ERROR_FILENAME);
2550 FILE *openErrorFile()
2552 return fopen(ERROR_FILENAME, MODE_APPEND);
2555 void dumpErrorFile()
2557 FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
2559 if (error_file != NULL)
2561 while (!feof(error_file))
2562 fputc(fgetc(error_file), stderr);
2570 /* ------------------------------------------------------------------------- */
2571 /* the following is only for debugging purpose and normally not used */
2572 /* ------------------------------------------------------------------------- */
2574 #define DEBUG_NUM_TIMESTAMPS 3
2576 void debug_print_timestamp(int counter_nr, char *message)
2578 static long counter[DEBUG_NUM_TIMESTAMPS][2];
2580 if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
2581 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
2583 counter[counter_nr][0] = Counter();
2586 printf("%s %.2f seconds\n", message,
2587 (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
2589 counter[counter_nr][1] = Counter();
2592 void debug_print_parent_only(char *format, ...)
2594 if (!IS_PARENT_PROCESS())
2601 va_start(ap, format);
2602 vprintf(format, ap);