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 /* ------------------------------------------------------------------------- */
41 /* platform independent wrappers for printf() et al. (newline aware) */
42 /* ------------------------------------------------------------------------- */
44 static void vfprintf_newline(FILE *stream, char *format, va_list ap)
46 char *newline = STRING_NEWLINE;
48 vfprintf(stream, format, ap);
50 fprintf(stream, "%s", newline);
53 static void vprintf_error_ext(char *format, va_list ap, boolean print_newline)
55 FILE *error_file = openErrorFile(); /* this returns at least 'stderr' */
58 vfprintf_newline(error_file, format, ap);
60 vfprintf(error_file, format, ap);
62 if (error_file != stderr) /* do not close stream 'stderr' */
66 static void vprintf_error(char *format, va_list ap)
68 vprintf_error_ext(format, ap, FALSE);
71 static void vprintf_error_newline(char *format, va_list ap)
73 vprintf_error_ext(format, ap, TRUE);
76 static void printf_error(char *format, ...)
83 vprintf_error(format, ap);
88 static void printf_error_newline(char *format, ...)
95 vprintf_error_newline(format, ap);
100 static void fprintf_newline(FILE *stream, char *format, ...)
106 va_start(ap, format);
107 vfprintf_newline(stream, format, ap);
112 static char *get_line_string(char *line_chars, int line_length)
114 static char *buffer = NULL;
115 int line_chars_length = strlen(line_chars);
119 checked_free(buffer);
121 buffer = checked_malloc(line_chars_length * line_length + 1);
123 for (i = 0; i < line_length; i++)
124 strcpy(&buffer[i * line_chars_length], line_chars);
129 void fprintf_line(FILE *stream, char *line_chars, int line_length)
131 fprintf_newline(stream, get_line_string(line_chars, line_length));
134 void printf_line(char *line_chars, int line_length)
136 fprintf_line(stdout, line_chars, line_length);
139 void printf_line_error(char *line_chars, int line_length)
141 printf_error_newline(get_line_string(line_chars, line_length));
144 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
146 fprintf(stdout, "%s", prefix);
147 fprintf_line(stdout, line_chars, line_length);
151 /* ------------------------------------------------------------------------- */
152 /* string functions */
153 /* ------------------------------------------------------------------------- */
155 /* int2str() returns a number converted to a string;
156 the used memory is static, but will be overwritten by later calls,
157 so if you want to save the result, copy it to a private string buffer;
158 there can be 10 local calls of int2str() without buffering the result --
159 the 11th call will then destroy the result from the first call and so on.
162 char *int2str(int number, int size)
164 static char shift_array[10][40];
165 static int shift_counter = 0;
166 char *s = shift_array[shift_counter];
168 shift_counter = (shift_counter + 1) % 10;
175 sprintf(s, " %09d", number);
176 return &s[strlen(s) - size];
180 sprintf(s, "%d", number);
186 /* something similar to "int2str()" above, but allocates its own memory
187 and has a different interface; we cannot use "itoa()", because this
188 seems to be already defined when cross-compiling to the win32 target */
190 char *i_to_a(unsigned int i)
192 static char *a = NULL;
196 if (i > 2147483647) /* yes, this is a kludge */
199 a = checked_malloc(10 + 1);
207 /* calculate base-2 logarithm of argument (rounded down to integer;
208 this function returns the number of the highest bit set in argument) */
210 int log_2(unsigned int x)
216 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
224 /* ------------------------------------------------------------------------- */
225 /* counter functions */
226 /* ------------------------------------------------------------------------- */
228 #if defined(PLATFORM_MSDOS)
229 volatile unsigned long counter = 0;
231 void increment_counter()
236 END_OF_FUNCTION(increment_counter);
240 /* maximal allowed length of a command line option */
241 #define MAX_OPTION_LEN 256
244 static unsigned long mainCounter(int mode)
246 static unsigned long base_ms = 0;
247 unsigned long current_ms;
248 unsigned long counter_ms;
250 current_ms = SDL_GetTicks();
252 /* reset base time in case of counter initializing or wrap-around */
253 if (mode == INIT_COUNTER || current_ms < base_ms)
254 base_ms = current_ms;
256 counter_ms = current_ms - base_ms;
258 return counter_ms; /* return milliseconds since last init */
261 #else /* !TARGET_SDL */
263 #if defined(PLATFORM_UNIX)
264 static unsigned long mainCounter(int mode)
266 static struct timeval base_time = { 0, 0 };
267 struct timeval current_time;
268 unsigned long counter_ms;
270 gettimeofday(¤t_time, NULL);
272 /* reset base time in case of counter initializing or wrap-around */
273 if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
274 base_time = current_time;
276 counter_ms = (current_time.tv_sec - base_time.tv_sec) * 1000
277 + (current_time.tv_usec - base_time.tv_usec) / 1000;
279 return counter_ms; /* return milliseconds since last init */
281 #endif /* PLATFORM_UNIX */
282 #endif /* !TARGET_SDL */
284 void InitCounter() /* set counter back to zero */
286 #if !defined(PLATFORM_MSDOS)
287 mainCounter(INIT_COUNTER);
289 LOCK_VARIABLE(counter);
290 LOCK_FUNCTION(increment_counter);
291 install_int_ex(increment_counter, BPS_TO_TIMER(100));
295 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
297 #if !defined(PLATFORM_MSDOS)
298 return mainCounter(READ_COUNTER);
300 return (counter * 10);
304 static void sleep_milliseconds(unsigned long milliseconds_delay)
306 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
310 /* we want to wait only a few ms -- if we assume that we have a
311 kernel timer resolution of 10 ms, we would wait far to long;
312 therefore it's better to do a short interval of busy waiting
313 to get our sleeping time more accurate */
315 unsigned long base_counter = Counter(), actual_counter = Counter();
317 while (actual_counter < base_counter + milliseconds_delay &&
318 actual_counter >= base_counter)
319 actual_counter = Counter();
323 #if defined(TARGET_SDL)
324 SDL_Delay(milliseconds_delay);
325 #elif defined(TARGET_ALLEGRO)
326 rest(milliseconds_delay);
328 struct timeval delay;
330 delay.tv_sec = milliseconds_delay / 1000;
331 delay.tv_usec = 1000 * (milliseconds_delay % 1000);
333 if (select(0, NULL, NULL, NULL, &delay) != 0)
334 Error(ERR_WARN, "sleep_milliseconds(): select() failed");
339 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
341 sleep_milliseconds(delay);
344 boolean FrameReached(unsigned long *frame_counter_var,
345 unsigned long frame_delay)
347 unsigned long actual_frame_counter = FrameCounter;
349 if (actual_frame_counter >= *frame_counter_var &&
350 actual_frame_counter < *frame_counter_var + frame_delay)
353 *frame_counter_var = actual_frame_counter;
358 boolean DelayReached(unsigned long *counter_var,
361 unsigned long actual_counter = Counter();
363 if (actual_counter >= *counter_var &&
364 actual_counter < *counter_var + delay)
367 *counter_var = actual_counter;
372 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
374 unsigned long actual_counter;
378 actual_counter = Counter();
380 if (actual_counter >= *counter_var &&
381 actual_counter < *counter_var + delay)
382 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
387 *counter_var = actual_counter;
391 /* ------------------------------------------------------------------------- */
392 /* random generator functions */
393 /* ------------------------------------------------------------------------- */
395 unsigned int init_random_number(int nr, long seed)
397 if (seed == NEW_RANDOMIZE)
399 #if defined(TARGET_SDL)
400 seed = (long)SDL_GetTicks();
402 struct timeval current_time;
404 gettimeofday(¤t_time, NULL);
405 seed = (long)current_time.tv_usec;
409 srandom_linux_libc(nr, (unsigned int) seed);
411 return (unsigned int) seed;
414 unsigned int get_random_number(int nr, int max)
416 return (max > 0 ? random_linux_libc(nr) % max : 0);
420 /* ------------------------------------------------------------------------- */
421 /* system info functions */
422 /* ------------------------------------------------------------------------- */
424 #if !defined(PLATFORM_MSDOS)
425 static char *get_corrected_real_name(char *real_name)
427 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
428 char *from_ptr = real_name;
429 char *to_ptr = real_name_new;
431 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
432 while (*from_ptr && (long)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
434 /* the name field read from "passwd" file may also contain additional
435 user information, separated by commas, which will be removed here */
436 if (*from_ptr == ',')
439 /* the user's real name may contain 'ß' characters (german sharp s),
440 which have no equivalent in upper case letters (used by our fonts) */
441 if (*from_ptr == 'ß')
448 *to_ptr++ = *from_ptr++;
453 return real_name_new;
459 static char *login_name = NULL;
461 #if defined(PLATFORM_WIN32)
462 if (login_name == NULL)
464 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
465 login_name = checked_malloc(buffer_size);
467 if (GetUserName(login_name, &buffer_size) == 0)
468 strcpy(login_name, ANONYMOUS_NAME);
471 if (login_name == NULL)
475 if ((pwd = getpwuid(getuid())) == NULL)
476 login_name = ANONYMOUS_NAME;
478 login_name = getStringCopy(pwd->pw_name);
487 static char *real_name = NULL;
489 #if defined(PLATFORM_WIN32)
490 if (real_name == NULL)
492 static char buffer[MAX_USERNAME_LEN + 1];
493 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
495 if (GetUserName(buffer, &buffer_size) != 0)
496 real_name = get_corrected_real_name(buffer);
498 real_name = ANONYMOUS_NAME;
500 #elif defined(PLATFORM_UNIX)
501 if (real_name == NULL)
505 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
506 real_name = get_corrected_real_name(pwd->pw_gecos);
508 real_name = ANONYMOUS_NAME;
511 real_name = ANONYMOUS_NAME;
519 static char *dir = NULL;
521 #if defined(PLATFORM_WIN32)
524 dir = checked_malloc(MAX_PATH + 1);
526 if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, dir)))
529 #elif defined(PLATFORM_UNIX)
532 if ((dir = getenv("HOME")) == NULL)
536 if ((pwd = getpwuid(getuid())) != NULL)
537 dir = getStringCopy(pwd->pw_dir);
550 /* ------------------------------------------------------------------------- */
551 /* path manipulation functions */
552 /* ------------------------------------------------------------------------- */
554 static char *getLastPathSeparatorPtr(char *filename)
556 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
558 if (last_separator == NULL) /* also try DOS/Windows variant */
559 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
561 return last_separator;
564 char *getBaseNamePtr(char *filename)
566 char *last_separator = getLastPathSeparatorPtr(filename);
568 if (last_separator != NULL)
569 return last_separator + 1; /* separator found: strip base path */
571 return filename; /* no separator found: filename has no path */
574 char *getBaseName(char *filename)
576 return getStringCopy(getBaseNamePtr(filename));
579 char *getBasePath(char *filename)
581 char *basepath = getStringCopy(filename);
582 char *last_separator = getLastPathSeparatorPtr(basepath);
584 if (last_separator != NULL)
585 *last_separator = '\0'; /* separator found: strip basename */
587 basepath = "."; /* no separator found: use current path */
593 /* ------------------------------------------------------------------------- */
594 /* various string functions */
595 /* ------------------------------------------------------------------------- */
597 char *getPath2(char *path1, char *path2)
599 char *sep = STRING_PATH_SEPARATOR;
600 char *complete_path = checked_malloc(strlen(path1) + 1 +
603 sprintf(complete_path, "%s%s%s", path1, sep, path2);
605 return complete_path;
608 char *getPath3(char *path1, char *path2, char *path3)
610 char *sep = STRING_PATH_SEPARATOR;
611 char *complete_path = checked_malloc(strlen(path1) + 1 +
615 sprintf(complete_path, "%s%s%s%s%s", path1, sep, path2, sep, path3);
617 return complete_path;
620 char *getStringCat2(char *s1, char *s2)
622 char *complete_string = checked_malloc(strlen(s1) + strlen(s2) + 1);
624 sprintf(complete_string, "%s%s", s1, s2);
626 return complete_string;
629 char *getStringCopy(char *s)
636 s_copy = checked_malloc(strlen(s) + 1);
642 char *getStringToLower(char *s)
644 char *s_copy = checked_malloc(strlen(s) + 1);
645 char *s_ptr = s_copy;
648 *s_ptr++ = tolower(*s++);
654 void setString(char **old_value, char *new_value)
656 checked_free(*old_value);
658 *old_value = getStringCopy(new_value);
661 boolean strEqual(char *s1, char *s2)
663 return (s1 == NULL && s2 == NULL ? TRUE :
664 s1 == NULL && s2 != NULL ? FALSE :
665 s1 != NULL && s2 == NULL ? FALSE :
666 strcmp(s1, s2) == 0);
670 /* ------------------------------------------------------------------------- */
671 /* command line option handling functions */
672 /* ------------------------------------------------------------------------- */
674 void GetOptions(char *argv[], void (*print_usage_function)(void))
676 char *ro_base_path = RO_BASE_PATH;
677 char *rw_base_path = RW_BASE_PATH;
678 char **options_left = &argv[1];
680 #if !defined(PLATFORM_MACOSX)
681 /* if the program is configured to start from current directory (default),
682 determine program package directory (KDE/Konqueror does not do this by
683 itself and fails otherwise); on Mac OS X, the program binary is stored
684 in an application package directory -- do not try to use this directory
685 as the program data directory (Mac OS X handles this correctly anyway) */
687 if (strEqual(ro_base_path, "."))
688 ro_base_path = program.command_basepath;
689 if (strEqual(rw_base_path, "."))
690 rw_base_path = program.command_basepath;
693 /* initialize global program options */
694 options.display_name = NULL;
695 options.server_host = NULL;
696 options.server_port = 0;
697 options.ro_base_directory = ro_base_path;
698 options.rw_base_directory = rw_base_path;
699 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
700 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
701 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
702 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
703 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
704 options.execute_command = NULL;
705 options.serveronly = FALSE;
706 options.network = FALSE;
707 options.verbose = FALSE;
708 options.debug = FALSE;
710 #if !defined(PLATFORM_UNIX)
711 if (*options_left == NULL) /* no options given -- enable verbose mode */
712 options.verbose = TRUE;
715 while (*options_left)
717 char option_str[MAX_OPTION_LEN];
718 char *option = options_left[0];
719 char *next_option = options_left[1];
720 char *option_arg = NULL;
721 int option_len = strlen(option);
723 if (option_len >= MAX_OPTION_LEN)
724 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
726 strcpy(option_str, option); /* copy argument into buffer */
729 if (strEqual(option, "--")) /* stop scanning arguments */
732 if (strncmp(option, "--", 2) == 0) /* treat '--' like '-' */
735 option_arg = strchr(option, '=');
736 if (option_arg == NULL) /* no '=' in option */
737 option_arg = next_option;
740 *option_arg++ = '\0'; /* cut argument from option */
741 if (*option_arg == '\0') /* no argument after '=' */
742 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
745 option_len = strlen(option);
747 if (strEqual(option, "-"))
748 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
749 else if (strncmp(option, "-help", option_len) == 0)
751 print_usage_function();
755 else if (strncmp(option, "-display", option_len) == 0)
757 if (option_arg == NULL)
758 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
760 options.display_name = option_arg;
761 if (option_arg == next_option)
764 else if (strncmp(option, "-basepath", option_len) == 0)
766 if (option_arg == NULL)
767 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
769 /* this should be extended to separate options for ro and rw data */
770 options.ro_base_directory = ro_base_path = option_arg;
771 options.rw_base_directory = rw_base_path = option_arg;
772 if (option_arg == next_option)
775 /* adjust paths for sub-directories in base directory accordingly */
776 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
777 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
778 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
779 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
780 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
782 else if (strncmp(option, "-levels", option_len) == 0)
784 if (option_arg == NULL)
785 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
787 options.level_directory = option_arg;
788 if (option_arg == next_option)
791 else if (strncmp(option, "-graphics", option_len) == 0)
793 if (option_arg == NULL)
794 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
796 options.graphics_directory = option_arg;
797 if (option_arg == next_option)
800 else if (strncmp(option, "-sounds", option_len) == 0)
802 if (option_arg == NULL)
803 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
805 options.sounds_directory = option_arg;
806 if (option_arg == next_option)
809 else if (strncmp(option, "-music", option_len) == 0)
811 if (option_arg == NULL)
812 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
814 options.music_directory = option_arg;
815 if (option_arg == next_option)
818 else if (strncmp(option, "-network", option_len) == 0)
820 options.network = TRUE;
822 else if (strncmp(option, "-serveronly", option_len) == 0)
824 options.serveronly = TRUE;
826 else if (strncmp(option, "-verbose", option_len) == 0)
828 options.verbose = TRUE;
830 else if (strncmp(option, "-debug", option_len) == 0)
832 options.debug = TRUE;
834 else if (strncmp(option, "-execute", option_len) == 0)
836 if (option_arg == NULL)
837 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
839 options.execute_command = option_arg;
840 if (option_arg == next_option)
843 /* when doing batch processing, always enable verbose mode (warnings) */
844 options.verbose = TRUE;
846 else if (*option == '-')
848 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
850 else if (options.server_host == NULL)
852 options.server_host = *options_left;
854 else if (options.server_port == 0)
856 options.server_port = atoi(*options_left);
857 if (options.server_port < 1024)
858 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
861 Error(ERR_EXIT_HELP, "too many arguments");
868 /* ------------------------------------------------------------------------- */
869 /* error handling functions */
870 /* ------------------------------------------------------------------------- */
872 /* used by SetError() and GetError() to store internal error messages */
873 static char internal_error[1024]; /* this is bad */
875 void SetError(char *format, ...)
879 va_start(ap, format);
880 vsprintf(internal_error, format, ap);
886 return internal_error;
891 void Error(int mode, char *format, ...)
893 static boolean last_line_was_separator = FALSE;
894 char *process_name = "";
896 /* display warnings only when running in verbose mode */
897 if (mode & ERR_WARN && !options.verbose)
900 if (mode == ERR_RETURN_LINE)
902 if (!last_line_was_separator)
903 printf_line_error(format, 79);
905 last_line_was_separator = TRUE;
910 last_line_was_separator = FALSE;
912 if (mode & ERR_SOUND_SERVER)
913 process_name = " sound server";
914 else if (mode & ERR_NETWORK_SERVER)
915 process_name = " network server";
916 else if (mode & ERR_NETWORK_CLIENT)
917 process_name = " network client **";
923 printf_error("%s%s: ", program.command_basename, process_name);
926 printf_error("warning: ");
928 va_start(ap, format);
929 vprintf_error_newline(format, ap);
934 printf_error_newline("%s: Try option '--help' for more information.",
935 program.command_basename);
938 printf_error_newline("%s%s: aborting",
939 program.command_basename, process_name);
943 if (mode & ERR_FROM_SERVER)
944 exit(1); /* child process: normal exit */
946 program.exit_function(1); /* main process: clean up stuff */
952 void Error(int mode, char *format, ...)
954 static boolean last_line_was_separator = FALSE;
955 char *process_name = "";
956 FILE *error = stderr;
957 char *newline = "\n";
959 /* display warnings only when running in verbose mode */
960 if (mode & ERR_WARN && !options.verbose)
963 if (mode == ERR_RETURN_LINE)
965 if (!last_line_was_separator)
966 fprintf_line(error, format, 79);
968 last_line_was_separator = TRUE;
973 last_line_was_separator = FALSE;
975 #if defined(PLATFORM_WIN32) || defined(PLATFORM_MSDOS)
978 if ((error = openErrorFile()) == NULL)
980 printf("Cannot write to error output file!%s", newline);
982 program.exit_function(1);
986 if (mode & ERR_SOUND_SERVER)
987 process_name = " sound server";
988 else if (mode & ERR_NETWORK_SERVER)
989 process_name = " network server";
990 else if (mode & ERR_NETWORK_CLIENT)
991 process_name = " network client **";
997 fprintf(error, "%s%s: ", program.command_basename, process_name);
1000 fprintf(error, "warning: ");
1002 va_start(ap, format);
1003 vfprintf(error, format, ap);
1006 fprintf(error, "%s", newline);
1009 if (mode & ERR_HELP)
1010 fprintf(error, "%s: Try option '--help' for more information.%s",
1011 program.command_basename, newline);
1013 if (mode & ERR_EXIT)
1014 fprintf(error, "%s%s: aborting%s",
1015 program.command_basename, process_name, newline);
1017 if (error != stderr)
1020 if (mode & ERR_EXIT)
1022 if (mode & ERR_FROM_SERVER)
1023 exit(1); /* child process: normal exit */
1025 program.exit_function(1); /* main process: clean up stuff */
1032 /* ------------------------------------------------------------------------- */
1033 /* checked memory allocation and freeing functions */
1034 /* ------------------------------------------------------------------------- */
1036 void *checked_malloc(unsigned long size)
1043 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1048 void *checked_calloc(unsigned long size)
1052 ptr = calloc(1, size);
1055 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1060 void *checked_realloc(void *ptr, unsigned long size)
1062 ptr = realloc(ptr, size);
1065 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1070 void checked_free(void *ptr)
1072 if (ptr != NULL) /* this check should be done by free() anyway */
1077 /* ------------------------------------------------------------------------- */
1078 /* various helper functions */
1079 /* ------------------------------------------------------------------------- */
1081 inline void swap_numbers(int *i1, int *i2)
1089 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1101 /* the "put" variants of the following file access functions check for the file
1102 pointer being != NULL and return the number of bytes they have or would have
1103 written; this allows for chunk writing functions to first determine the size
1104 of the (not yet written) chunk, write the correct chunk size and finally
1105 write the chunk itself */
1107 int getFile8BitInteger(FILE *file)
1112 int putFile8BitInteger(FILE *file, int value)
1120 int getFile16BitInteger(FILE *file, int byte_order)
1122 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1123 return ((fgetc(file) << 8) |
1124 (fgetc(file) << 0));
1125 else /* BYTE_ORDER_LITTLE_ENDIAN */
1126 return ((fgetc(file) << 0) |
1127 (fgetc(file) << 8));
1130 int putFile16BitInteger(FILE *file, int value, int byte_order)
1134 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1136 fputc((value >> 8) & 0xff, file);
1137 fputc((value >> 0) & 0xff, file);
1139 else /* BYTE_ORDER_LITTLE_ENDIAN */
1141 fputc((value >> 0) & 0xff, file);
1142 fputc((value >> 8) & 0xff, file);
1149 int getFile32BitInteger(FILE *file, int byte_order)
1151 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1152 return ((fgetc(file) << 24) |
1153 (fgetc(file) << 16) |
1154 (fgetc(file) << 8) |
1155 (fgetc(file) << 0));
1156 else /* BYTE_ORDER_LITTLE_ENDIAN */
1157 return ((fgetc(file) << 0) |
1158 (fgetc(file) << 8) |
1159 (fgetc(file) << 16) |
1160 (fgetc(file) << 24));
1163 int putFile32BitInteger(FILE *file, int value, int byte_order)
1167 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1169 fputc((value >> 24) & 0xff, file);
1170 fputc((value >> 16) & 0xff, file);
1171 fputc((value >> 8) & 0xff, file);
1172 fputc((value >> 0) & 0xff, file);
1174 else /* BYTE_ORDER_LITTLE_ENDIAN */
1176 fputc((value >> 0) & 0xff, file);
1177 fputc((value >> 8) & 0xff, file);
1178 fputc((value >> 16) & 0xff, file);
1179 fputc((value >> 24) & 0xff, file);
1186 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
1189 const int chunk_name_length = 4;
1191 /* read chunk name */
1192 fgets(chunk_name, chunk_name_length + 1, file);
1194 if (chunk_size != NULL)
1196 /* read chunk size */
1197 *chunk_size = getFile32BitInteger(file, byte_order);
1200 return (feof(file) || ferror(file) ? FALSE : TRUE);
1203 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1208 /* write chunk name */
1210 fputs(chunk_name, file);
1212 num_bytes += strlen(chunk_name);
1214 if (chunk_size >= 0)
1216 /* write chunk size */
1218 putFile32BitInteger(file, chunk_size, byte_order);
1226 int getFileVersion(FILE *file)
1228 int version_major = fgetc(file);
1229 int version_minor = fgetc(file);
1230 int version_patch = fgetc(file);
1231 int version_build = fgetc(file);
1233 return VERSION_IDENT(version_major, version_minor, version_patch,
1237 int putFileVersion(FILE *file, int version)
1241 int version_major = VERSION_MAJOR(version);
1242 int version_minor = VERSION_MINOR(version);
1243 int version_patch = VERSION_PATCH(version);
1244 int version_build = VERSION_BUILD(version);
1246 fputc(version_major, file);
1247 fputc(version_minor, file);
1248 fputc(version_patch, file);
1249 fputc(version_build, file);
1255 void ReadBytesFromFile(FILE *file, byte *buffer, unsigned long bytes)
1259 for(i = 0; i < bytes && !feof(file); i++)
1260 buffer[i] = fgetc(file);
1263 void WriteBytesToFile(FILE *file, byte *buffer, unsigned long bytes)
1267 for(i = 0; i < bytes; i++)
1268 fputc(buffer[i], file);
1271 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
1273 while (bytes-- && !feof(file))
1277 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
1284 /* ------------------------------------------------------------------------- */
1285 /* functions to translate key identifiers between different format */
1286 /* ------------------------------------------------------------------------- */
1288 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1289 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1290 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1291 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1293 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1302 /* normal cursor keys */
1303 { KSYM_Left, "XK_Left", "cursor left" },
1304 { KSYM_Right, "XK_Right", "cursor right" },
1305 { KSYM_Up, "XK_Up", "cursor up" },
1306 { KSYM_Down, "XK_Down", "cursor down" },
1308 /* keypad cursor keys */
1310 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1311 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1312 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1313 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1316 /* other keypad keys */
1317 #ifdef KSYM_KP_Enter
1318 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1319 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1320 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1321 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1322 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1323 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1327 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1328 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1329 { KSYM_Control_L, "XK_Control_L", "left control" },
1330 { KSYM_Control_R, "XK_Control_R", "right control" },
1331 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1332 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1333 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1334 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1335 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1336 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1337 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1338 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1340 /* some special keys */
1341 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1342 { KSYM_Delete, "XK_Delete", "delete" },
1343 { KSYM_Insert, "XK_Insert", "insert" },
1344 { KSYM_Tab, "XK_Tab", "tab" },
1345 { KSYM_Home, "XK_Home", "home" },
1346 { KSYM_End, "XK_End", "end" },
1347 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1348 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1349 { KSYM_Menu, "XK_Menu", "menu" }, /* Win-Menu */
1351 /* ASCII 0x20 to 0x40 keys (except numbers) */
1352 { KSYM_space, "XK_space", "space" },
1353 { KSYM_exclam, "XK_exclam", "!" },
1354 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1355 { KSYM_numbersign, "XK_numbersign", "#" },
1356 { KSYM_dollar, "XK_dollar", "$" },
1357 { KSYM_percent, "XK_percent", "%" },
1358 { KSYM_ampersand, "XK_ampersand", "&" },
1359 { KSYM_apostrophe, "XK_apostrophe", "'" },
1360 { KSYM_parenleft, "XK_parenleft", "(" },
1361 { KSYM_parenright, "XK_parenright", ")" },
1362 { KSYM_asterisk, "XK_asterisk", "*" },
1363 { KSYM_plus, "XK_plus", "+" },
1364 { KSYM_comma, "XK_comma", "," },
1365 { KSYM_minus, "XK_minus", "-" },
1366 { KSYM_period, "XK_period", "." },
1367 { KSYM_slash, "XK_slash", "/" },
1368 { KSYM_colon, "XK_colon", ":" },
1369 { KSYM_semicolon, "XK_semicolon", ";" },
1370 { KSYM_less, "XK_less", "<" },
1371 { KSYM_equal, "XK_equal", "=" },
1372 { KSYM_greater, "XK_greater", ">" },
1373 { KSYM_question, "XK_question", "?" },
1374 { KSYM_at, "XK_at", "@" },
1376 /* more ASCII keys */
1377 { KSYM_bracketleft, "XK_bracketleft", "[" },
1378 { KSYM_backslash, "XK_backslash", "\\" },
1379 { KSYM_bracketright,"XK_bracketright", "]" },
1380 { KSYM_asciicircum, "XK_asciicircum", "^" },
1381 { KSYM_underscore, "XK_underscore", "_" },
1382 { KSYM_grave, "XK_grave", "grave" },
1383 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1384 { KSYM_braceleft, "XK_braceleft", "brace left" },
1385 { KSYM_bar, "XK_bar", "bar" },
1386 { KSYM_braceright, "XK_braceright", "brace right" },
1387 { KSYM_asciitilde, "XK_asciitilde", "~" },
1389 /* special (non-ASCII) keys */
1390 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
1391 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
1392 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
1393 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
1394 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
1395 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
1396 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1398 /* end-of-array identifier */
1404 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1406 static char name_buffer[30];
1409 if (key >= KSYM_A && key <= KSYM_Z)
1410 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1411 else if (key >= KSYM_a && key <= KSYM_z)
1412 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1413 else if (key >= KSYM_0 && key <= KSYM_9)
1414 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1415 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1416 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1418 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1419 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1421 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1422 sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1424 else if (key == KSYM_UNDEFINED)
1425 strcpy(name_buffer, "(undefined)");
1432 if (key == translate_key[i].key)
1434 strcpy(name_buffer, translate_key[i].name);
1438 while (translate_key[++i].name);
1440 if (!translate_key[i].name)
1441 strcpy(name_buffer, "(unknown)");
1444 *name = name_buffer;
1446 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1448 static char name_buffer[30];
1451 if (key >= KSYM_A && key <= KSYM_Z)
1452 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1453 else if (key >= KSYM_a && key <= KSYM_z)
1454 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1455 else if (key >= KSYM_0 && key <= KSYM_9)
1456 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1457 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1458 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1459 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1460 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1461 else if (key == KSYM_UNDEFINED)
1462 strcpy(name_buffer, "[undefined]");
1469 if (key == translate_key[i].key)
1471 strcpy(name_buffer, translate_key[i].x11name);
1475 while (translate_key[++i].x11name);
1477 if (!translate_key[i].x11name)
1478 sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1481 *x11name = name_buffer;
1483 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1485 Key key = KSYM_UNDEFINED;
1490 if (strEqual(translate_key[i].name, *name))
1492 key = translate_key[i].key;
1496 while (translate_key[++i].x11name);
1498 if (key == KSYM_UNDEFINED)
1499 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1503 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1505 Key key = KSYM_UNDEFINED;
1506 char *name_ptr = *x11name;
1508 if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1510 char c = name_ptr[3];
1512 if (c >= 'A' && c <= 'Z')
1513 key = KSYM_A + (Key)(c - 'A');
1514 else if (c >= 'a' && c <= 'z')
1515 key = KSYM_a + (Key)(c - 'a');
1516 else if (c >= '0' && c <= '9')
1517 key = KSYM_0 + (Key)(c - '0');
1519 else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1521 char c = name_ptr[6];
1523 if (c >= '0' && c <= '9')
1524 key = KSYM_KP_0 + (Key)(c - '0');
1526 else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1528 char c1 = name_ptr[4];
1529 char c2 = name_ptr[5];
1532 if ((c1 >= '0' && c1 <= '9') &&
1533 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1534 d = atoi(&name_ptr[4]);
1536 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1537 key = KSYM_F1 + (Key)(d - 1);
1539 else if (strncmp(name_ptr, "XK_", 3) == 0)
1545 if (strEqual(name_ptr, translate_key[i].x11name))
1547 key = translate_key[i].key;
1551 while (translate_key[++i].x11name);
1553 else if (strncmp(name_ptr, "0x", 2) == 0)
1555 unsigned long value = 0;
1561 char c = *name_ptr++;
1564 if (c >= '0' && c <= '9')
1566 else if (c >= 'a' && c <= 'f')
1567 d = (int)(c - 'a' + 10);
1568 else if (c >= 'A' && c <= 'F')
1569 d = (int)(c - 'A' + 10);
1577 value = value * 16 + d;
1588 char *getKeyNameFromKey(Key key)
1592 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1596 char *getX11KeyNameFromKey(Key key)
1600 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1604 Key getKeyFromKeyName(char *name)
1608 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1612 Key getKeyFromX11KeyName(char *x11name)
1616 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1620 char getCharFromKey(Key key)
1622 char *keyname = getKeyNameFromKey(key);
1625 if (strlen(keyname) == 1)
1626 letter = keyname[0];
1627 else if (strEqual(keyname, "space"))
1629 else if (strEqual(keyname, "circumflex"))
1636 /* ------------------------------------------------------------------------- */
1637 /* functions to translate string identifiers to integer or boolean value */
1638 /* ------------------------------------------------------------------------- */
1640 int get_integer_from_string(char *s)
1642 static char *number_text[][3] =
1644 { "0", "zero", "null", },
1645 { "1", "one", "first" },
1646 { "2", "two", "second" },
1647 { "3", "three", "third" },
1648 { "4", "four", "fourth" },
1649 { "5", "five", "fifth" },
1650 { "6", "six", "sixth" },
1651 { "7", "seven", "seventh" },
1652 { "8", "eight", "eighth" },
1653 { "9", "nine", "ninth" },
1654 { "10", "ten", "tenth" },
1655 { "11", "eleven", "eleventh" },
1656 { "12", "twelve", "twelfth" },
1658 { NULL, NULL, NULL },
1662 char *s_lower = getStringToLower(s);
1665 for (i = 0; number_text[i][0] != NULL; i++)
1666 for (j = 0; j < 3; j++)
1667 if (strEqual(s_lower, number_text[i][j]))
1672 if (strEqual(s_lower, "false"))
1674 else if (strEqual(s_lower, "true"))
1685 boolean get_boolean_from_string(char *s)
1687 char *s_lower = getStringToLower(s);
1688 boolean result = FALSE;
1690 if (strEqual(s_lower, "true") ||
1691 strEqual(s_lower, "yes") ||
1692 strEqual(s_lower, "on") ||
1693 get_integer_from_string(s) == 1)
1702 /* ------------------------------------------------------------------------- */
1703 /* functions for generic lists */
1704 /* ------------------------------------------------------------------------- */
1706 ListNode *newListNode()
1708 return checked_calloc(sizeof(ListNode));
1711 void addNodeToList(ListNode **node_first, char *key, void *content)
1713 ListNode *node_new = newListNode();
1715 node_new->key = getStringCopy(key);
1716 node_new->content = content;
1717 node_new->next = *node_first;
1718 *node_first = node_new;
1721 void deleteNodeFromList(ListNode **node_first, char *key,
1722 void (*destructor_function)(void *))
1724 if (node_first == NULL || *node_first == NULL)
1727 if (strEqual((*node_first)->key, key))
1729 free((*node_first)->key);
1730 if (destructor_function)
1731 destructor_function((*node_first)->content);
1732 *node_first = (*node_first)->next;
1735 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1738 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1740 if (node_first == NULL)
1743 if (strEqual(node_first->key, key))
1746 return getNodeFromKey(node_first->next, key);
1749 int getNumNodes(ListNode *node_first)
1751 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1754 void dumpList(ListNode *node_first)
1756 ListNode *node = node_first;
1760 printf("['%s' (%d)]\n", node->key,
1761 ((struct ListNodeInfo *)node->content)->num_references);
1765 printf("[%d nodes]\n", getNumNodes(node_first));
1769 /* ------------------------------------------------------------------------- */
1770 /* functions for checking files and filenames */
1771 /* ------------------------------------------------------------------------- */
1773 boolean fileExists(char *filename)
1775 if (filename == NULL)
1778 return (access(filename, F_OK) == 0);
1781 boolean fileHasPrefix(char *basename, char *prefix)
1783 static char *basename_lower = NULL;
1784 int basename_length, prefix_length;
1786 checked_free(basename_lower);
1788 if (basename == NULL || prefix == NULL)
1791 basename_lower = getStringToLower(basename);
1792 basename_length = strlen(basename_lower);
1793 prefix_length = strlen(prefix);
1795 if (basename_length > prefix_length + 1 &&
1796 basename_lower[prefix_length] == '.' &&
1797 strncmp(basename_lower, prefix, prefix_length) == 0)
1803 boolean fileHasSuffix(char *basename, char *suffix)
1805 static char *basename_lower = NULL;
1806 int basename_length, suffix_length;
1808 checked_free(basename_lower);
1810 if (basename == NULL || suffix == NULL)
1813 basename_lower = getStringToLower(basename);
1814 basename_length = strlen(basename_lower);
1815 suffix_length = strlen(suffix);
1817 if (basename_length > suffix_length + 1 &&
1818 basename_lower[basename_length - suffix_length - 1] == '.' &&
1819 strEqual(&basename_lower[basename_length - suffix_length], suffix))
1825 boolean FileIsGraphic(char *filename)
1827 char *basename = getBaseNamePtr(filename);
1829 return fileHasSuffix(basename, "pcx");
1832 boolean FileIsSound(char *filename)
1834 char *basename = getBaseNamePtr(filename);
1836 return fileHasSuffix(basename, "wav");
1839 boolean FileIsMusic(char *filename)
1841 char *basename = getBaseNamePtr(filename);
1843 if (FileIsSound(basename))
1846 #if defined(TARGET_SDL)
1847 if (fileHasPrefix(basename, "mod") ||
1848 fileHasSuffix(basename, "mod") ||
1849 fileHasSuffix(basename, "s3m") ||
1850 fileHasSuffix(basename, "it") ||
1851 fileHasSuffix(basename, "xm") ||
1852 fileHasSuffix(basename, "midi") ||
1853 fileHasSuffix(basename, "mid") ||
1854 fileHasSuffix(basename, "mp3") ||
1855 fileHasSuffix(basename, "ogg"))
1862 boolean FileIsArtworkType(char *basename, int type)
1864 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1865 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1866 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1872 /* ------------------------------------------------------------------------- */
1873 /* functions for loading artwork configuration information */
1874 /* ------------------------------------------------------------------------- */
1876 char *get_mapped_token(char *token)
1878 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
1879 static char *map_token_prefix[][2] =
1881 { "char_procent", "char_percent" },
1886 for (i = 0; map_token_prefix[i][0] != NULL; i++)
1888 int len_token_prefix = strlen(map_token_prefix[i][0]);
1890 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
1891 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
1897 /* This function checks if a string <s> of the format "string1, string2, ..."
1898 exactly contains a string <s_contained>. */
1900 static boolean string_has_parameter(char *s, char *s_contained)
1904 if (s == NULL || s_contained == NULL)
1907 if (strlen(s_contained) > strlen(s))
1910 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
1912 char next_char = s[strlen(s_contained)];
1914 /* check if next character is delimiter or whitespace */
1915 return (next_char == ',' || next_char == '\0' ||
1916 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
1919 /* check if string contains another parameter string after a comma */
1920 substring = strchr(s, ',');
1921 if (substring == NULL) /* string does not contain a comma */
1924 /* advance string pointer to next character after the comma */
1927 /* skip potential whitespaces after the comma */
1928 while (*substring == ' ' || *substring == '\t')
1931 return string_has_parameter(substring, s_contained);
1934 int get_parameter_value(char *value_raw, char *suffix, int type)
1936 char *value = getStringToLower(value_raw);
1937 int result = 0; /* probably a save default value */
1939 if (strEqual(suffix, ".direction"))
1941 result = (strEqual(value, "left") ? MV_LEFT :
1942 strEqual(value, "right") ? MV_RIGHT :
1943 strEqual(value, "up") ? MV_UP :
1944 strEqual(value, "down") ? MV_DOWN : MV_NONE);
1946 else if (strEqual(suffix, ".anim_mode"))
1948 result = (string_has_parameter(value, "none") ? ANIM_NONE :
1949 string_has_parameter(value, "loop") ? ANIM_LOOP :
1950 string_has_parameter(value, "linear") ? ANIM_LINEAR :
1951 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
1952 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
1953 string_has_parameter(value, "random") ? ANIM_RANDOM :
1954 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
1955 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
1956 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
1957 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
1958 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
1961 if (string_has_parameter(value, "reverse"))
1962 result |= ANIM_REVERSE;
1964 if (string_has_parameter(value, "opaque_player"))
1965 result |= ANIM_OPAQUE_PLAYER;
1967 if (string_has_parameter(value, "static_panel"))
1968 result |= ANIM_STATIC_PANEL;
1970 else /* generic parameter of type integer or boolean */
1972 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
1973 type == TYPE_INTEGER ? get_integer_from_string(value) :
1974 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
1975 ARG_UNDEFINED_VALUE);
1983 int get_auto_parameter_value(char *token, char *value_raw)
1987 if (token == NULL || value_raw == NULL)
1988 return ARG_UNDEFINED_VALUE;
1990 suffix = strrchr(token, '.');
1994 return get_parameter_value(value_raw, suffix, TYPE_INTEGER);
1997 static void FreeCustomArtworkList(struct ArtworkListInfo *,
1998 struct ListNodeInfo ***, int *);
2000 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2001 struct ConfigTypeInfo *suffix_list,
2002 char **ignore_tokens,
2003 int num_file_list_entries)
2005 struct FileInfo *file_list;
2006 int num_file_list_entries_found = 0;
2007 int num_suffix_list_entries = 0;
2011 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2013 for (i = 0; suffix_list[i].token != NULL; i++)
2014 num_suffix_list_entries++;
2016 /* always start with reliable default values */
2017 for (i = 0; i < num_file_list_entries; i++)
2019 file_list[i].token = NULL;
2021 file_list[i].default_filename = NULL;
2022 file_list[i].filename = NULL;
2024 if (num_suffix_list_entries > 0)
2026 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2028 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2029 file_list[i].parameter = checked_calloc(parameter_array_size);
2031 for (j = 0; j < num_suffix_list_entries; j++)
2033 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2034 setString(&file_list[i].parameter[j], suffix_list[j].value);
2037 file_list[i].redefined = FALSE;
2038 file_list[i].fallback_to_default = FALSE;
2043 for (i = 0; config_list[i].token != NULL; i++)
2045 int len_config_token = strlen(config_list[i].token);
2046 int len_config_value = strlen(config_list[i].value);
2047 boolean is_file_entry = TRUE;
2049 for (j = 0; suffix_list[j].token != NULL; j++)
2051 int len_suffix = strlen(suffix_list[j].token);
2053 if (len_suffix < len_config_token &&
2054 strEqual(&config_list[i].token[len_config_token - len_suffix],
2055 suffix_list[j].token))
2057 setString(&file_list[list_pos].default_parameter[j],
2058 config_list[i].value);
2060 is_file_entry = FALSE;
2065 /* the following tokens are no file definitions, but other config tokens */
2066 for (j = 0; ignore_tokens[j] != NULL; j++)
2067 if (strEqual(config_list[i].token, ignore_tokens[j]))
2068 is_file_entry = FALSE;
2075 if (list_pos >= num_file_list_entries)
2078 /* simple sanity check if this is really a file definition */
2079 if (!strEqual(&config_list[i].value[len_config_value - 4], ".pcx") &&
2080 !strEqual(&config_list[i].value[len_config_value - 4], ".wav") &&
2081 !strEqual(config_list[i].value, UNDEFINED_FILENAME))
2083 Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
2084 config_list[i].token, config_list[i].value);
2085 Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
2088 file_list[list_pos].token = config_list[i].token;
2089 file_list[list_pos].default_filename = config_list[i].value;
2093 num_file_list_entries_found = list_pos + 1;
2094 if (num_file_list_entries_found != num_file_list_entries)
2096 Error(ERR_RETURN_LINE, "-");
2097 Error(ERR_RETURN, "inconsistant config list information:");
2098 Error(ERR_RETURN, "- should be: %d (according to 'src/conf_gfx.h')",
2099 num_file_list_entries);
2100 Error(ERR_RETURN, "- found to be: %d (according to 'src/conf_gfx.c')",
2101 num_file_list_entries_found);
2102 Error(ERR_EXIT, "please fix");
2108 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2110 int len_token = strlen(token);
2111 int len_suffix = strlen(suffix);
2113 if (start_pos < 0) /* compare suffix from end of string */
2114 start_pos += len_token;
2116 if (start_pos < 0 || start_pos + len_suffix > len_token)
2119 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2122 if (token[start_pos + len_suffix] == '\0')
2125 if (token[start_pos + len_suffix] == '.')
2131 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2133 static void read_token_parameters(SetupFileHash *setup_file_hash,
2134 struct ConfigTypeInfo *suffix_list,
2135 struct FileInfo *file_list_entry)
2137 /* check for config token that is the base token without any suffixes */
2138 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2139 char *known_token_value = KNOWN_TOKEN_VALUE;
2142 if (filename != NULL)
2144 setString(&file_list_entry->filename, filename);
2146 /* when file definition found, set all parameters to default values */
2147 for (i = 0; suffix_list[i].token != NULL; i++)
2148 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2150 file_list_entry->redefined = TRUE;
2152 /* mark config file token as well known from default config */
2153 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2156 /* check for config tokens that can be build by base token and suffixes */
2157 for (i = 0; suffix_list[i].token != NULL; i++)
2159 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2160 char *value = getHashEntry(setup_file_hash, token);
2164 setString(&file_list_entry->parameter[i], value);
2166 /* mark config file token as well known from default config */
2167 setHashEntry(setup_file_hash, token, known_token_value);
2174 static void add_dynamic_file_list_entry(struct FileInfo **list,
2175 int *num_list_entries,
2176 SetupFileHash *extra_file_hash,
2177 struct ConfigTypeInfo *suffix_list,
2178 int num_suffix_list_entries,
2181 struct FileInfo *new_list_entry;
2182 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2184 (*num_list_entries)++;
2185 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2186 new_list_entry = &(*list)[*num_list_entries - 1];
2188 new_list_entry->token = getStringCopy(token);
2189 new_list_entry->default_filename = NULL;
2190 new_list_entry->filename = NULL;
2191 new_list_entry->parameter = checked_calloc(parameter_array_size);
2193 new_list_entry->redefined = FALSE;
2194 new_list_entry->fallback_to_default = FALSE;
2196 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2199 static void add_property_mapping(struct PropertyMapping **list,
2200 int *num_list_entries,
2201 int base_index, int ext1_index,
2202 int ext2_index, int ext3_index,
2205 struct PropertyMapping *new_list_entry;
2207 (*num_list_entries)++;
2208 *list = checked_realloc(*list,
2209 *num_list_entries * sizeof(struct PropertyMapping));
2210 new_list_entry = &(*list)[*num_list_entries - 1];
2212 new_list_entry->base_index = base_index;
2213 new_list_entry->ext1_index = ext1_index;
2214 new_list_entry->ext2_index = ext2_index;
2215 new_list_entry->ext3_index = ext3_index;
2217 new_list_entry->artwork_index = artwork_index;
2220 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2223 struct FileInfo *file_list = artwork_info->file_list;
2224 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2225 char **base_prefixes = artwork_info->base_prefixes;
2226 char **ext1_suffixes = artwork_info->ext1_suffixes;
2227 char **ext2_suffixes = artwork_info->ext2_suffixes;
2228 char **ext3_suffixes = artwork_info->ext3_suffixes;
2229 char **ignore_tokens = artwork_info->ignore_tokens;
2230 int num_file_list_entries = artwork_info->num_file_list_entries;
2231 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2232 int num_base_prefixes = artwork_info->num_base_prefixes;
2233 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2234 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2235 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2236 int num_ignore_tokens = artwork_info->num_ignore_tokens;
2237 SetupFileHash *setup_file_hash, *valid_file_hash;
2238 SetupFileHash *extra_file_hash, *empty_file_hash;
2239 char *known_token_value = KNOWN_TOKEN_VALUE;
2242 if (filename == NULL)
2246 printf("LoadArtworkConfigFromFilename '%s' ...\n", filename);
2249 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2252 /* separate valid (defined) from empty (undefined) config token values */
2253 valid_file_hash = newSetupFileHash();
2254 empty_file_hash = newSetupFileHash();
2255 BEGIN_HASH_ITERATION(setup_file_hash, itr)
2257 char *value = HASH_ITERATION_VALUE(itr);
2259 setHashEntry(*value ? valid_file_hash : empty_file_hash,
2260 HASH_ITERATION_TOKEN(itr), value);
2262 END_HASH_ITERATION(setup_file_hash, itr)
2264 /* at this point, we do not need the setup file hash anymore -- free it */
2265 freeSetupFileHash(setup_file_hash);
2267 /* map deprecated to current tokens (using prefix match and replace) */
2268 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2270 char *token = HASH_ITERATION_TOKEN(itr);
2271 char *mapped_token = get_mapped_token(token);
2273 if (mapped_token != NULL)
2275 char *value = HASH_ITERATION_VALUE(itr);
2277 /* add mapped token */
2278 setHashEntry(valid_file_hash, mapped_token, value);
2280 /* ignore old token (by setting it to "known" keyword) */
2281 setHashEntry(valid_file_hash, token, known_token_value);
2286 END_HASH_ITERATION(valid_file_hash, itr)
2288 /* read parameters for all known config file tokens */
2289 for (i = 0; i < num_file_list_entries; i++)
2290 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2292 /* set all tokens that can be ignored here to "known" keyword */
2293 for (i = 0; i < num_ignore_tokens; i++)
2294 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2296 /* copy all unknown config file tokens to extra config hash */
2297 extra_file_hash = newSetupFileHash();
2298 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2300 char *value = HASH_ITERATION_VALUE(itr);
2302 if (!strEqual(value, known_token_value))
2303 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2305 END_HASH_ITERATION(valid_file_hash, itr)
2307 /* at this point, we do not need the valid file hash anymore -- free it */
2308 freeSetupFileHash(valid_file_hash);
2310 /* now try to determine valid, dynamically defined config tokens */
2312 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2314 struct FileInfo **dynamic_file_list =
2315 &artwork_info->dynamic_file_list;
2316 int *num_dynamic_file_list_entries =
2317 &artwork_info->num_dynamic_file_list_entries;
2318 struct PropertyMapping **property_mapping =
2319 &artwork_info->property_mapping;
2320 int *num_property_mapping_entries =
2321 &artwork_info->num_property_mapping_entries;
2322 int current_summarized_file_list_entry =
2323 artwork_info->num_file_list_entries +
2324 artwork_info->num_dynamic_file_list_entries;
2325 char *token = HASH_ITERATION_TOKEN(itr);
2326 int len_token = strlen(token);
2328 boolean base_prefix_found = FALSE;
2329 boolean parameter_suffix_found = FALSE;
2332 printf("::: examining '%s' -> '%s'\n", token, HASH_ITERATION_VALUE(itr));
2335 /* skip all parameter definitions (handled by read_token_parameters()) */
2336 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2338 int len_suffix = strlen(suffix_list[i].token);
2340 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2341 parameter_suffix_found = TRUE;
2344 if (parameter_suffix_found)
2347 /* ---------- step 0: search for matching base prefix ---------- */
2350 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2352 char *base_prefix = base_prefixes[i];
2353 int len_base_prefix = strlen(base_prefix);
2354 boolean ext1_suffix_found = FALSE;
2355 boolean ext2_suffix_found = FALSE;
2356 boolean ext3_suffix_found = FALSE;
2357 boolean exact_match = FALSE;
2358 int base_index = -1;
2359 int ext1_index = -1;
2360 int ext2_index = -1;
2361 int ext3_index = -1;
2363 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2365 if (!base_prefix_found)
2370 if (start_pos + len_base_prefix == len_token) /* exact match */
2374 add_dynamic_file_list_entry(dynamic_file_list,
2375 num_dynamic_file_list_entries,
2378 num_suffix_list_entries,
2380 add_property_mapping(property_mapping,
2381 num_property_mapping_entries,
2382 base_index, -1, -1, -1,
2383 current_summarized_file_list_entry);
2388 if (IS_PARENT_PROCESS())
2389 printf("---> examining token '%s': search 1st suffix ...\n", token);
2392 /* ---------- step 1: search for matching first suffix ---------- */
2394 start_pos += len_base_prefix;
2395 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
2397 char *ext1_suffix = ext1_suffixes[j];
2398 int len_ext1_suffix = strlen(ext1_suffix);
2400 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2402 if (!ext1_suffix_found)
2407 if (start_pos + len_ext1_suffix == len_token) /* exact match */
2411 add_dynamic_file_list_entry(dynamic_file_list,
2412 num_dynamic_file_list_entries,
2415 num_suffix_list_entries,
2417 add_property_mapping(property_mapping,
2418 num_property_mapping_entries,
2419 base_index, ext1_index, -1, -1,
2420 current_summarized_file_list_entry);
2424 start_pos += len_ext1_suffix;
2431 if (IS_PARENT_PROCESS())
2432 printf("---> examining token '%s': search 2nd suffix ...\n", token);
2435 /* ---------- step 2: search for matching second suffix ---------- */
2437 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
2439 char *ext2_suffix = ext2_suffixes[k];
2440 int len_ext2_suffix = strlen(ext2_suffix);
2442 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
2444 if (!ext2_suffix_found)
2449 if (start_pos + len_ext2_suffix == len_token) /* exact match */
2453 add_dynamic_file_list_entry(dynamic_file_list,
2454 num_dynamic_file_list_entries,
2457 num_suffix_list_entries,
2459 add_property_mapping(property_mapping,
2460 num_property_mapping_entries,
2461 base_index, ext1_index, ext2_index, -1,
2462 current_summarized_file_list_entry);
2466 start_pos += len_ext2_suffix;
2473 if (IS_PARENT_PROCESS())
2474 printf("---> examining token '%s': search 3rd suffix ...\n",token);
2477 /* ---------- step 3: search for matching third suffix ---------- */
2479 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
2481 char *ext3_suffix = ext3_suffixes[l];
2482 int len_ext3_suffix = strlen(ext3_suffix);
2484 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
2486 if (!ext3_suffix_found)
2491 if (start_pos + len_ext3_suffix == len_token) /* exact match */
2495 add_dynamic_file_list_entry(dynamic_file_list,
2496 num_dynamic_file_list_entries,
2499 num_suffix_list_entries,
2501 add_property_mapping(property_mapping,
2502 num_property_mapping_entries,
2503 base_index, ext1_index, ext2_index, ext3_index,
2504 current_summarized_file_list_entry);
2510 END_HASH_ITERATION(extra_file_hash, itr)
2512 if (artwork_info->num_dynamic_file_list_entries > 0)
2514 artwork_info->dynamic_artwork_list =
2515 checked_calloc(artwork_info->num_dynamic_file_list_entries *
2516 artwork_info->sizeof_artwork_list_entry);
2519 if (options.verbose && IS_PARENT_PROCESS())
2521 SetupFileList *setup_file_list, *list;
2522 boolean dynamic_tokens_found = FALSE;
2523 boolean unknown_tokens_found = FALSE;
2524 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
2526 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
2527 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
2529 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2531 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
2532 dynamic_tokens_found = TRUE;
2534 unknown_tokens_found = TRUE;
2536 END_HASH_ITERATION(extra_file_hash, itr)
2538 if (options.debug && dynamic_tokens_found)
2540 Error(ERR_RETURN_LINE, "-");
2541 Error(ERR_RETURN, "dynamic token(s) found in config file:");
2542 Error(ERR_RETURN, "- config file: '%s'", filename);
2544 for (list = setup_file_list; list != NULL; list = list->next)
2546 char *value = getHashEntry(extra_file_hash, list->token);
2548 if (value != NULL && strEqual(value, known_token_value))
2549 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2552 Error(ERR_RETURN_LINE, "-");
2555 if (unknown_tokens_found)
2557 Error(ERR_RETURN_LINE, "-");
2558 Error(ERR_RETURN, "warning: unknown token(s) found in config file:");
2559 Error(ERR_RETURN, "- config file: '%s'", filename);
2561 for (list = setup_file_list; list != NULL; list = list->next)
2563 char *value = getHashEntry(extra_file_hash, list->token);
2565 if (value != NULL && !strEqual(value, known_token_value))
2566 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2569 Error(ERR_RETURN_LINE, "-");
2572 if (undefined_values_found)
2574 Error(ERR_RETURN_LINE, "-");
2575 Error(ERR_RETURN, "warning: undefined values found in config file:");
2576 Error(ERR_RETURN, "- config file: '%s'", filename);
2578 for (list = setup_file_list; list != NULL; list = list->next)
2580 char *value = getHashEntry(empty_file_hash, list->token);
2583 Error(ERR_RETURN, "- undefined value for token: '%s'", list->token);
2586 Error(ERR_RETURN_LINE, "-");
2589 freeSetupFileList(setup_file_list);
2592 freeSetupFileHash(extra_file_hash);
2593 freeSetupFileHash(empty_file_hash);
2596 for (i = 0; i < num_file_list_entries; i++)
2598 printf("'%s' ", file_list[i].token);
2599 if (file_list[i].filename)
2600 printf("-> '%s'\n", file_list[i].filename);
2602 printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
2607 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
2609 struct FileInfo *file_list = artwork_info->file_list;
2610 int num_file_list_entries = artwork_info->num_file_list_entries;
2611 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2612 char *filename_base = UNDEFINED_FILENAME, *filename_local;
2615 DrawInitText("Loading artwork config:", 120, FC_GREEN);
2616 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
2618 /* always start with reliable default values */
2619 for (i = 0; i < num_file_list_entries; i++)
2621 setString(&file_list[i].filename, file_list[i].default_filename);
2623 for (j = 0; j < num_suffix_list_entries; j++)
2624 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
2626 file_list[i].redefined = FALSE;
2627 file_list[i].fallback_to_default = FALSE;
2630 /* free previous dynamic artwork file array */
2631 if (artwork_info->dynamic_file_list != NULL)
2633 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
2635 free(artwork_info->dynamic_file_list[i].token);
2636 free(artwork_info->dynamic_file_list[i].filename);
2637 free(artwork_info->dynamic_file_list[i].parameter);
2640 free(artwork_info->dynamic_file_list);
2641 artwork_info->dynamic_file_list = NULL;
2643 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2644 &artwork_info->num_dynamic_file_list_entries);
2647 /* free previous property mapping */
2648 if (artwork_info->property_mapping != NULL)
2650 free(artwork_info->property_mapping);
2652 artwork_info->property_mapping = NULL;
2653 artwork_info->num_property_mapping_entries = 0;
2656 if (!SETUP_OVERRIDE_ARTWORK(setup, artwork_info->type))
2658 /* first look for special artwork configured in level series config */
2659 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
2661 if (fileExists(filename_base))
2662 LoadArtworkConfigFromFilename(artwork_info, filename_base);
2665 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
2667 if (filename_local != NULL && !strEqual(filename_base, filename_local))
2668 LoadArtworkConfigFromFilename(artwork_info, filename_local);
2671 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
2672 struct ListNodeInfo **listnode)
2676 char *filename = (*listnode)->source_filename;
2678 if (--(*listnode)->num_references <= 0)
2679 deleteNodeFromList(&artwork_info->content_list, filename,
2680 artwork_info->free_artwork);
2686 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
2687 struct ListNodeInfo **listnode,
2688 struct FileInfo *file_list_entry)
2692 "Loading graphics:",
2698 char *basename = file_list_entry->filename;
2699 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
2701 if (filename == NULL)
2703 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
2705 basename = file_list_entry->default_filename;
2707 /* dynamic artwork has no default filename / skip empty default artwork */
2708 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
2711 file_list_entry->fallback_to_default = TRUE;
2713 Error(ERR_WARN, "trying default artwork file '%s'", basename);
2715 filename = getCustomArtworkFilename(basename, artwork_info->type);
2717 if (filename == NULL)
2719 int error_mode = ERR_WARN;
2721 /* we can get away without sounds and music, but not without graphics */
2722 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2723 error_mode = ERR_EXIT;
2725 Error(error_mode, "cannot find default artwork file '%s'", basename);
2731 /* check if the old and the new artwork file are the same */
2732 if (*listnode && strEqual((*listnode)->source_filename, filename))
2734 /* The old and new artwork are the same (have the same filename and path).
2735 This usually means that this artwork does not exist in this artwork set
2736 and a fallback to the existing artwork is done. */
2739 printf("[artwork '%s' already exists (same list entry)]\n", filename);
2745 /* delete existing artwork file entry */
2746 deleteArtworkListEntry(artwork_info, listnode);
2748 /* check if the new artwork file already exists in the list of artworks */
2749 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
2752 printf("[artwork '%s' already exists (other list entry)]\n", filename);
2755 *listnode = (struct ListNodeInfo *)node->content;
2756 (*listnode)->num_references++;
2761 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
2762 DrawInitText(basename, 150, FC_YELLOW);
2764 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
2767 printf("[adding new artwork '%s']\n", filename);
2770 (*listnode)->num_references = 1;
2771 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
2776 int error_mode = ERR_WARN;
2778 /* we can get away without sounds and music, but not without graphics */
2779 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2780 error_mode = ERR_EXIT;
2782 Error(error_mode, "cannot load artwork file '%s'", basename);
2787 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
2788 struct ListNodeInfo **listnode,
2789 struct FileInfo *file_list_entry)
2792 printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
2795 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
2797 deleteArtworkListEntry(artwork_info, listnode);
2801 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
2804 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
2806 struct FileInfo *file_list = artwork_info->file_list;
2807 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
2808 int num_file_list_entries = artwork_info->num_file_list_entries;
2809 int num_dynamic_file_list_entries =
2810 artwork_info->num_dynamic_file_list_entries;
2813 for (i = 0; i < num_file_list_entries; i++)
2814 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
2817 for (i = 0; i < num_dynamic_file_list_entries; i++)
2818 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
2819 &dynamic_file_list[i]);
2822 dumpList(artwork_info->content_list);
2826 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
2827 struct ListNodeInfo ***list,
2828 int *num_list_entries)
2835 for (i = 0; i < *num_list_entries; i++)
2836 deleteArtworkListEntry(artwork_info, &(*list)[i]);
2840 *num_list_entries = 0;
2843 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
2845 if (artwork_info == NULL)
2848 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
2849 &artwork_info->num_file_list_entries);
2851 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2852 &artwork_info->num_dynamic_file_list_entries);
2856 /* ------------------------------------------------------------------------- */
2857 /* functions only needed for non-Unix (non-command-line) systems */
2858 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
2859 /* (now also added for Windows, to create files in user data directory) */
2860 /* ------------------------------------------------------------------------- */
2862 char *getErrorFilename(char *basename)
2864 return getPath2(getUserDataDir(), basename);
2867 void initErrorFile()
2869 unlink(program.error_filename);
2872 FILE *openErrorFile()
2874 FILE *error_file = stderr;
2876 #if defined(PLATFORM_WIN32) || defined(PLATFORM_MSDOS)
2877 if ((error_file = fopen(program.error_filename, MODE_APPEND)) == NULL)
2878 fprintf_newline(stderr, "ERROR: cannot open file '%s' for appending!",
2879 program.error_filename);
2885 void dumpErrorFile()
2887 FILE *error_file = fopen(program.error_filename, MODE_READ);
2889 if (error_file != NULL)
2891 while (!feof(error_file))
2892 fputc(fgetc(error_file), stderr);
2898 void NotifyUserAboutErrorFile()
2900 #if defined(PLATFORM_WIN32)
2901 char *title_text = getStringCat2(program.program_title, " Error Message");
2902 char *error_text = getStringCat2("The program was aborted due to an error; "
2903 "for details, see the following error file:"
2904 STRING_NEWLINE, program.error_filename);
2906 MessageBox(NULL, error_text, title_text, MB_OK);
2911 /* ------------------------------------------------------------------------- */
2912 /* the following is only for debugging purpose and normally not used */
2913 /* ------------------------------------------------------------------------- */
2915 #define DEBUG_NUM_TIMESTAMPS 3
2917 void debug_print_timestamp(int counter_nr, char *message)
2919 static long counter[DEBUG_NUM_TIMESTAMPS][2];
2921 if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
2922 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
2924 counter[counter_nr][0] = Counter();
2927 printf("%s %.2f seconds\n", message,
2928 (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
2930 counter[counter_nr][1] = Counter();
2933 void debug_print_parent_only(char *format, ...)
2935 if (!IS_PARENT_PROCESS())
2942 va_start(ap, format);
2943 vprintf(format, ap);