1 /***********************************************************
2 * Artsoft Retro-Game Library *
3 *----------------------------------------------------------*
4 * (c) 1994-2006 Artsoft Entertainment *
6 * Detmolder Strasse 189 *
9 * e-mail: info@artsoft.org *
10 *----------------------------------------------------------*
12 ***********************************************************/
16 #include <sys/types.h>
26 #if !defined(PLATFORM_WIN32)
28 #include <sys/param.h>
38 /* ========================================================================= */
39 /* some generic helper functions */
40 /* ========================================================================= */
42 /* ------------------------------------------------------------------------- */
43 /* platform independent wrappers for printf() et al. (newline aware) */
44 /* ------------------------------------------------------------------------- */
46 #if defined(PLATFORM_ANDROID)
47 static int android_log_prio = ANDROID_LOG_INFO;
51 static void vfPrintLog(FILE *stream, char *format, va_list ap)
55 static void vfPrintLog(FILE *stream, char *format, va_list ap)
59 static void fPrintLog(FILE *stream, char *format, va_list ap)
63 static void fPrintLog(FILE *stream, char *format, va_list ap)
68 static void vfprintf_nonewline(FILE *stream, char *format, va_list ap)
70 #if defined(PLATFORM_ANDROID)
71 // (prefix text of logging output is currently skipped on Android)
72 //__android_log_vprint(android_log_prio, program.program_title, format, ap);
77 vfprintf(stream, format, ap);
78 vfprintf(stderr, format, ap2);
84 static void vfprintf_newline(FILE *stream, char *format, va_list ap)
86 #if defined(PLATFORM_ANDROID)
87 __android_log_vprint(android_log_prio, program.program_title, format, ap);
89 char *newline = STRING_NEWLINE;
94 vfprintf(stream, format, ap);
95 fprintf(stream, "%s", newline);
97 vfprintf(stderr, format, ap2);
98 fprintf(stderr, "%s", newline);
104 static void fprintf_nonewline(FILE *stream, char *format, ...)
108 va_start(ap, format);
109 vfprintf_nonewline(stream, format, ap);
113 static void fprintf_newline(FILE *stream, char *format, ...)
117 va_start(ap, format);
118 vfprintf_newline(stream, format, ap);
122 void fprintf_line(FILE *stream, char *line_chars, int line_length)
126 for (i = 0; i < line_length; i++)
127 fprintf_nonewline(stream, "%s", line_chars);
129 fprintf_newline(stream, "");
132 void printf_line(char *line_chars, int line_length)
134 fprintf_line(stdout, line_chars, line_length);
137 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
139 fprintf(stdout, "%s", prefix);
140 fprintf_line(stdout, line_chars, line_length);
144 /* ------------------------------------------------------------------------- */
145 /* string functions */
146 /* ------------------------------------------------------------------------- */
148 /* int2str() returns a number converted to a string;
149 the used memory is static, but will be overwritten by later calls,
150 so if you want to save the result, copy it to a private string buffer;
151 there can be 10 local calls of int2str() without buffering the result --
152 the 11th call will then destroy the result from the first call and so on.
155 char *int2str(int number, int size)
157 static char shift_array[10][40];
158 static int shift_counter = 0;
159 char *s = shift_array[shift_counter];
161 shift_counter = (shift_counter + 1) % 10;
168 sprintf(s, " %09d", number);
169 return &s[strlen(s) - size];
173 sprintf(s, "%d", number);
179 /* something similar to "int2str()" above, but allocates its own memory
180 and has a different interface; we cannot use "itoa()", because this
181 seems to be already defined when cross-compiling to the win32 target */
183 char *i_to_a(unsigned int i)
185 static char *a = NULL;
189 if (i > 2147483647) /* yes, this is a kludge */
192 a = checked_malloc(10 + 1);
200 /* calculate base-2 logarithm of argument (rounded down to integer;
201 this function returns the number of the highest bit set in argument) */
203 int log_2(unsigned int x)
209 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
216 boolean getTokenValueFromString(char *string, char **token, char **value)
218 return getTokenValueFromSetupLine(string, token, value);
222 /* ------------------------------------------------------------------------- */
223 /* counter functions */
224 /* ------------------------------------------------------------------------- */
226 #if defined(PLATFORM_MSDOS)
227 volatile unsigned int counter = 0;
229 void increment_counter()
234 END_OF_FUNCTION(increment_counter);
238 /* maximal allowed length of a command line option */
239 #define MAX_OPTION_LEN 256
243 #if defined(TARGET_SDL)
244 static unsigned int getCurrentMS()
246 return SDL_GetTicks();
249 #else /* !TARGET_SDL */
251 #if defined(PLATFORM_UNIX)
252 static unsigned int getCurrentMS()
254 struct timeval current_time;
256 gettimeofday(¤t_time, NULL);
258 return current_time.tv_sec * 1000 + current_time.tv_usec / 1000;
260 #endif /* PLATFORM_UNIX */
261 #endif /* !TARGET_SDL */
263 static unsigned int mainCounter(int mode)
265 static unsigned int base_ms = 0;
266 unsigned int current_ms;
268 /* get current system milliseconds */
269 current_ms = getCurrentMS();
271 /* reset base timestamp in case of counter reset or wrap-around */
272 if (mode == INIT_COUNTER || current_ms < base_ms)
273 base_ms = current_ms;
275 /* return milliseconds since last counter reset */
276 return current_ms - base_ms;
281 #if defined(TARGET_SDL)
282 static unsigned int mainCounter(int mode)
284 static unsigned int base_ms = 0;
285 unsigned int current_ms;
286 unsigned int counter_ms;
288 current_ms = SDL_GetTicks();
290 /* reset base time in case of counter initializing or wrap-around */
291 if (mode == INIT_COUNTER || current_ms < base_ms)
292 base_ms = current_ms;
294 counter_ms = current_ms - base_ms;
296 return counter_ms; /* return milliseconds since last init */
299 #else /* !TARGET_SDL */
301 #if defined(PLATFORM_UNIX)
302 static unsigned int mainCounter(int mode)
304 static struct timeval base_time = { 0, 0 };
305 struct timeval current_time;
306 unsigned int counter_ms;
308 gettimeofday(¤t_time, NULL);
310 /* reset base time in case of counter initializing or wrap-around */
311 if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
312 base_time = current_time;
314 counter_ms = (current_time.tv_sec - base_time.tv_sec) * 1000
315 + (current_time.tv_usec - base_time.tv_usec) / 1000;
317 return counter_ms; /* return milliseconds since last init */
319 #endif /* PLATFORM_UNIX */
320 #endif /* !TARGET_SDL */
324 void InitCounter() /* set counter back to zero */
326 #if !defined(PLATFORM_MSDOS)
327 mainCounter(INIT_COUNTER);
329 LOCK_VARIABLE(counter);
330 LOCK_FUNCTION(increment_counter);
331 install_int_ex(increment_counter, BPS_TO_TIMER(100));
335 unsigned int Counter() /* get milliseconds since last call of InitCounter() */
337 #if !defined(PLATFORM_MSDOS)
338 return mainCounter(READ_COUNTER);
340 return (counter * 10);
344 static void sleep_milliseconds(unsigned int milliseconds_delay)
346 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
350 /* we want to wait only a few ms -- if we assume that we have a
351 kernel timer resolution of 10 ms, we would wait far to long;
352 therefore it's better to do a short interval of busy waiting
353 to get our sleeping time more accurate */
355 unsigned int base_counter = Counter(), actual_counter = Counter();
357 while (actual_counter < base_counter + milliseconds_delay &&
358 actual_counter >= base_counter)
359 actual_counter = Counter();
363 #if defined(TARGET_SDL)
364 SDL_Delay(milliseconds_delay);
365 #elif defined(TARGET_ALLEGRO)
366 rest(milliseconds_delay);
368 struct timeval delay;
370 delay.tv_sec = milliseconds_delay / 1000;
371 delay.tv_usec = 1000 * (milliseconds_delay % 1000);
373 if (select(0, NULL, NULL, NULL, &delay) != 0)
374 Error(ERR_WARN, "sleep_milliseconds(): select() failed");
379 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
381 sleep_milliseconds(delay);
384 boolean FrameReached(unsigned int *frame_counter_var,
385 unsigned int frame_delay)
387 unsigned int actual_frame_counter = FrameCounter;
389 if (actual_frame_counter >= *frame_counter_var &&
390 actual_frame_counter < *frame_counter_var + frame_delay)
393 *frame_counter_var = actual_frame_counter;
398 boolean DelayReached(unsigned int *counter_var,
401 unsigned int actual_counter = Counter();
403 if (actual_counter >= *counter_var &&
404 actual_counter < *counter_var + delay)
407 *counter_var = actual_counter;
412 void WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
414 unsigned int actual_counter;
418 actual_counter = Counter();
420 if (actual_counter >= *counter_var &&
421 actual_counter < *counter_var + delay)
422 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
427 *counter_var = actual_counter;
431 /* ------------------------------------------------------------------------- */
432 /* random generator functions */
433 /* ------------------------------------------------------------------------- */
435 unsigned int init_random_number(int nr, int seed)
437 if (seed == NEW_RANDOMIZE)
439 /* default random seed */
440 seed = (int)time(NULL); // seconds since the epoch
442 #if !defined(PLATFORM_WIN32)
443 /* add some more randomness */
444 struct timeval current_time;
446 gettimeofday(¤t_time, NULL);
448 seed += (int)current_time.tv_usec; // microseconds since the epoch
451 #if defined(TARGET_SDL)
452 /* add some more randomness */
453 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
457 /* add some more randomness */
458 seed += GetSimpleRandom(1000000);
462 srandom_linux_libc(nr, (unsigned int) seed);
464 return (unsigned int) seed;
467 unsigned int get_random_number(int nr, int max)
469 return (max > 0 ? random_linux_libc(nr) % max : 0);
473 /* ------------------------------------------------------------------------- */
474 /* system info functions */
475 /* ------------------------------------------------------------------------- */
477 #if !defined(PLATFORM_MSDOS) && !defined(PLATFORM_ANDROID)
478 static char *get_corrected_real_name(char *real_name)
480 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
481 char *from_ptr = real_name;
482 char *to_ptr = real_name_new;
484 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
485 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
487 /* the name field read from "passwd" file may also contain additional
488 user information, separated by commas, which will be removed here */
489 if (*from_ptr == ',')
492 /* the user's real name may contain 'ß' characters (german sharp s),
493 which have no equivalent in upper case letters (used by our fonts) */
494 if (*from_ptr == 'ß')
501 *to_ptr++ = *from_ptr++;
506 return real_name_new;
512 static char *login_name = NULL;
514 #if defined(PLATFORM_WIN32)
515 if (login_name == NULL)
517 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
518 login_name = checked_malloc(buffer_size);
520 if (GetUserName(login_name, &buffer_size) == 0)
521 strcpy(login_name, ANONYMOUS_NAME);
524 if (login_name == NULL)
528 if ((pwd = getpwuid(getuid())) == NULL)
529 login_name = ANONYMOUS_NAME;
531 login_name = getStringCopy(pwd->pw_name);
540 static char *real_name = NULL;
542 #if defined(PLATFORM_WIN32)
543 if (real_name == NULL)
545 static char buffer[MAX_USERNAME_LEN + 1];
546 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
548 if (GetUserName(buffer, &buffer_size) != 0)
549 real_name = get_corrected_real_name(buffer);
551 real_name = ANONYMOUS_NAME;
553 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
554 if (real_name == NULL)
558 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
559 real_name = get_corrected_real_name(pwd->pw_gecos);
561 real_name = ANONYMOUS_NAME;
564 real_name = ANONYMOUS_NAME;
570 time_t getFileTimestampEpochSeconds(char *filename)
572 struct stat file_status;
574 if (stat(filename, &file_status) != 0) /* cannot stat file */
577 return file_status.st_mtime;
581 /* ------------------------------------------------------------------------- */
582 /* path manipulation functions */
583 /* ------------------------------------------------------------------------- */
585 static char *getLastPathSeparatorPtr(char *filename)
587 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
589 if (last_separator == NULL) /* also try DOS/Windows variant */
590 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
592 return last_separator;
595 char *getBaseNamePtr(char *filename)
597 char *last_separator = getLastPathSeparatorPtr(filename);
599 if (last_separator != NULL)
600 return last_separator + 1; /* separator found: strip base path */
602 return filename; /* no separator found: filename has no path */
605 char *getBaseName(char *filename)
607 return getStringCopy(getBaseNamePtr(filename));
610 char *getBasePath(char *filename)
612 char *basepath = getStringCopy(filename);
613 char *last_separator = getLastPathSeparatorPtr(basepath);
615 if (last_separator != NULL)
616 *last_separator = '\0'; /* separator found: strip basename */
618 basepath = "."; /* no separator found: use current path */
623 static char *getProgramMainDataPath()
625 char *main_data_path = getStringCopy(program.command_basepath);
627 #if defined(PLATFORM_MACOSX)
628 static char *main_data_binary_subdir = NULL;
630 if (main_data_binary_subdir == NULL)
632 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
634 strlen(MAC_APP_BINARY_SUBDIR) + 1);
636 sprintf(main_data_binary_subdir, "%s.app/%s",
637 program.program_title, MAC_APP_BINARY_SUBDIR);
640 // cut relative path to Mac OS X application binary directory from path
641 if (strSuffix(main_data_path, main_data_binary_subdir))
642 main_data_path[strlen(main_data_path) -
643 strlen(main_data_binary_subdir)] = '\0';
645 // cut trailing path separator from path (but not if path is root directory)
646 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
647 main_data_path[strlen(main_data_path) - 1] = '\0';
650 return main_data_path;
654 /* ------------------------------------------------------------------------- */
655 /* various string functions */
656 /* ------------------------------------------------------------------------- */
658 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
660 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
663 sprintf(complete_string, "%s%s%s", s1, sep, s2);
665 return complete_string;
668 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
670 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
671 strlen(s2) + strlen(sep) +
674 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
676 return complete_string;
679 char *getStringCat2(char *s1, char *s2)
681 return getStringCat2WithSeparator(s1, s2, "");
684 char *getStringCat3(char *s1, char *s2, char *s3)
686 return getStringCat3WithSeparator(s1, s2, s3, "");
689 char *getPath2(char *path1, char *path2)
691 #if defined(PLATFORM_ANDROID)
692 // workaround for reading from APK assets directory -- skip leading "./"
693 if (strEqual(path1, "."))
694 return getStringCopy(path2);
697 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
700 char *getPath3(char *path1, char *path2, char *path3)
702 #if defined(PLATFORM_ANDROID)
703 // workaround for reading from APK assets directory -- skip leading "./"
704 if (strEqual(path1, "."))
705 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
708 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
711 char *getStringCopy(const char *s)
718 s_copy = checked_malloc(strlen(s) + 1);
724 char *getStringCopyN(const char *s, int n)
727 int s_len = MAX(0, n);
732 s_copy = checked_malloc(s_len + 1);
733 strncpy(s_copy, s, s_len);
734 s_copy[s_len] = '\0';
739 char *getStringCopyNStatic(const char *s, int n)
741 static char *s_copy = NULL;
743 checked_free(s_copy);
745 s_copy = getStringCopyN(s, n);
750 char *getStringToLower(const char *s)
752 char *s_copy = checked_malloc(strlen(s) + 1);
753 char *s_ptr = s_copy;
756 *s_ptr++ = tolower(*s++);
762 void setString(char **old_value, char *new_value)
764 checked_free(*old_value);
766 *old_value = getStringCopy(new_value);
769 boolean strEqual(char *s1, char *s2)
771 return (s1 == NULL && s2 == NULL ? TRUE :
772 s1 == NULL && s2 != NULL ? FALSE :
773 s1 != NULL && s2 == NULL ? FALSE :
774 strcmp(s1, s2) == 0);
777 boolean strEqualN(char *s1, char *s2, int n)
779 return (s1 == NULL && s2 == NULL ? TRUE :
780 s1 == NULL && s2 != NULL ? FALSE :
781 s1 != NULL && s2 == NULL ? FALSE :
782 strncmp(s1, s2, n) == 0);
785 boolean strPrefix(char *s, char *prefix)
787 return (s == NULL && prefix == NULL ? TRUE :
788 s == NULL && prefix != NULL ? FALSE :
789 s != NULL && prefix == NULL ? FALSE :
790 strncmp(s, prefix, strlen(prefix)) == 0);
793 boolean strSuffix(char *s, char *suffix)
795 return (s == NULL && suffix == NULL ? TRUE :
796 s == NULL && suffix != NULL ? FALSE :
797 s != NULL && suffix == NULL ? FALSE :
798 strlen(s) < strlen(suffix) ? FALSE :
799 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
802 boolean strPrefixLower(char *s, char *prefix)
804 char *s_lower = getStringToLower(s);
805 boolean match = strPrefix(s_lower, prefix);
812 boolean strSuffixLower(char *s, char *suffix)
814 char *s_lower = getStringToLower(s);
815 boolean match = strSuffix(s_lower, suffix);
823 /* ------------------------------------------------------------------------- */
824 /* command line option handling functions */
825 /* ------------------------------------------------------------------------- */
827 void GetOptions(char *argv[], void (*print_usage_function)(void))
829 char *ro_base_path = RO_BASE_PATH;
830 char *rw_base_path = RW_BASE_PATH;
831 char **options_left = &argv[1];
834 /* if the program is configured to start from current directory (default),
835 determine program package directory from program binary (some versions
836 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
837 set the current working directory to the program package directory) */
839 if (strEqual(ro_base_path, "."))
840 ro_base_path = getProgramMainDataPath();
841 if (strEqual(rw_base_path, "."))
842 rw_base_path = getProgramMainDataPath();
845 #if !defined(PLATFORM_MACOSX)
846 /* if the program is configured to start from current directory (default),
847 determine program package directory (KDE/Konqueror does not do this by
848 itself and fails otherwise); on Mac OS X, the program binary is stored
849 in an application package directory -- do not try to use this directory
850 as the program data directory (Mac OS X handles this correctly anyway) */
852 if (strEqual(ro_base_path, "."))
853 ro_base_path = program.command_basepath;
854 if (strEqual(rw_base_path, "."))
855 rw_base_path = program.command_basepath;
860 /* initialize global program options */
861 options.display_name = NULL;
862 options.server_host = NULL;
863 options.server_port = 0;
865 options.ro_base_directory = ro_base_path;
866 options.rw_base_directory = rw_base_path;
867 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
868 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
869 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
870 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
871 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
873 options.execute_command = NULL;
874 options.special_flags = NULL;
876 options.serveronly = FALSE;
877 options.network = FALSE;
878 options.verbose = FALSE;
879 options.debug = FALSE;
880 options.debug_x11_sync = FALSE;
883 options.verbose = TRUE;
885 #if !defined(PLATFORM_UNIX)
886 if (*options_left == NULL) /* no options given -- enable verbose mode */
887 options.verbose = TRUE;
891 while (*options_left)
893 char option_str[MAX_OPTION_LEN];
894 char *option = options_left[0];
895 char *next_option = options_left[1];
896 char *option_arg = NULL;
897 int option_len = strlen(option);
899 if (option_len >= MAX_OPTION_LEN)
900 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
902 strcpy(option_str, option); /* copy argument into buffer */
905 if (strEqual(option, "--")) /* stop scanning arguments */
908 if (strPrefix(option, "--")) /* treat '--' like '-' */
911 option_arg = strchr(option, '=');
912 if (option_arg == NULL) /* no '=' in option */
913 option_arg = next_option;
916 *option_arg++ = '\0'; /* cut argument from option */
917 if (*option_arg == '\0') /* no argument after '=' */
918 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
921 option_len = strlen(option);
923 if (strEqual(option, "-"))
924 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
925 else if (strncmp(option, "-help", option_len) == 0)
927 print_usage_function();
931 else if (strncmp(option, "-display", option_len) == 0)
933 if (option_arg == NULL)
934 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
936 options.display_name = option_arg;
937 if (option_arg == next_option)
940 else if (strncmp(option, "-basepath", option_len) == 0)
942 if (option_arg == NULL)
943 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
945 /* this should be extended to separate options for ro and rw data */
946 options.ro_base_directory = ro_base_path = option_arg;
947 options.rw_base_directory = rw_base_path = option_arg;
948 if (option_arg == next_option)
951 /* adjust paths for sub-directories in base directory accordingly */
952 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
953 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
954 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
955 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
956 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
958 else if (strncmp(option, "-levels", option_len) == 0)
960 if (option_arg == NULL)
961 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
963 options.level_directory = option_arg;
964 if (option_arg == next_option)
967 else if (strncmp(option, "-graphics", option_len) == 0)
969 if (option_arg == NULL)
970 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
972 options.graphics_directory = option_arg;
973 if (option_arg == next_option)
976 else if (strncmp(option, "-sounds", option_len) == 0)
978 if (option_arg == NULL)
979 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
981 options.sounds_directory = option_arg;
982 if (option_arg == next_option)
985 else if (strncmp(option, "-music", option_len) == 0)
987 if (option_arg == NULL)
988 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
990 options.music_directory = option_arg;
991 if (option_arg == next_option)
994 else if (strncmp(option, "-network", option_len) == 0)
996 options.network = TRUE;
998 else if (strncmp(option, "-serveronly", option_len) == 0)
1000 options.serveronly = TRUE;
1002 else if (strncmp(option, "-verbose", option_len) == 0)
1004 options.verbose = TRUE;
1006 else if (strncmp(option, "-debug", option_len) == 0)
1008 options.debug = TRUE;
1010 else if (strncmp(option, "-debug-x11-sync", option_len) == 0)
1012 options.debug_x11_sync = TRUE;
1014 else if (strPrefix(option, "-D"))
1017 options.special_flags = getStringCopy(&option[2]);
1019 char *flags_string = &option[2];
1020 unsigned int flags_value;
1022 if (*flags_string == '\0')
1023 Error(ERR_EXIT_HELP, "empty flag ignored");
1025 flags_value = get_special_flags_function(flags_string);
1027 if (flags_value == 0)
1028 Error(ERR_EXIT_HELP, "unknown flag '%s'", flags_string);
1030 options.special_flags |= flags_value;
1033 else if (strncmp(option, "-execute", option_len) == 0)
1035 if (option_arg == NULL)
1036 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1038 options.execute_command = option_arg;
1039 if (option_arg == next_option)
1042 /* when doing batch processing, always enable verbose mode (warnings) */
1043 options.verbose = TRUE;
1045 else if (*option == '-')
1047 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1049 else if (options.server_host == NULL)
1051 options.server_host = *options_left;
1053 else if (options.server_port == 0)
1055 options.server_port = atoi(*options_left);
1056 if (options.server_port < 1024)
1057 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1060 Error(ERR_EXIT_HELP, "too many arguments");
1067 /* ------------------------------------------------------------------------- */
1068 /* error handling functions */
1069 /* ------------------------------------------------------------------------- */
1071 #define MAX_INTERNAL_ERROR_SIZE 1024
1073 /* used by SetError() and GetError() to store internal error messages */
1074 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1076 void SetError(char *format, ...)
1080 va_start(ap, format);
1081 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1087 return internal_error;
1090 void Error(int mode, char *format, ...)
1092 static boolean last_line_was_separator = FALSE;
1093 char *process_name = "";
1095 #if defined(PLATFORM_ANDROID)
1096 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1097 mode & ERR_INFO ? ANDROID_LOG_INFO :
1098 mode & ERR_WARN ? ANDROID_LOG_WARN :
1099 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1100 ANDROID_LOG_UNKNOWN);
1104 /* display warnings only when running in verbose mode */
1105 if (mode & ERR_WARN && !options.verbose)
1109 if (mode == ERR_INFO_LINE)
1111 if (!last_line_was_separator)
1112 fprintf_line(program.error_file, format, 79);
1114 last_line_was_separator = TRUE;
1119 last_line_was_separator = FALSE;
1121 if (mode & ERR_SOUND_SERVER)
1122 process_name = " sound server";
1123 else if (mode & ERR_NETWORK_SERVER)
1124 process_name = " network server";
1125 else if (mode & ERR_NETWORK_CLIENT)
1126 process_name = " network client **";
1132 fprintf_nonewline(program.error_file, "%s%s: ", program.command_basename,
1135 if (mode & ERR_WARN)
1136 fprintf_nonewline(program.error_file, "warning: ");
1138 va_start(ap, format);
1139 vfprintf_newline(program.error_file, format, ap);
1142 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1144 va_start(ap, format);
1145 program.exit_message_function(format, ap);
1150 if (mode & ERR_HELP)
1151 fprintf_newline(program.error_file,
1152 "%s: Try option '--help' for more information.",
1153 program.command_basename);
1155 if (mode & ERR_EXIT)
1156 fprintf_newline(program.error_file, "%s%s: aborting",
1157 program.command_basename, process_name);
1159 if (mode & ERR_EXIT)
1161 if (mode & ERR_FROM_SERVER)
1162 exit(1); /* child process: normal exit */
1164 program.exit_function(1); /* main process: clean up stuff */
1169 /* ------------------------------------------------------------------------- */
1170 /* checked memory allocation and freeing functions */
1171 /* ------------------------------------------------------------------------- */
1173 void *checked_malloc(unsigned int size)
1180 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1185 void *checked_calloc(unsigned int size)
1189 ptr = calloc(1, size);
1192 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1197 void *checked_realloc(void *ptr, unsigned int size)
1199 ptr = realloc(ptr, size);
1202 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1207 void checked_free(void *ptr)
1209 if (ptr != NULL) /* this check should be done by free() anyway */
1213 void clear_mem(void *ptr, unsigned int size)
1215 #if defined(PLATFORM_WIN32)
1216 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1217 char *cptr = (char *)ptr;
1222 memset(ptr, 0, size);
1227 /* ------------------------------------------------------------------------- */
1228 /* various helper functions */
1229 /* ------------------------------------------------------------------------- */
1231 inline void swap_numbers(int *i1, int *i2)
1239 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1251 /* the "put" variants of the following file access functions check for the file
1252 pointer being != NULL and return the number of bytes they have or would have
1253 written; this allows for chunk writing functions to first determine the size
1254 of the (not yet written) chunk, write the correct chunk size and finally
1255 write the chunk itself */
1259 int getFile8BitInteger(File *file)
1261 return getByteFromFile(file);
1266 int getFile8BitInteger(FILE *file)
1273 int putFile8BitInteger(FILE *file, int value)
1283 int getFile16BitInteger(File *file, int byte_order)
1285 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1286 return ((getByteFromFile(file) << 8) |
1287 (getByteFromFile(file) << 0));
1288 else /* BYTE_ORDER_LITTLE_ENDIAN */
1289 return ((getByteFromFile(file) << 0) |
1290 (getByteFromFile(file) << 8));
1295 int getFile16BitInteger(FILE *file, int byte_order)
1297 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1298 return ((fgetc(file) << 8) |
1299 (fgetc(file) << 0));
1300 else /* BYTE_ORDER_LITTLE_ENDIAN */
1301 return ((fgetc(file) << 0) |
1302 (fgetc(file) << 8));
1307 int putFile16BitInteger(FILE *file, int value, int byte_order)
1311 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1313 fputc((value >> 8) & 0xff, file);
1314 fputc((value >> 0) & 0xff, file);
1316 else /* BYTE_ORDER_LITTLE_ENDIAN */
1318 fputc((value >> 0) & 0xff, file);
1319 fputc((value >> 8) & 0xff, file);
1328 int getFile32BitInteger(File *file, int byte_order)
1330 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1331 return ((getByteFromFile(file) << 24) |
1332 (getByteFromFile(file) << 16) |
1333 (getByteFromFile(file) << 8) |
1334 (getByteFromFile(file) << 0));
1335 else /* BYTE_ORDER_LITTLE_ENDIAN */
1336 return ((getByteFromFile(file) << 0) |
1337 (getByteFromFile(file) << 8) |
1338 (getByteFromFile(file) << 16) |
1339 (getByteFromFile(file) << 24));
1344 int getFile32BitInteger(FILE *file, int byte_order)
1346 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1347 return ((fgetc(file) << 24) |
1348 (fgetc(file) << 16) |
1349 (fgetc(file) << 8) |
1350 (fgetc(file) << 0));
1351 else /* BYTE_ORDER_LITTLE_ENDIAN */
1352 return ((fgetc(file) << 0) |
1353 (fgetc(file) << 8) |
1354 (fgetc(file) << 16) |
1355 (fgetc(file) << 24));
1360 int putFile32BitInteger(FILE *file, int value, int byte_order)
1364 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1366 fputc((value >> 24) & 0xff, file);
1367 fputc((value >> 16) & 0xff, file);
1368 fputc((value >> 8) & 0xff, file);
1369 fputc((value >> 0) & 0xff, file);
1371 else /* BYTE_ORDER_LITTLE_ENDIAN */
1373 fputc((value >> 0) & 0xff, file);
1374 fputc((value >> 8) & 0xff, file);
1375 fputc((value >> 16) & 0xff, file);
1376 fputc((value >> 24) & 0xff, file);
1385 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1388 const int chunk_name_length = 4;
1390 /* read chunk name */
1391 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1394 if (chunk_size != NULL)
1396 /* read chunk size */
1397 *chunk_size = getFile32BitInteger(file, byte_order);
1400 return (checkEndOfFile(file) ? FALSE : TRUE);
1405 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
1408 const int chunk_name_length = 4;
1410 /* read chunk name */
1411 if (fgets(chunk_name, chunk_name_length + 1, file) == NULL)
1414 if (chunk_size != NULL)
1416 /* read chunk size */
1417 *chunk_size = getFile32BitInteger(file, byte_order);
1420 return (feof(file) || ferror(file) ? FALSE : TRUE);
1425 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1430 /* write chunk name */
1432 fputs(chunk_name, file);
1434 num_bytes += strlen(chunk_name);
1436 if (chunk_size >= 0)
1438 /* write chunk size */
1440 putFile32BitInteger(file, chunk_size, byte_order);
1450 int getFileVersion(File *file)
1452 int version_major = getByteFromFile(file);
1453 int version_minor = getByteFromFile(file);
1454 int version_patch = getByteFromFile(file);
1455 int version_build = getByteFromFile(file);
1457 return VERSION_IDENT(version_major, version_minor, version_patch,
1463 int getFileVersion(FILE *file)
1465 int version_major = fgetc(file);
1466 int version_minor = fgetc(file);
1467 int version_patch = fgetc(file);
1468 int version_build = fgetc(file);
1470 return VERSION_IDENT(version_major, version_minor, version_patch,
1476 int putFileVersion(FILE *file, int version)
1480 int version_major = VERSION_MAJOR(version);
1481 int version_minor = VERSION_MINOR(version);
1482 int version_patch = VERSION_PATCH(version);
1483 int version_build = VERSION_BUILD(version);
1485 fputc(version_major, file);
1486 fputc(version_minor, file);
1487 fputc(version_patch, file);
1488 fputc(version_build, file);
1496 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1500 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1501 buffer[i] = getByteFromFile(file);
1506 void ReadBytesFromFile(FILE *file, byte *buffer, unsigned int bytes)
1510 for(i = 0; i < bytes && !feof(file); i++)
1511 buffer[i] = fgetc(file);
1516 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1520 for(i = 0; i < bytes; i++)
1521 fputc(buffer[i], file);
1526 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1528 while (bytes-- && !checkEndOfFile(file))
1529 getByteFromFile(file);
1534 void ReadUnusedBytesFromFile(FILE *file, unsigned int bytes)
1536 while (bytes-- && !feof(file))
1542 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1549 /* ------------------------------------------------------------------------- */
1550 /* functions to translate key identifiers between different format */
1551 /* ------------------------------------------------------------------------- */
1553 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1554 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1555 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1556 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1558 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1567 /* normal cursor keys */
1568 { KSYM_Left, "XK_Left", "cursor left" },
1569 { KSYM_Right, "XK_Right", "cursor right" },
1570 { KSYM_Up, "XK_Up", "cursor up" },
1571 { KSYM_Down, "XK_Down", "cursor down" },
1573 /* keypad cursor keys */
1575 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1576 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1577 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1578 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1581 /* other keypad keys */
1582 #ifdef KSYM_KP_Enter
1583 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1584 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1585 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1586 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1587 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1588 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1592 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1593 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1594 { KSYM_Control_L, "XK_Control_L", "left control" },
1595 { KSYM_Control_R, "XK_Control_R", "right control" },
1596 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1597 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1598 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1599 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1600 #if !defined(TARGET_SDL2)
1601 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1602 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1604 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1605 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1607 /* some special keys */
1608 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1609 { KSYM_Delete, "XK_Delete", "delete" },
1610 { KSYM_Insert, "XK_Insert", "insert" },
1611 { KSYM_Tab, "XK_Tab", "tab" },
1612 { KSYM_Home, "XK_Home", "home" },
1613 { KSYM_End, "XK_End", "end" },
1614 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1615 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1617 #if defined(TARGET_SDL2)
1618 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1619 { KSYM_Back, "XK_Back", "back" }, /* back key */
1622 /* ASCII 0x20 to 0x40 keys (except numbers) */
1623 { KSYM_space, "XK_space", "space" },
1624 { KSYM_exclam, "XK_exclam", "!" },
1625 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1626 { KSYM_numbersign, "XK_numbersign", "#" },
1627 { KSYM_dollar, "XK_dollar", "$" },
1628 { KSYM_percent, "XK_percent", "%" },
1629 { KSYM_ampersand, "XK_ampersand", "&" },
1630 { KSYM_apostrophe, "XK_apostrophe", "'" },
1631 { KSYM_parenleft, "XK_parenleft", "(" },
1632 { KSYM_parenright, "XK_parenright", ")" },
1633 { KSYM_asterisk, "XK_asterisk", "*" },
1634 { KSYM_plus, "XK_plus", "+" },
1635 { KSYM_comma, "XK_comma", "," },
1636 { KSYM_minus, "XK_minus", "-" },
1637 { KSYM_period, "XK_period", "." },
1638 { KSYM_slash, "XK_slash", "/" },
1639 { KSYM_colon, "XK_colon", ":" },
1640 { KSYM_semicolon, "XK_semicolon", ";" },
1641 { KSYM_less, "XK_less", "<" },
1642 { KSYM_equal, "XK_equal", "=" },
1643 { KSYM_greater, "XK_greater", ">" },
1644 { KSYM_question, "XK_question", "?" },
1645 { KSYM_at, "XK_at", "@" },
1647 /* more ASCII keys */
1648 { KSYM_bracketleft, "XK_bracketleft", "[" },
1649 { KSYM_backslash, "XK_backslash", "\\" },
1650 { KSYM_bracketright,"XK_bracketright", "]" },
1651 { KSYM_asciicircum, "XK_asciicircum", "^" },
1652 { KSYM_underscore, "XK_underscore", "_" },
1653 { KSYM_grave, "XK_grave", "grave" },
1654 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1655 { KSYM_braceleft, "XK_braceleft", "brace left" },
1656 { KSYM_bar, "XK_bar", "bar" },
1657 { KSYM_braceright, "XK_braceright", "brace right" },
1658 { KSYM_asciitilde, "XK_asciitilde", "~" },
1660 /* special (non-ASCII) keys (ISO-Latin-1) */
1661 { KSYM_degree, "XK_degree", "°" },
1662 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
1663 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
1664 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
1665 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
1666 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
1667 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
1668 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1670 #if defined(TARGET_SDL2)
1671 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1672 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1673 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1674 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1675 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1676 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1677 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1678 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1679 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1681 /* other keys (for reverse mapping only) */
1682 { KSYM_space, "XK_space", " " },
1685 #if defined(TARGET_SDL2)
1686 /* keypad keys are not in numerical order in SDL2 */
1687 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1688 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1689 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1690 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1691 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1692 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1693 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1694 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1695 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1696 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1699 /* end-of-array identifier */
1705 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1707 static char name_buffer[30];
1710 if (key >= KSYM_A && key <= KSYM_Z)
1711 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1712 else if (key >= KSYM_a && key <= KSYM_z)
1713 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1714 else if (key >= KSYM_0 && key <= KSYM_9)
1715 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1716 #if !defined(TARGET_SDL2)
1717 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1718 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1720 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1721 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1722 else if (key == KSYM_UNDEFINED)
1723 strcpy(name_buffer, "(undefined)");
1730 if (key == translate_key[i].key)
1732 strcpy(name_buffer, translate_key[i].name);
1736 while (translate_key[++i].name);
1738 if (!translate_key[i].name)
1739 strcpy(name_buffer, "(unknown)");
1742 *name = name_buffer;
1744 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1746 static char name_buffer[30];
1749 if (key >= KSYM_A && key <= KSYM_Z)
1750 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1751 else if (key >= KSYM_a && key <= KSYM_z)
1752 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1753 else if (key >= KSYM_0 && key <= KSYM_9)
1754 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1755 #if !defined(TARGET_SDL2)
1756 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1757 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1759 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1760 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1761 else if (key == KSYM_UNDEFINED)
1762 strcpy(name_buffer, "[undefined]");
1769 if (key == translate_key[i].key)
1771 strcpy(name_buffer, translate_key[i].x11name);
1775 while (translate_key[++i].x11name);
1777 if (!translate_key[i].x11name)
1778 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1781 *x11name = name_buffer;
1783 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1785 Key key = KSYM_UNDEFINED;
1786 char *name_ptr = *name;
1788 if (strlen(*name) == 1)
1790 char c = name_ptr[0];
1792 if (c >= 'A' && c <= 'Z')
1793 key = KSYM_A + (Key)(c - 'A');
1794 else if (c >= 'a' && c <= 'z')
1795 key = KSYM_a + (Key)(c - 'a');
1796 else if (c >= '0' && c <= '9')
1797 key = KSYM_0 + (Key)(c - '0');
1800 if (key == KSYM_UNDEFINED)
1806 if (strEqual(translate_key[i].name, *name))
1808 key = translate_key[i].key;
1812 while (translate_key[++i].x11name);
1815 if (key == KSYM_UNDEFINED)
1816 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1820 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1822 Key key = KSYM_UNDEFINED;
1823 char *name_ptr = *x11name;
1825 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1827 char c = name_ptr[3];
1829 if (c >= 'A' && c <= 'Z')
1830 key = KSYM_A + (Key)(c - 'A');
1831 else if (c >= 'a' && c <= 'z')
1832 key = KSYM_a + (Key)(c - 'a');
1833 else if (c >= '0' && c <= '9')
1834 key = KSYM_0 + (Key)(c - '0');
1836 #if !defined(TARGET_SDL2)
1837 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1839 char c = name_ptr[6];
1841 if (c >= '0' && c <= '9')
1842 key = KSYM_KP_0 + (Key)(c - '0');
1845 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1847 char c1 = name_ptr[4];
1848 char c2 = name_ptr[5];
1851 if ((c1 >= '0' && c1 <= '9') &&
1852 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1853 d = atoi(&name_ptr[4]);
1855 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1856 key = KSYM_F1 + (Key)(d - 1);
1858 else if (strPrefix(name_ptr, "XK_"))
1864 if (strEqual(name_ptr, translate_key[i].x11name))
1866 key = translate_key[i].key;
1870 while (translate_key[++i].x11name);
1872 else if (strPrefix(name_ptr, "0x"))
1874 unsigned int value = 0;
1880 char c = *name_ptr++;
1883 if (c >= '0' && c <= '9')
1885 else if (c >= 'a' && c <= 'f')
1886 d = (int)(c - 'a' + 10);
1887 else if (c >= 'A' && c <= 'F')
1888 d = (int)(c - 'A' + 10);
1896 value = value * 16 + d;
1907 char *getKeyNameFromKey(Key key)
1911 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1915 char *getX11KeyNameFromKey(Key key)
1919 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1923 Key getKeyFromKeyName(char *name)
1927 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1931 Key getKeyFromX11KeyName(char *x11name)
1935 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1939 char getCharFromKey(Key key)
1941 char *keyname = getKeyNameFromKey(key);
1944 if (strlen(keyname) == 1)
1946 else if (strEqual(keyname, "space"))
1952 char getValidConfigValueChar(char c)
1954 if (c == '#' || /* used to mark comments */
1955 c == '\\') /* used to mark continued lines */
1962 /* ------------------------------------------------------------------------- */
1963 /* functions to translate string identifiers to integer or boolean value */
1964 /* ------------------------------------------------------------------------- */
1966 int get_integer_from_string(char *s)
1968 static char *number_text[][3] =
1970 { "0", "zero", "null", },
1971 { "1", "one", "first" },
1972 { "2", "two", "second" },
1973 { "3", "three", "third" },
1974 { "4", "four", "fourth" },
1975 { "5", "five", "fifth" },
1976 { "6", "six", "sixth" },
1977 { "7", "seven", "seventh" },
1978 { "8", "eight", "eighth" },
1979 { "9", "nine", "ninth" },
1980 { "10", "ten", "tenth" },
1981 { "11", "eleven", "eleventh" },
1982 { "12", "twelve", "twelfth" },
1984 { NULL, NULL, NULL },
1988 char *s_lower = getStringToLower(s);
1991 for (i = 0; number_text[i][0] != NULL; i++)
1992 for (j = 0; j < 3; j++)
1993 if (strEqual(s_lower, number_text[i][j]))
1998 if (strEqual(s_lower, "false") ||
1999 strEqual(s_lower, "no") ||
2000 strEqual(s_lower, "off"))
2002 else if (strEqual(s_lower, "true") ||
2003 strEqual(s_lower, "yes") ||
2004 strEqual(s_lower, "on"))
2015 boolean get_boolean_from_string(char *s)
2017 char *s_lower = getStringToLower(s);
2018 boolean result = FALSE;
2020 if (strEqual(s_lower, "true") ||
2021 strEqual(s_lower, "yes") ||
2022 strEqual(s_lower, "on") ||
2023 get_integer_from_string(s) == 1)
2031 int get_switch3_from_string(char *s)
2033 char *s_lower = getStringToLower(s);
2036 if (strEqual(s_lower, "true") ||
2037 strEqual(s_lower, "yes") ||
2038 strEqual(s_lower, "on") ||
2039 get_integer_from_string(s) == 1)
2041 else if (strEqual(s_lower, "auto"))
2050 /* ------------------------------------------------------------------------- */
2051 /* functions for generic lists */
2052 /* ------------------------------------------------------------------------- */
2054 ListNode *newListNode()
2056 return checked_calloc(sizeof(ListNode));
2059 void addNodeToList(ListNode **node_first, char *key, void *content)
2061 ListNode *node_new = newListNode();
2063 node_new->key = getStringCopy(key);
2064 node_new->content = content;
2065 node_new->next = *node_first;
2066 *node_first = node_new;
2069 void deleteNodeFromList(ListNode **node_first, char *key,
2070 void (*destructor_function)(void *))
2072 if (node_first == NULL || *node_first == NULL)
2075 if (strEqual((*node_first)->key, key))
2077 checked_free((*node_first)->key);
2078 if (destructor_function)
2079 destructor_function((*node_first)->content);
2080 *node_first = (*node_first)->next;
2083 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2086 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2088 if (node_first == NULL)
2091 if (strEqual(node_first->key, key))
2094 return getNodeFromKey(node_first->next, key);
2097 int getNumNodes(ListNode *node_first)
2099 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2102 void dumpList(ListNode *node_first)
2104 ListNode *node = node_first;
2108 printf("['%s' (%d)]\n", node->key,
2109 ((struct ListNodeInfo *)node->content)->num_references);
2113 printf("[%d nodes]\n", getNumNodes(node_first));
2117 /* ------------------------------------------------------------------------- */
2118 /* functions for file handling */
2119 /* ------------------------------------------------------------------------- */
2121 File *openFile(char *filename, char *mode)
2123 File *file = checked_calloc(sizeof(File));
2125 file->file = fopen(filename, mode);
2127 if (file->file != NULL)
2129 file->filename = getStringCopy(filename);
2134 #if defined(PLATFORM_ANDROID)
2135 file->asset_file = SDL_RWFromFile(filename, mode);
2137 if (file->asset_file != NULL)
2139 file->file_is_asset = TRUE;
2140 file->filename = getStringCopy(filename);
2151 int closeFile(File *file)
2158 #if defined(PLATFORM_ANDROID)
2159 if (file->asset_file)
2160 result = SDL_RWclose(file->asset_file);
2164 result = fclose(file->file);
2166 checked_free(file->filename);
2172 int checkEndOfFile(File *file)
2174 #if defined(PLATFORM_ANDROID)
2175 if (file->file_is_asset)
2176 return file->end_of_file;
2179 return feof(file->file);
2182 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2184 #if defined(PLATFORM_ANDROID)
2185 if (file->file_is_asset)
2187 if (file->end_of_file)
2190 size_t num_items_read =
2191 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2193 if (num_items_read < num_items)
2194 file->end_of_file = TRUE;
2196 return num_items_read;
2200 return fread(buffer, item_size, num_items, file->file);
2203 int seekFile(File *file, long offset, int whence)
2205 #if defined(PLATFORM_ANDROID)
2206 if (file->file_is_asset)
2208 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2209 whence == SEEK_CUR ? RW_SEEK_CUR :
2210 whence == SEEK_END ? RW_SEEK_END : 0);
2212 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2216 return fseek(file->file, offset, whence);
2219 int getByteFromFile(File *file)
2221 #if defined(PLATFORM_ANDROID)
2222 if (file->file_is_asset)
2224 if (file->end_of_file)
2228 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2230 if (num_bytes_read < 1)
2231 file->end_of_file = TRUE;
2233 return (file->end_of_file ? EOF : (int)c);
2237 return fgetc(file->file);
2240 char *getStringFromFile(File *file, char *line, int size)
2242 #if defined(PLATFORM_ANDROID)
2243 if (file->file_is_asset)
2245 if (file->end_of_file)
2248 char *line_ptr = line;
2249 int num_bytes_read = 0;
2251 while (num_bytes_read < size - 1 &&
2252 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2253 *line_ptr++ != '\n')
2258 if (strlen(line) == 0)
2260 file->end_of_file = TRUE;
2269 return fgets(line, size, file->file);
2273 /* ------------------------------------------------------------------------- */
2274 /* functions for directory handling */
2275 /* ------------------------------------------------------------------------- */
2277 Directory *openDirectory(char *dir_name)
2279 Directory *dir = checked_calloc(sizeof(Directory));
2281 dir->dir = opendir(dir_name);
2283 if (dir->dir != NULL)
2285 dir->filename = getStringCopy(dir_name);
2290 #if defined(PLATFORM_ANDROID)
2291 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2293 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2295 checked_free(asset_toc_filename);
2297 if (dir->asset_toc_file != NULL)
2299 dir->directory_is_asset = TRUE;
2300 dir->filename = getStringCopy(dir_name);
2311 int closeDirectory(Directory *dir)
2318 #if defined(PLATFORM_ANDROID)
2319 if (dir->asset_toc_file)
2320 result = SDL_RWclose(dir->asset_toc_file);
2324 result = closedir(dir->dir);
2327 freeDirectoryEntry(dir->dir_entry);
2329 checked_free(dir->filename);
2335 DirectoryEntry *readDirectory(Directory *dir)
2338 freeDirectoryEntry(dir->dir_entry);
2340 dir->dir_entry = NULL;
2342 #if defined(PLATFORM_ANDROID)
2343 if (dir->directory_is_asset)
2345 char line[MAX_LINE_LEN];
2346 char *line_ptr = line;
2347 int num_bytes_read = 0;
2349 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2350 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2359 if (strlen(line) == 0)
2362 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2364 dir->dir_entry->is_directory = FALSE;
2365 if (line[strlen(line) - 1] == '/')
2367 dir->dir_entry->is_directory = TRUE;
2369 line[strlen(line) - 1] = '\0';
2372 dir->dir_entry->basename = getStringCopy(line);
2373 dir->dir_entry->filename = getPath2(dir->filename, line);
2375 return dir->dir_entry;
2379 struct dirent *dir_entry = readdir(dir->dir);
2381 if (dir_entry == NULL)
2384 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2386 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2387 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2389 struct stat file_status;
2391 dir->dir_entry->is_directory =
2392 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2393 (file_status.st_mode & S_IFMT) == S_IFDIR);
2396 Error(ERR_INFO, "::: '%s' is directory: %d",
2397 dir->dir_entry->basename,
2398 dir->dir_entry->is_directory);
2401 return dir->dir_entry;
2404 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2406 if (dir_entry == NULL)
2409 checked_free(dir_entry->basename);
2410 checked_free(dir_entry->filename);
2411 checked_free(dir_entry);
2415 /* ------------------------------------------------------------------------- */
2416 /* functions for checking files and filenames */
2417 /* ------------------------------------------------------------------------- */
2419 boolean directoryExists(char *dir_name)
2421 if (dir_name == NULL)
2424 boolean success = (access(dir_name, F_OK) == 0);
2426 #if defined(PLATFORM_ANDROID)
2429 // this might be an asset directory; check by trying to open toc file
2430 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2431 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2433 checked_free(asset_toc_filename);
2435 success = (file != NULL);
2445 boolean fileExists(char *filename)
2447 if (filename == NULL)
2450 boolean success = (access(filename, F_OK) == 0);
2452 #if defined(PLATFORM_ANDROID)
2455 // this might be an asset file; check by trying to open it
2456 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2458 success = (file != NULL);
2468 boolean fileHasPrefix(char *basename, char *prefix)
2470 static char *basename_lower = NULL;
2471 int basename_length, prefix_length;
2473 checked_free(basename_lower);
2475 if (basename == NULL || prefix == NULL)
2478 basename_lower = getStringToLower(basename);
2479 basename_length = strlen(basename_lower);
2480 prefix_length = strlen(prefix);
2482 if (basename_length > prefix_length + 1 &&
2483 basename_lower[prefix_length] == '.' &&
2484 strncmp(basename_lower, prefix, prefix_length) == 0)
2490 boolean fileHasSuffix(char *basename, char *suffix)
2492 static char *basename_lower = NULL;
2493 int basename_length, suffix_length;
2495 checked_free(basename_lower);
2497 if (basename == NULL || suffix == NULL)
2500 basename_lower = getStringToLower(basename);
2501 basename_length = strlen(basename_lower);
2502 suffix_length = strlen(suffix);
2504 if (basename_length > suffix_length + 1 &&
2505 basename_lower[basename_length - suffix_length - 1] == '.' &&
2506 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2512 #if defined(TARGET_SDL)
2513 static boolean FileCouldBeArtwork(char *basename)
2515 return (!strEqual(basename, ".") &&
2516 !strEqual(basename, "..") &&
2517 !fileHasSuffix(basename, "txt") &&
2518 !fileHasSuffix(basename, "conf"));
2522 boolean FileIsGraphic(char *filename)
2524 char *basename = getBaseNamePtr(filename);
2526 #if defined(TARGET_SDL)
2527 return FileCouldBeArtwork(basename);
2529 return fileHasSuffix(basename, "pcx");
2533 boolean FileIsSound(char *filename)
2535 char *basename = getBaseNamePtr(filename);
2537 #if defined(TARGET_SDL)
2538 return FileCouldBeArtwork(basename);
2540 return fileHasSuffix(basename, "wav");
2544 boolean FileIsMusic(char *filename)
2546 char *basename = getBaseNamePtr(filename);
2548 #if defined(TARGET_SDL)
2549 return FileCouldBeArtwork(basename);
2551 if (FileIsSound(basename))
2555 #if defined(TARGET_SDL)
2556 if ((fileHasPrefix(basename, "mod") && !fileHasSuffix(basename, "txt")) ||
2557 fileHasSuffix(basename, "mod") ||
2558 fileHasSuffix(basename, "s3m") ||
2559 fileHasSuffix(basename, "it") ||
2560 fileHasSuffix(basename, "xm") ||
2561 fileHasSuffix(basename, "midi") ||
2562 fileHasSuffix(basename, "mid") ||
2563 fileHasSuffix(basename, "mp3") ||
2564 fileHasSuffix(basename, "ogg"))
2573 boolean FileIsArtworkType(char *basename, int type)
2575 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
2576 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
2577 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
2583 /* ------------------------------------------------------------------------- */
2584 /* functions for loading artwork configuration information */
2585 /* ------------------------------------------------------------------------- */
2587 char *get_mapped_token(char *token)
2589 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2590 static char *map_token_prefix[][2] =
2592 { "char_procent", "char_percent" },
2597 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2599 int len_token_prefix = strlen(map_token_prefix[i][0]);
2601 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2602 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2608 /* This function checks if a string <s> of the format "string1, string2, ..."
2609 exactly contains a string <s_contained>. */
2611 static boolean string_has_parameter(char *s, char *s_contained)
2615 if (s == NULL || s_contained == NULL)
2618 if (strlen(s_contained) > strlen(s))
2621 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2623 char next_char = s[strlen(s_contained)];
2625 /* check if next character is delimiter or whitespace */
2626 return (next_char == ',' || next_char == '\0' ||
2627 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2630 /* check if string contains another parameter string after a comma */
2631 substring = strchr(s, ',');
2632 if (substring == NULL) /* string does not contain a comma */
2635 /* advance string pointer to next character after the comma */
2638 /* skip potential whitespaces after the comma */
2639 while (*substring == ' ' || *substring == '\t')
2642 return string_has_parameter(substring, s_contained);
2645 int get_parameter_value(char *value_raw, char *suffix, int type)
2647 char *value = getStringToLower(value_raw);
2648 int result = 0; /* probably a save default value */
2650 if (strEqual(suffix, ".direction"))
2652 result = (strEqual(value, "left") ? MV_LEFT :
2653 strEqual(value, "right") ? MV_RIGHT :
2654 strEqual(value, "up") ? MV_UP :
2655 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2657 else if (strEqual(suffix, ".align"))
2659 result = (strEqual(value, "left") ? ALIGN_LEFT :
2660 strEqual(value, "right") ? ALIGN_RIGHT :
2661 strEqual(value, "center") ? ALIGN_CENTER :
2662 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2664 else if (strEqual(suffix, ".valign"))
2666 result = (strEqual(value, "top") ? VALIGN_TOP :
2667 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2668 strEqual(value, "middle") ? VALIGN_MIDDLE :
2669 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2671 else if (strEqual(suffix, ".anim_mode"))
2673 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2674 string_has_parameter(value, "loop") ? ANIM_LOOP :
2675 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2676 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2677 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2678 string_has_parameter(value, "random") ? ANIM_RANDOM :
2679 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2680 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2681 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2682 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2683 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2684 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2687 if (string_has_parameter(value, "reverse"))
2688 result |= ANIM_REVERSE;
2690 if (string_has_parameter(value, "opaque_player"))
2691 result |= ANIM_OPAQUE_PLAYER;
2693 if (string_has_parameter(value, "static_panel"))
2694 result |= ANIM_STATIC_PANEL;
2696 else if (strEqual(suffix, ".class"))
2698 result = get_hash_from_key(value);
2700 else if (strEqual(suffix, ".style"))
2702 result = STYLE_DEFAULT;
2704 if (string_has_parameter(value, "accurate_borders"))
2705 result |= STYLE_ACCURATE_BORDERS;
2707 if (string_has_parameter(value, "inner_corners"))
2708 result |= STYLE_INNER_CORNERS;
2710 else if (strEqual(suffix, ".fade_mode"))
2712 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2713 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2714 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2715 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2719 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2721 else if (strEqualN(suffix, ".font", 5)) /* (may also be ".font_xyz") */
2724 result = gfx.get_font_from_token_function(value);
2726 else /* generic parameter of type integer or boolean */
2728 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2729 type == TYPE_INTEGER ? get_integer_from_string(value) :
2730 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2731 ARG_UNDEFINED_VALUE);
2739 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2741 static struct ScreenModeInfo screen_mode;
2742 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2743 char *screen_mode_string_copy;
2744 char *screen_mode_string_pos_w;
2745 char *screen_mode_string_pos_h;
2747 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2750 screen_mode_string_copy = getStringCopy(screen_mode_string);
2752 screen_mode_string_pos_w = screen_mode_string_copy;
2753 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2754 *screen_mode_string_pos_h++ = '\0';
2756 screen_mode.width = atoi(screen_mode_string_pos_w);
2757 screen_mode.height = atoi(screen_mode_string_pos_h);
2759 return &screen_mode;
2762 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2765 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2766 float aspect_ratio_new;
2771 *x = i * aspect_ratio + 0.000001;
2774 aspect_ratio_new = (float)*x / (float)*y;
2778 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2781 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2782 struct ListNodeInfo ***, int *);
2784 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2785 struct ConfigTypeInfo *suffix_list,
2786 char **ignore_tokens,
2787 int num_file_list_entries)
2789 struct FileInfo *file_list;
2790 int num_file_list_entries_found = 0;
2791 int num_suffix_list_entries = 0;
2795 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2797 for (i = 0; suffix_list[i].token != NULL; i++)
2798 num_suffix_list_entries++;
2800 /* always start with reliable default values */
2801 for (i = 0; i < num_file_list_entries; i++)
2803 file_list[i].token = NULL;
2805 file_list[i].default_filename = NULL;
2806 file_list[i].filename = NULL;
2808 if (num_suffix_list_entries > 0)
2810 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2812 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2813 file_list[i].parameter = checked_calloc(parameter_array_size);
2815 for (j = 0; j < num_suffix_list_entries; j++)
2817 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2818 setString(&file_list[i].parameter[j], suffix_list[j].value);
2821 file_list[i].redefined = FALSE;
2822 file_list[i].fallback_to_default = FALSE;
2823 file_list[i].default_is_cloned = FALSE;
2829 for (i = 0; config_list[i].token != NULL; i++)
2831 int len_config_token = strlen(config_list[i].token);
2833 int len_config_value = strlen(config_list[i].value);
2835 boolean is_file_entry = TRUE;
2837 for (j = 0; suffix_list[j].token != NULL; j++)
2839 int len_suffix = strlen(suffix_list[j].token);
2841 if (len_suffix < len_config_token &&
2842 strEqual(&config_list[i].token[len_config_token - len_suffix],
2843 suffix_list[j].token))
2845 setString(&file_list[list_pos].default_parameter[j],
2846 config_list[i].value);
2848 is_file_entry = FALSE;
2854 /* the following tokens are no file definitions, but other config tokens */
2855 for (j = 0; ignore_tokens[j] != NULL; j++)
2856 if (strEqual(config_list[i].token, ignore_tokens[j]))
2857 is_file_entry = FALSE;
2864 if (list_pos >= num_file_list_entries)
2868 /* simple sanity check if this is really a file definition */
2869 if (!strEqual(&config_list[i].value[len_config_value - 4], ".pcx") &&
2870 !strEqual(&config_list[i].value[len_config_value - 4], ".wav") &&
2871 !strEqual(config_list[i].value, UNDEFINED_FILENAME))
2873 Error(ERR_INFO, "Configuration directive '%s' -> '%s':",
2874 config_list[i].token, config_list[i].value);
2875 Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
2879 file_list[list_pos].token = config_list[i].token;
2880 file_list[list_pos].default_filename = config_list[i].value;
2883 printf("::: '%s' => '%s'\n", config_list[i].token, config_list[i].value);
2887 if (strSuffix(config_list[i].token, ".clone_from"))
2888 file_list[list_pos].default_is_cloned = TRUE;
2891 num_file_list_entries_found = list_pos + 1;
2892 if (num_file_list_entries_found != num_file_list_entries)
2894 Error(ERR_INFO_LINE, "-");
2895 Error(ERR_INFO, "inconsistant config list information:");
2896 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2897 num_file_list_entries);
2898 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2899 num_file_list_entries_found);
2900 Error(ERR_EXIT, "please fix");
2904 printf("::: ---------- DONE ----------\n");
2910 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2912 int len_token = strlen(token);
2913 int len_suffix = strlen(suffix);
2915 if (start_pos < 0) /* compare suffix from end of string */
2916 start_pos += len_token;
2918 if (start_pos < 0 || start_pos + len_suffix > len_token)
2921 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2924 if (token[start_pos + len_suffix] == '\0')
2927 if (token[start_pos + len_suffix] == '.')
2933 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2935 static void read_token_parameters(SetupFileHash *setup_file_hash,
2936 struct ConfigTypeInfo *suffix_list,
2937 struct FileInfo *file_list_entry)
2939 /* check for config token that is the base token without any suffixes */
2940 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2941 char *known_token_value = KNOWN_TOKEN_VALUE;
2944 if (filename != NULL)
2946 setString(&file_list_entry->filename, filename);
2948 /* when file definition found, set all parameters to default values */
2949 for (i = 0; suffix_list[i].token != NULL; i++)
2950 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2952 file_list_entry->redefined = TRUE;
2954 /* mark config file token as well known from default config */
2955 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2958 /* check for config tokens that can be build by base token and suffixes */
2959 for (i = 0; suffix_list[i].token != NULL; i++)
2961 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2962 char *value = getHashEntry(setup_file_hash, token);
2966 setString(&file_list_entry->parameter[i], value);
2968 /* mark config file token as well known from default config */
2969 setHashEntry(setup_file_hash, token, known_token_value);
2976 static void add_dynamic_file_list_entry(struct FileInfo **list,
2977 int *num_list_entries,
2978 SetupFileHash *extra_file_hash,
2979 struct ConfigTypeInfo *suffix_list,
2980 int num_suffix_list_entries,
2983 struct FileInfo *new_list_entry;
2984 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2986 (*num_list_entries)++;
2987 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2988 new_list_entry = &(*list)[*num_list_entries - 1];
2990 new_list_entry->token = getStringCopy(token);
2991 new_list_entry->default_filename = NULL;
2992 new_list_entry->filename = NULL;
2993 new_list_entry->parameter = checked_calloc(parameter_array_size);
2995 new_list_entry->redefined = FALSE;
2996 new_list_entry->fallback_to_default = FALSE;
2997 new_list_entry->default_is_cloned = FALSE;
2999 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3002 static void add_property_mapping(struct PropertyMapping **list,
3003 int *num_list_entries,
3004 int base_index, int ext1_index,
3005 int ext2_index, int ext3_index,
3008 struct PropertyMapping *new_list_entry;
3010 (*num_list_entries)++;
3011 *list = checked_realloc(*list,
3012 *num_list_entries * sizeof(struct PropertyMapping));
3013 new_list_entry = &(*list)[*num_list_entries - 1];
3015 new_list_entry->base_index = base_index;
3016 new_list_entry->ext1_index = ext1_index;
3017 new_list_entry->ext2_index = ext2_index;
3018 new_list_entry->ext3_index = ext3_index;
3020 new_list_entry->artwork_index = artwork_index;
3023 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3026 struct FileInfo *file_list = artwork_info->file_list;
3027 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3028 char **base_prefixes = artwork_info->base_prefixes;
3029 char **ext1_suffixes = artwork_info->ext1_suffixes;
3030 char **ext2_suffixes = artwork_info->ext2_suffixes;
3031 char **ext3_suffixes = artwork_info->ext3_suffixes;
3032 char **ignore_tokens = artwork_info->ignore_tokens;
3033 int num_file_list_entries = artwork_info->num_file_list_entries;
3034 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3035 int num_base_prefixes = artwork_info->num_base_prefixes;
3036 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3037 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3038 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3039 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3040 SetupFileHash *setup_file_hash, *valid_file_hash;
3041 SetupFileHash *extra_file_hash, *empty_file_hash;
3042 char *known_token_value = KNOWN_TOKEN_VALUE;
3045 if (filename == NULL)
3049 printf("LoadArtworkConfigFromFilename '%s' ...\n", filename);
3052 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3055 /* separate valid (defined) from empty (undefined) config token values */
3056 valid_file_hash = newSetupFileHash();
3057 empty_file_hash = newSetupFileHash();
3058 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3060 char *value = HASH_ITERATION_VALUE(itr);
3062 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3063 HASH_ITERATION_TOKEN(itr), value);
3065 END_HASH_ITERATION(setup_file_hash, itr)
3067 /* at this point, we do not need the setup file hash anymore -- free it */
3068 freeSetupFileHash(setup_file_hash);
3070 /* map deprecated to current tokens (using prefix match and replace) */
3071 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3073 char *token = HASH_ITERATION_TOKEN(itr);
3074 char *mapped_token = get_mapped_token(token);
3076 if (mapped_token != NULL)
3078 char *value = HASH_ITERATION_VALUE(itr);
3080 /* add mapped token */
3081 setHashEntry(valid_file_hash, mapped_token, value);
3083 /* ignore old token (by setting it to "known" keyword) */
3084 setHashEntry(valid_file_hash, token, known_token_value);
3089 END_HASH_ITERATION(valid_file_hash, itr)
3091 /* read parameters for all known config file tokens */
3092 for (i = 0; i < num_file_list_entries; i++)
3093 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3095 /* set all tokens that can be ignored here to "known" keyword */
3096 for (i = 0; i < num_ignore_tokens; i++)
3097 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3099 /* copy all unknown config file tokens to extra config hash */
3100 extra_file_hash = newSetupFileHash();
3101 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3103 char *value = HASH_ITERATION_VALUE(itr);
3105 if (!strEqual(value, known_token_value))
3106 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3108 END_HASH_ITERATION(valid_file_hash, itr)
3110 /* at this point, we do not need the valid file hash anymore -- free it */
3111 freeSetupFileHash(valid_file_hash);
3113 /* now try to determine valid, dynamically defined config tokens */
3115 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3117 struct FileInfo **dynamic_file_list =
3118 &artwork_info->dynamic_file_list;
3119 int *num_dynamic_file_list_entries =
3120 &artwork_info->num_dynamic_file_list_entries;
3121 struct PropertyMapping **property_mapping =
3122 &artwork_info->property_mapping;
3123 int *num_property_mapping_entries =
3124 &artwork_info->num_property_mapping_entries;
3125 int current_summarized_file_list_entry =
3126 artwork_info->num_file_list_entries +
3127 artwork_info->num_dynamic_file_list_entries;
3128 char *token = HASH_ITERATION_TOKEN(itr);
3129 int len_token = strlen(token);
3131 boolean base_prefix_found = FALSE;
3132 boolean parameter_suffix_found = FALSE;
3135 printf("::: examining '%s' -> '%s'\n", token, HASH_ITERATION_VALUE(itr));
3138 /* skip all parameter definitions (handled by read_token_parameters()) */
3139 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3141 int len_suffix = strlen(suffix_list[i].token);
3143 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3144 parameter_suffix_found = TRUE;
3147 if (parameter_suffix_found)
3150 /* ---------- step 0: search for matching base prefix ---------- */
3153 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3155 char *base_prefix = base_prefixes[i];
3156 int len_base_prefix = strlen(base_prefix);
3157 boolean ext1_suffix_found = FALSE;
3158 boolean ext2_suffix_found = FALSE;
3159 boolean ext3_suffix_found = FALSE;
3160 boolean exact_match = FALSE;
3161 int base_index = -1;
3162 int ext1_index = -1;
3163 int ext2_index = -1;
3164 int ext3_index = -1;
3166 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3168 if (!base_prefix_found)
3174 if (IS_PARENT_PROCESS())
3175 printf("===> MATCH: '%s', '%s'\n", token, base_prefix);
3178 if (start_pos + len_base_prefix == len_token) /* exact match */
3183 if (IS_PARENT_PROCESS())
3184 printf("===> EXACT MATCH: '%s', '%s'\n", token, base_prefix);
3187 add_dynamic_file_list_entry(dynamic_file_list,
3188 num_dynamic_file_list_entries,
3191 num_suffix_list_entries,
3193 add_property_mapping(property_mapping,
3194 num_property_mapping_entries,
3195 base_index, -1, -1, -1,
3196 current_summarized_file_list_entry);
3201 if (IS_PARENT_PROCESS())
3202 printf("---> examining token '%s': search 1st suffix ...\n", token);
3205 /* ---------- step 1: search for matching first suffix ---------- */
3207 start_pos += len_base_prefix;
3208 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3210 char *ext1_suffix = ext1_suffixes[j];
3211 int len_ext1_suffix = strlen(ext1_suffix);
3213 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3215 if (!ext1_suffix_found)
3221 if (IS_PARENT_PROCESS())
3222 printf("===> MATCH: '%s', '%s'\n", token, ext1_suffix);
3225 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3230 if (IS_PARENT_PROCESS())
3231 printf("===> EXACT MATCH: '%s', '%s'\n", token, ext1_suffix);
3234 add_dynamic_file_list_entry(dynamic_file_list,
3235 num_dynamic_file_list_entries,
3238 num_suffix_list_entries,
3240 add_property_mapping(property_mapping,
3241 num_property_mapping_entries,
3242 base_index, ext1_index, -1, -1,
3243 current_summarized_file_list_entry);
3247 start_pos += len_ext1_suffix;
3254 if (IS_PARENT_PROCESS())
3255 printf("---> examining token '%s': search 2nd suffix ...\n", token);
3258 /* ---------- step 2: search for matching second suffix ---------- */
3260 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3262 char *ext2_suffix = ext2_suffixes[k];
3263 int len_ext2_suffix = strlen(ext2_suffix);
3265 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3267 if (!ext2_suffix_found)
3273 if (IS_PARENT_PROCESS())
3274 printf("===> MATCH: '%s', '%s'\n", token, ext2_suffix);
3277 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3282 if (IS_PARENT_PROCESS())
3283 printf("===> EXACT MATCH: '%s', '%s'\n", token, ext2_suffix);
3286 add_dynamic_file_list_entry(dynamic_file_list,
3287 num_dynamic_file_list_entries,
3290 num_suffix_list_entries,
3292 add_property_mapping(property_mapping,
3293 num_property_mapping_entries,
3294 base_index, ext1_index, ext2_index, -1,
3295 current_summarized_file_list_entry);
3299 start_pos += len_ext2_suffix;
3306 if (IS_PARENT_PROCESS())
3307 printf("---> examining token '%s': search 3rd suffix ...\n",token);
3310 /* ---------- step 3: search for matching third suffix ---------- */
3312 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3314 char *ext3_suffix = ext3_suffixes[l];
3315 int len_ext3_suffix = strlen(ext3_suffix);
3317 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3319 if (!ext3_suffix_found)
3325 if (IS_PARENT_PROCESS())
3326 printf("===> MATCH: '%s', '%s'\n", token, ext3_suffix);
3329 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3334 if (IS_PARENT_PROCESS())
3335 printf("===> EXACT MATCH: '%s', '%s'\n", token, ext3_suffix);
3338 add_dynamic_file_list_entry(dynamic_file_list,
3339 num_dynamic_file_list_entries,
3342 num_suffix_list_entries,
3344 add_property_mapping(property_mapping,
3345 num_property_mapping_entries,
3346 base_index, ext1_index, ext2_index, ext3_index,
3347 current_summarized_file_list_entry);
3353 END_HASH_ITERATION(extra_file_hash, itr)
3355 if (artwork_info->num_dynamic_file_list_entries > 0)
3357 artwork_info->dynamic_artwork_list =
3358 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3359 artwork_info->sizeof_artwork_list_entry);
3362 if (options.verbose && IS_PARENT_PROCESS())
3364 SetupFileList *setup_file_list, *list;
3365 boolean dynamic_tokens_found = FALSE;
3366 boolean unknown_tokens_found = FALSE;
3367 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3369 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3370 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3372 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3374 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3375 dynamic_tokens_found = TRUE;
3377 unknown_tokens_found = TRUE;
3379 END_HASH_ITERATION(extra_file_hash, itr)
3381 if (options.debug && dynamic_tokens_found)
3383 Error(ERR_INFO_LINE, "-");
3384 Error(ERR_INFO, "dynamic token(s) found in config file:");
3385 Error(ERR_INFO, "- config file: '%s'", filename);
3387 for (list = setup_file_list; list != NULL; list = list->next)
3389 char *value = getHashEntry(extra_file_hash, list->token);
3391 if (value != NULL && strEqual(value, known_token_value))
3392 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3395 Error(ERR_INFO_LINE, "-");
3398 if (unknown_tokens_found)
3400 Error(ERR_INFO_LINE, "-");
3401 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3402 Error(ERR_INFO, "- config file: '%s'", filename);
3404 for (list = setup_file_list; list != NULL; list = list->next)
3406 char *value = getHashEntry(extra_file_hash, list->token);
3408 if (value != NULL && !strEqual(value, known_token_value))
3409 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3412 Error(ERR_INFO_LINE, "-");
3415 if (undefined_values_found)
3417 Error(ERR_INFO_LINE, "-");
3418 Error(ERR_INFO, "warning: undefined values found in config file:");
3419 Error(ERR_INFO, "- config file: '%s'", filename);
3421 for (list = setup_file_list; list != NULL; list = list->next)
3423 char *value = getHashEntry(empty_file_hash, list->token);
3426 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3429 Error(ERR_INFO_LINE, "-");
3432 freeSetupFileList(setup_file_list);
3435 freeSetupFileHash(extra_file_hash);
3436 freeSetupFileHash(empty_file_hash);
3439 for (i = 0; i < num_file_list_entries; i++)
3441 printf("'%s' ", file_list[i].token);
3442 if (file_list[i].filename)
3443 printf("-> '%s'\n", file_list[i].filename);
3445 printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
3450 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3452 struct FileInfo *file_list = artwork_info->file_list;
3453 int num_file_list_entries = artwork_info->num_file_list_entries;
3454 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3455 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3458 DrawInitText("Loading artwork config", 120, FC_GREEN);
3459 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3461 /* always start with reliable default values */
3462 for (i = 0; i < num_file_list_entries; i++)
3464 setString(&file_list[i].filename, file_list[i].default_filename);
3466 for (j = 0; j < num_suffix_list_entries; j++)
3467 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3469 file_list[i].redefined = FALSE;
3470 file_list[i].fallback_to_default = FALSE;
3473 /* free previous dynamic artwork file array */
3474 if (artwork_info->dynamic_file_list != NULL)
3476 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3478 free(artwork_info->dynamic_file_list[i].token);
3479 free(artwork_info->dynamic_file_list[i].filename);
3480 free(artwork_info->dynamic_file_list[i].parameter);
3483 free(artwork_info->dynamic_file_list);
3484 artwork_info->dynamic_file_list = NULL;
3486 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3487 &artwork_info->num_dynamic_file_list_entries);
3490 /* free previous property mapping */
3491 if (artwork_info->property_mapping != NULL)
3493 free(artwork_info->property_mapping);
3495 artwork_info->property_mapping = NULL;
3496 artwork_info->num_property_mapping_entries = 0;
3500 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3502 if (!SETUP_OVERRIDE_ARTWORK(setup, artwork_info->type))
3505 /* first look for special artwork configured in level series config */
3506 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3509 printf("::: filename_base == '%s' [%s, %s]\n", filename_base,
3510 leveldir_current->graphics_set,
3511 leveldir_current->graphics_path);
3514 if (fileExists(filename_base))
3515 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3518 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3520 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3521 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3524 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3525 struct ListNodeInfo **listnode)
3529 char *filename = (*listnode)->source_filename;
3531 if (--(*listnode)->num_references <= 0)
3532 deleteNodeFromList(&artwork_info->content_list, filename,
3533 artwork_info->free_artwork);
3539 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3540 struct ListNodeInfo **listnode,
3541 struct FileInfo *file_list_entry)
3551 char *basename = file_list_entry->filename;
3552 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3554 if (filename == NULL)
3556 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3558 basename = file_list_entry->default_filename;
3560 /* fail for cloned default artwork that has no default filename defined */
3561 if (file_list_entry->default_is_cloned &&
3562 strEqual(basename, UNDEFINED_FILENAME))
3564 int error_mode = ERR_WARN;
3566 /* we can get away without sounds and music, but not without graphics */
3567 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3568 error_mode = ERR_EXIT;
3570 Error(error_mode, "token '%s' was cloned and has no default filename",
3571 file_list_entry->token);
3576 /* dynamic artwork has no default filename / skip empty default artwork */
3577 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3580 file_list_entry->fallback_to_default = TRUE;
3582 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3584 filename = getCustomArtworkFilename(basename, artwork_info->type);
3586 if (filename == NULL)
3588 int error_mode = ERR_WARN;
3590 /* we can get away without sounds and music, but not without graphics */
3591 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3592 error_mode = ERR_EXIT;
3594 Error(error_mode, "cannot find default artwork file '%s'", basename);
3600 /* check if the old and the new artwork file are the same */
3601 if (*listnode && strEqual((*listnode)->source_filename, filename))
3603 /* The old and new artwork are the same (have the same filename and path).
3604 This usually means that this artwork does not exist in this artwork set
3605 and a fallback to the existing artwork is done. */
3608 printf("[artwork '%s' already exists (same list entry)]\n", filename);
3614 /* delete existing artwork file entry */
3615 deleteArtworkListEntry(artwork_info, listnode);
3617 /* check if the new artwork file already exists in the list of artworks */
3618 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3621 printf("[artwork '%s' already exists (other list entry)]\n", filename);
3624 *listnode = (struct ListNodeInfo *)node->content;
3625 (*listnode)->num_references++;
3630 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3631 DrawInitText(basename, 150, FC_YELLOW);
3633 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3636 printf("[adding new artwork '%s']\n", filename);
3639 (*listnode)->num_references = 1;
3640 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3645 int error_mode = ERR_WARN;
3647 /* we can get away without sounds and music, but not without graphics */
3648 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3649 error_mode = ERR_EXIT;
3651 Error(error_mode, "cannot load artwork file '%s'", basename);
3657 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3658 struct ListNodeInfo **listnode,
3659 struct FileInfo *file_list_entry)
3662 printf("GOT CUSTOM ARTWORK FILE '%s'\n", file_list_entry->filename);
3665 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3667 deleteArtworkListEntry(artwork_info, listnode);
3672 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3675 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3677 struct FileInfo *file_list = artwork_info->file_list;
3678 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3679 int num_file_list_entries = artwork_info->num_file_list_entries;
3680 int num_dynamic_file_list_entries =
3681 artwork_info->num_dynamic_file_list_entries;
3684 print_timestamp_init("ReloadCustomArtworkList");
3686 for (i = 0; i < num_file_list_entries; i++)
3687 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3690 for (i = 0; i < num_dynamic_file_list_entries; i++)
3691 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3692 &dynamic_file_list[i]);
3694 print_timestamp_done("ReloadCustomArtworkList");
3697 dumpList(artwork_info->content_list);
3701 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3702 struct ListNodeInfo ***list,
3703 int *num_list_entries)
3710 for (i = 0; i < *num_list_entries; i++)
3711 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3715 *num_list_entries = 0;
3718 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3720 if (artwork_info == NULL)
3723 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3724 &artwork_info->num_file_list_entries);
3726 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3727 &artwork_info->num_dynamic_file_list_entries);
3731 /* ------------------------------------------------------------------------- */
3732 /* functions only needed for non-Unix (non-command-line) systems */
3733 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3734 /* (now also added for Windows, to create files in user data directory) */
3735 /* ------------------------------------------------------------------------- */
3737 char *getErrorFilename(char *basename)
3739 return getPath2(getUserGameDataDir(), basename);
3742 void openErrorFile()
3744 InitUserDataDirectory();
3746 if ((program.error_file = fopen(program.error_filename, MODE_WRITE)) == NULL)
3748 program.error_file = stderr;
3750 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3751 program.error_filename, strerror(errno));
3755 void closeErrorFile()
3757 if (program.error_file != stderr) /* do not close stream 'stderr' */
3758 fclose(program.error_file);
3761 void dumpErrorFile()
3763 FILE *error_file = fopen(program.error_filename, MODE_READ);
3765 if (error_file != NULL)
3767 while (!feof(error_file))
3768 fputc(fgetc(error_file), stderr);
3774 void NotifyUserAboutErrorFile()
3776 #if defined(PLATFORM_WIN32)
3777 char *title_text = getStringCat2(program.program_title, " Error Message");
3778 char *error_text = getStringCat2("The program was aborted due to an error; "
3779 "for details, see the following error file:"
3780 STRING_NEWLINE, program.error_filename);
3782 MessageBox(NULL, error_text, title_text, MB_OK);
3787 /* ------------------------------------------------------------------------- */
3788 /* the following is only for debugging purpose and normally not used */
3789 /* ------------------------------------------------------------------------- */
3793 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3794 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3796 #define DEBUG_NUM_TIMESTAMPS 10
3797 #define DEBUG_TIME_IN_MICROSECONDS 0
3799 #if DEBUG_TIME_IN_MICROSECONDS
3800 static double Counter_Microseconds()
3802 static struct timeval base_time = { 0, 0 };
3803 struct timeval current_time;
3806 gettimeofday(¤t_time, NULL);
3808 /* reset base time in case of wrap-around */
3809 if (current_time.tv_sec < base_time.tv_sec)
3810 base_time = current_time;
3813 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3814 ((double)(current_time.tv_usec - base_time.tv_usec));
3816 return counter; /* return microseconds since last init */
3820 char *debug_print_timestamp_get_padding(int padding_size)
3822 static char *padding = NULL;
3823 int max_padding_size = 100;
3825 if (padding == NULL)
3827 padding = checked_calloc(max_padding_size + 1);
3828 memset(padding, ' ', max_padding_size);
3831 return &padding[MAX(0, max_padding_size - padding_size)];
3834 void debug_print_timestamp(int counter_nr, char *message)
3836 int indent_size = 8;
3837 int padding_size = 40;
3838 float timestamp_interval;
3841 Error(ERR_EXIT, "debugging: invalid negative counter");
3842 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3843 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3845 #if DEBUG_TIME_IN_MICROSECONDS
3846 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3849 counter[counter_nr][0] = Counter_Microseconds();
3851 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3854 counter[counter_nr][0] = Counter();
3857 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3858 counter[counter_nr][1] = counter[counter_nr][0];
3862 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3864 printf("%s%s%s %.3f %s\n",
3866 debug_print_timestamp_get_padding(counter_nr * indent_size),
3868 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3869 timestamp_interval / 1000,
3873 void debug_print_parent_only(char *format, ...)
3875 if (!IS_PARENT_PROCESS())
3882 va_start(ap, format);
3883 vprintf(format, ap);
3892 void print_timestamp_ext(char *message, char *mode)
3894 #if DEBUG_PRINT_INIT_TIMESTAMPS
3895 static char *debug_message = NULL;
3896 static char *last_message = NULL;
3897 static int counter_nr = 0;
3898 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3900 checked_free(debug_message);
3901 debug_message = getStringCat3(mode, " ", message);
3903 if (strEqual(mode, "INIT"))
3905 debug_print_timestamp(counter_nr, NULL);
3907 if (counter_nr + 1 < max_depth)
3908 debug_print_timestamp(counter_nr, debug_message);
3912 debug_print_timestamp(counter_nr, NULL);
3914 else if (strEqual(mode, "DONE"))
3918 if (counter_nr + 1 < max_depth ||
3919 (counter_nr == 0 && max_depth == 1))
3921 last_message = message;
3923 if (counter_nr == 0 && max_depth == 1)
3925 checked_free(debug_message);
3926 debug_message = getStringCat3("TIME", " ", message);
3929 debug_print_timestamp(counter_nr, debug_message);
3932 else if (!strEqual(mode, "TIME") ||
3933 !strEqual(message, last_message))
3935 if (counter_nr < max_depth)
3936 debug_print_timestamp(counter_nr, debug_message);
3941 void print_timestamp_init(char *message)
3943 print_timestamp_ext(message, "INIT");
3946 void print_timestamp_time(char *message)
3948 print_timestamp_ext(message, "TIME");
3951 void print_timestamp_done(char *message)
3953 print_timestamp_ext(message, "DONE");