1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
14 #include <sys/types.h>
24 #if !defined(PLATFORM_WIN32)
26 #include <sys/param.h>
36 /* ========================================================================= */
37 /* some generic helper functions */
38 /* ========================================================================= */
40 /* ------------------------------------------------------------------------- */
41 /* platform independent wrappers for printf() et al. (newline aware) */
42 /* ------------------------------------------------------------------------- */
44 #if defined(PLATFORM_ANDROID)
45 static int android_log_prio = ANDROID_LOG_INFO;
49 static void vfPrintLog(FILE *stream, char *format, va_list ap)
53 static void vfPrintLog(FILE *stream, char *format, va_list ap)
57 static void fPrintLog(FILE *stream, char *format, va_list ap)
61 static void fPrintLog(FILE *stream, char *format, va_list ap)
66 static void vfprintf_nonewline(FILE *stream, char *format, va_list ap)
68 #if defined(PLATFORM_ANDROID)
69 // (prefix text of logging output is currently skipped on Android)
70 //__android_log_vprint(android_log_prio, program.program_title, format, ap);
75 vfprintf(stream, format, ap);
76 vfprintf(stderr, format, ap2);
82 static void vfprintf_newline(FILE *stream, char *format, va_list ap)
84 #if defined(PLATFORM_ANDROID)
85 __android_log_vprint(android_log_prio, program.program_title, format, ap);
87 char *newline = STRING_NEWLINE;
92 vfprintf(stream, format, ap);
93 fprintf(stream, "%s", newline);
95 vfprintf(stderr, format, ap2);
96 fprintf(stderr, "%s", newline);
102 static void fprintf_nonewline(FILE *stream, char *format, ...)
106 va_start(ap, format);
107 vfprintf_nonewline(stream, format, ap);
111 static void fprintf_newline(FILE *stream, char *format, ...)
115 va_start(ap, format);
116 vfprintf_newline(stream, format, ap);
120 void fprintf_line(FILE *stream, char *line_chars, int line_length)
124 for (i = 0; i < line_length; i++)
125 fprintf_nonewline(stream, "%s", line_chars);
127 fprintf_newline(stream, "");
130 void printf_line(char *line_chars, int line_length)
132 fprintf_line(stdout, line_chars, line_length);
135 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
137 fprintf(stdout, "%s", prefix);
138 fprintf_line(stdout, line_chars, line_length);
142 /* ------------------------------------------------------------------------- */
143 /* string functions */
144 /* ------------------------------------------------------------------------- */
146 /* int2str() returns a number converted to a string;
147 the used memory is static, but will be overwritten by later calls,
148 so if you want to save the result, copy it to a private string buffer;
149 there can be 10 local calls of int2str() without buffering the result --
150 the 11th call will then destroy the result from the first call and so on.
153 char *int2str(int number, int size)
155 static char shift_array[10][40];
156 static int shift_counter = 0;
157 char *s = shift_array[shift_counter];
159 shift_counter = (shift_counter + 1) % 10;
166 sprintf(s, " %09d", number);
167 return &s[strlen(s) - size];
171 sprintf(s, "%d", number);
177 /* something similar to "int2str()" above, but allocates its own memory
178 and has a different interface; we cannot use "itoa()", because this
179 seems to be already defined when cross-compiling to the win32 target */
181 char *i_to_a(unsigned int i)
183 static char *a = NULL;
187 if (i > 2147483647) /* yes, this is a kludge */
190 a = checked_malloc(10 + 1);
198 /* calculate base-2 logarithm of argument (rounded down to integer;
199 this function returns the number of the highest bit set in argument) */
201 int log_2(unsigned int x)
207 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
214 boolean getTokenValueFromString(char *string, char **token, char **value)
216 return getTokenValueFromSetupLine(string, token, value);
220 /* ------------------------------------------------------------------------- */
221 /* counter functions */
222 /* ------------------------------------------------------------------------- */
224 /* maximal allowed length of a command line option */
225 #define MAX_OPTION_LEN 256
227 static unsigned int getCurrentMS()
229 return SDL_GetTicks();
232 static unsigned int mainCounter(int mode)
234 static unsigned int base_ms = 0;
235 unsigned int current_ms;
237 /* get current system milliseconds */
238 current_ms = getCurrentMS();
240 /* reset base timestamp in case of counter reset or wrap-around */
241 if (mode == INIT_COUNTER || current_ms < base_ms)
242 base_ms = current_ms;
244 /* return milliseconds since last counter reset */
245 return current_ms - base_ms;
248 void InitCounter() /* set counter back to zero */
250 mainCounter(INIT_COUNTER);
253 unsigned int Counter() /* get milliseconds since last call of InitCounter() */
255 return mainCounter(READ_COUNTER);
258 static void sleep_milliseconds(unsigned int milliseconds_delay)
260 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
264 /* we want to wait only a few ms -- if we assume that we have a
265 kernel timer resolution of 10 ms, we would wait far to long;
266 therefore it's better to do a short interval of busy waiting
267 to get our sleeping time more accurate */
269 unsigned int base_counter = Counter(), actual_counter = Counter();
271 while (actual_counter < base_counter + milliseconds_delay &&
272 actual_counter >= base_counter)
273 actual_counter = Counter();
277 SDL_Delay(milliseconds_delay);
281 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
283 sleep_milliseconds(delay);
286 boolean FrameReached(unsigned int *frame_counter_var,
287 unsigned int frame_delay)
289 unsigned int actual_frame_counter = FrameCounter;
291 if (actual_frame_counter >= *frame_counter_var &&
292 actual_frame_counter < *frame_counter_var + frame_delay)
295 *frame_counter_var = actual_frame_counter;
300 boolean DelayReached(unsigned int *counter_var,
303 unsigned int actual_counter = Counter();
305 if (actual_counter >= *counter_var &&
306 actual_counter < *counter_var + delay)
309 *counter_var = actual_counter;
314 void WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
316 unsigned int actual_counter;
320 actual_counter = Counter();
322 if (actual_counter >= *counter_var &&
323 actual_counter < *counter_var + delay)
324 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
329 *counter_var = actual_counter;
333 /* ------------------------------------------------------------------------- */
334 /* random generator functions */
335 /* ------------------------------------------------------------------------- */
337 unsigned int init_random_number(int nr, int seed)
339 if (seed == NEW_RANDOMIZE)
341 /* default random seed */
342 seed = (int)time(NULL); // seconds since the epoch
344 #if !defined(PLATFORM_WIN32)
345 /* add some more randomness */
346 struct timeval current_time;
348 gettimeofday(¤t_time, NULL);
350 seed += (int)current_time.tv_usec; // microseconds since the epoch
353 /* add some more randomness */
354 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
356 /* add some more randomness */
357 seed += GetSimpleRandom(1000000);
360 srandom_linux_libc(nr, (unsigned int) seed);
362 return (unsigned int) seed;
365 unsigned int get_random_number(int nr, int max)
367 return (max > 0 ? random_linux_libc(nr) % max : 0);
371 /* ------------------------------------------------------------------------- */
372 /* system info functions */
373 /* ------------------------------------------------------------------------- */
375 #if !defined(PLATFORM_ANDROID)
376 static char *get_corrected_real_name(char *real_name)
378 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
379 char *from_ptr = real_name;
380 char *to_ptr = real_name_new;
382 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
383 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
385 /* the name field read from "passwd" file may also contain additional
386 user information, separated by commas, which will be removed here */
387 if (*from_ptr == ',')
390 /* the user's real name may contain 'german sharp s' characters,
391 which have no equivalent in upper case letters (used by our fonts) */
392 if (*from_ptr == CHAR_BYTE_SHARP_S)
399 *to_ptr++ = *from_ptr++;
404 return real_name_new;
410 static char *login_name = NULL;
412 #if defined(PLATFORM_WIN32)
413 if (login_name == NULL)
415 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
416 login_name = checked_malloc(buffer_size);
418 if (GetUserName(login_name, &buffer_size) == 0)
419 strcpy(login_name, ANONYMOUS_NAME);
422 if (login_name == NULL)
426 if ((pwd = getpwuid(getuid())) == NULL)
427 login_name = ANONYMOUS_NAME;
429 login_name = getStringCopy(pwd->pw_name);
438 static char *real_name = NULL;
440 #if defined(PLATFORM_WIN32)
441 if (real_name == NULL)
443 static char buffer[MAX_USERNAME_LEN + 1];
444 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
446 if (GetUserName(buffer, &buffer_size) != 0)
447 real_name = get_corrected_real_name(buffer);
449 real_name = ANONYMOUS_NAME;
451 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
452 if (real_name == NULL)
456 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
457 real_name = get_corrected_real_name(pwd->pw_gecos);
459 real_name = ANONYMOUS_NAME;
462 real_name = ANONYMOUS_NAME;
468 time_t getFileTimestampEpochSeconds(char *filename)
470 struct stat file_status;
472 if (stat(filename, &file_status) != 0) /* cannot stat file */
475 return file_status.st_mtime;
479 /* ------------------------------------------------------------------------- */
480 /* path manipulation functions */
481 /* ------------------------------------------------------------------------- */
483 static char *getLastPathSeparatorPtr(char *filename)
485 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
487 if (last_separator == NULL) /* also try DOS/Windows variant */
488 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
490 return last_separator;
493 char *getBaseNamePtr(char *filename)
495 char *last_separator = getLastPathSeparatorPtr(filename);
497 if (last_separator != NULL)
498 return last_separator + 1; /* separator found: strip base path */
500 return filename; /* no separator found: filename has no path */
503 char *getBaseName(char *filename)
505 return getStringCopy(getBaseNamePtr(filename));
508 char *getBasePath(char *filename)
510 char *basepath = getStringCopy(filename);
511 char *last_separator = getLastPathSeparatorPtr(basepath);
513 if (last_separator != NULL)
514 *last_separator = '\0'; /* separator found: strip basename */
516 basepath = "."; /* no separator found: use current path */
521 static char *getProgramMainDataPath()
523 char *main_data_path = getStringCopy(program.command_basepath);
525 #if defined(PLATFORM_MACOSX)
526 static char *main_data_binary_subdir = NULL;
528 if (main_data_binary_subdir == NULL)
530 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
532 strlen(MAC_APP_BINARY_SUBDIR) + 1);
534 sprintf(main_data_binary_subdir, "%s.app/%s",
535 program.program_title, MAC_APP_BINARY_SUBDIR);
538 // cut relative path to Mac OS X application binary directory from path
539 if (strSuffix(main_data_path, main_data_binary_subdir))
540 main_data_path[strlen(main_data_path) -
541 strlen(main_data_binary_subdir)] = '\0';
543 // cut trailing path separator from path (but not if path is root directory)
544 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
545 main_data_path[strlen(main_data_path) - 1] = '\0';
548 return main_data_path;
552 /* ------------------------------------------------------------------------- */
553 /* various string functions */
554 /* ------------------------------------------------------------------------- */
556 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
558 if (s1 == NULL || s2 == NULL || sep == NULL)
561 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
564 sprintf(complete_string, "%s%s%s", s1, sep, s2);
566 return complete_string;
569 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
571 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
574 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
575 strlen(s2) + strlen(sep) +
578 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
580 return complete_string;
583 char *getStringCat2(char *s1, char *s2)
585 return getStringCat2WithSeparator(s1, s2, "");
588 char *getStringCat3(char *s1, char *s2, char *s3)
590 return getStringCat3WithSeparator(s1, s2, s3, "");
593 char *getPath2(char *path1, char *path2)
595 #if defined(PLATFORM_ANDROID)
596 // workaround for reading from APK assets directory -- skip leading "./"
597 if (strEqual(path1, "."))
598 return getStringCopy(path2);
601 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
604 char *getPath3(char *path1, char *path2, char *path3)
606 #if defined(PLATFORM_ANDROID)
607 // workaround for reading from APK assets directory -- skip leading "./"
608 if (strEqual(path1, "."))
609 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
612 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
615 char *getImg2(char *path1, char *path2)
617 char *filename = getPath2(path1, path2);
619 if (!fileExists(filename) && strSuffix(path2, ".png"))
621 // backward compatibility: if PNG file not found, check for PCX file
622 char *path2pcx = getStringCopy(path2);
624 strcpy(&path2pcx[strlen(path2pcx) - 3], "pcx");
628 filename = getPath2(path1, path2pcx);
636 char *getImg3(char *path1, char *path2, char *path3)
638 char *filename = getPath3(path1, path2, path3);
640 if (!fileExists(filename) && strSuffix(path3, ".png"))
642 // backward compatibility: if PNG file not found, check for PCX file
643 char *path3pcx = getStringCopy(path3);
645 strcpy(&path3pcx[strlen(path3pcx) - 3], "pcx");
649 filename = getPath3(path1, path2, path3pcx);
657 char *getStringCopy(const char *s)
664 s_copy = checked_malloc(strlen(s) + 1);
670 char *getStringCopyN(const char *s, int n)
673 int s_len = MAX(0, n);
678 s_copy = checked_malloc(s_len + 1);
679 strncpy(s_copy, s, s_len);
680 s_copy[s_len] = '\0';
685 char *getStringCopyNStatic(const char *s, int n)
687 static char *s_copy = NULL;
689 checked_free(s_copy);
691 s_copy = getStringCopyN(s, n);
696 char *getStringToLower(const char *s)
698 char *s_copy = checked_malloc(strlen(s) + 1);
699 char *s_ptr = s_copy;
702 *s_ptr++ = tolower(*s++);
708 void setString(char **old_value, char *new_value)
710 checked_free(*old_value);
712 *old_value = getStringCopy(new_value);
715 boolean strEqual(char *s1, char *s2)
717 return (s1 == NULL && s2 == NULL ? TRUE :
718 s1 == NULL && s2 != NULL ? FALSE :
719 s1 != NULL && s2 == NULL ? FALSE :
720 strcmp(s1, s2) == 0);
723 boolean strEqualN(char *s1, char *s2, int n)
725 return (s1 == NULL && s2 == NULL ? TRUE :
726 s1 == NULL && s2 != NULL ? FALSE :
727 s1 != NULL && s2 == NULL ? FALSE :
728 strncmp(s1, s2, n) == 0);
731 boolean strPrefix(char *s, char *prefix)
733 return (s == NULL && prefix == NULL ? TRUE :
734 s == NULL && prefix != NULL ? FALSE :
735 s != NULL && prefix == NULL ? FALSE :
736 strncmp(s, prefix, strlen(prefix)) == 0);
739 boolean strSuffix(char *s, char *suffix)
741 return (s == NULL && suffix == NULL ? TRUE :
742 s == NULL && suffix != NULL ? FALSE :
743 s != NULL && suffix == NULL ? FALSE :
744 strlen(s) < strlen(suffix) ? FALSE :
745 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
748 boolean strPrefixLower(char *s, char *prefix)
750 char *s_lower = getStringToLower(s);
751 boolean match = strPrefix(s_lower, prefix);
758 boolean strSuffixLower(char *s, char *suffix)
760 char *s_lower = getStringToLower(s);
761 boolean match = strSuffix(s_lower, suffix);
769 /* ------------------------------------------------------------------------- */
770 /* command line option handling functions */
771 /* ------------------------------------------------------------------------- */
773 void GetOptions(char *argv[],
774 void (*print_usage_function)(void),
775 void (*print_version_function)(void))
777 char *ro_base_path = RO_BASE_PATH;
778 char *rw_base_path = RW_BASE_PATH;
779 char **options_left = &argv[1];
781 /* if the program is configured to start from current directory (default),
782 determine program package directory from program binary (some versions
783 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
784 set the current working directory to the program package directory) */
786 if (strEqual(ro_base_path, "."))
787 ro_base_path = getProgramMainDataPath();
788 if (strEqual(rw_base_path, "."))
789 rw_base_path = getProgramMainDataPath();
791 /* initialize global program options */
792 options.display_name = NULL;
793 options.server_host = NULL;
794 options.server_port = 0;
796 options.ro_base_directory = ro_base_path;
797 options.rw_base_directory = rw_base_path;
798 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
799 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
800 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
801 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
802 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
804 options.execute_command = NULL;
805 options.special_flags = NULL;
807 options.serveronly = FALSE;
808 options.network = FALSE;
809 options.verbose = FALSE;
810 options.debug = FALSE;
813 options.verbose = TRUE;
815 #if !defined(PLATFORM_UNIX)
816 if (*options_left == NULL) /* no options given -- enable verbose mode */
817 options.verbose = TRUE;
821 while (*options_left)
823 char option_str[MAX_OPTION_LEN];
824 char *option = options_left[0];
825 char *next_option = options_left[1];
826 char *option_arg = NULL;
827 int option_len = strlen(option);
829 if (option_len >= MAX_OPTION_LEN)
830 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
832 strcpy(option_str, option); /* copy argument into buffer */
835 if (strEqual(option, "--")) /* stop scanning arguments */
838 if (strPrefix(option, "--")) /* treat '--' like '-' */
841 option_arg = strchr(option, '=');
842 if (option_arg == NULL) /* no '=' in option */
843 option_arg = next_option;
846 *option_arg++ = '\0'; /* cut argument from option */
847 if (*option_arg == '\0') /* no argument after '=' */
848 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
851 option_len = strlen(option);
853 if (strEqual(option, "-"))
855 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
857 else if (strncmp(option, "-help", option_len) == 0)
859 print_usage_function();
863 else if (strncmp(option, "-display", option_len) == 0)
865 if (option_arg == NULL)
866 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
868 options.display_name = option_arg;
869 if (option_arg == next_option)
872 else if (strncmp(option, "-basepath", option_len) == 0)
874 if (option_arg == NULL)
875 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
877 /* this should be extended to separate options for ro and rw data */
878 options.ro_base_directory = ro_base_path = option_arg;
879 options.rw_base_directory = rw_base_path = option_arg;
880 if (option_arg == next_option)
883 /* adjust paths for sub-directories in base directory accordingly */
884 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
885 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
886 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
887 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
888 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
890 else if (strncmp(option, "-levels", option_len) == 0)
892 if (option_arg == NULL)
893 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
895 options.level_directory = option_arg;
896 if (option_arg == next_option)
899 else if (strncmp(option, "-graphics", option_len) == 0)
901 if (option_arg == NULL)
902 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
904 options.graphics_directory = option_arg;
905 if (option_arg == next_option)
908 else if (strncmp(option, "-sounds", option_len) == 0)
910 if (option_arg == NULL)
911 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
913 options.sounds_directory = option_arg;
914 if (option_arg == next_option)
917 else if (strncmp(option, "-music", option_len) == 0)
919 if (option_arg == NULL)
920 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
922 options.music_directory = option_arg;
923 if (option_arg == next_option)
926 else if (strncmp(option, "-network", option_len) == 0)
928 options.network = TRUE;
930 else if (strncmp(option, "-serveronly", option_len) == 0)
932 options.serveronly = TRUE;
934 else if (strncmp(option, "-debug", option_len) == 0)
936 options.debug = TRUE;
938 else if (strncmp(option, "-verbose", option_len) == 0)
940 options.verbose = TRUE;
942 else if (strncmp(option, "-version", option_len) == 0 ||
943 strncmp(option, "-V", option_len) == 0)
945 print_version_function();
949 else if (strPrefix(option, "-D"))
951 options.special_flags = getStringCopy(&option[2]);
953 else if (strncmp(option, "-execute", option_len) == 0)
955 if (option_arg == NULL)
956 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
958 options.execute_command = option_arg;
959 if (option_arg == next_option)
962 /* when doing batch processing, always enable verbose mode (warnings) */
963 options.verbose = TRUE;
965 else if (*option == '-')
967 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
969 else if (options.server_host == NULL)
971 options.server_host = *options_left;
973 else if (options.server_port == 0)
975 options.server_port = atoi(*options_left);
976 if (options.server_port < 1024)
977 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
980 Error(ERR_EXIT_HELP, "too many arguments");
987 /* ------------------------------------------------------------------------- */
988 /* error handling functions */
989 /* ------------------------------------------------------------------------- */
991 #define MAX_INTERNAL_ERROR_SIZE 1024
993 /* used by SetError() and GetError() to store internal error messages */
994 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
996 void SetError(char *format, ...)
1000 va_start(ap, format);
1001 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1007 return internal_error;
1010 void Error(int mode, char *format, ...)
1012 static boolean last_line_was_separator = FALSE;
1013 char *process_name = "";
1015 #if defined(PLATFORM_ANDROID)
1016 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1017 mode & ERR_INFO ? ANDROID_LOG_INFO :
1018 mode & ERR_WARN ? ANDROID_LOG_WARN :
1019 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1020 ANDROID_LOG_UNKNOWN);
1023 /* display warnings only when running in verbose mode */
1024 if (mode & ERR_WARN && !options.verbose)
1027 if (mode == ERR_INFO_LINE)
1029 if (!last_line_was_separator)
1030 fprintf_line(program.error_file, format, 79);
1032 last_line_was_separator = TRUE;
1037 last_line_was_separator = FALSE;
1039 if (mode & ERR_SOUND_SERVER)
1040 process_name = " sound server";
1041 else if (mode & ERR_NETWORK_SERVER)
1042 process_name = " network server";
1043 else if (mode & ERR_NETWORK_CLIENT)
1044 process_name = " network client **";
1050 fprintf_nonewline(program.error_file, "%s%s: ", program.command_basename,
1053 if (mode & ERR_WARN)
1054 fprintf_nonewline(program.error_file, "warning: ");
1056 if (mode & ERR_EXIT)
1057 fprintf_nonewline(program.error_file, "fatal error: ");
1059 va_start(ap, format);
1060 vfprintf_newline(program.error_file, format, ap);
1063 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1065 va_start(ap, format);
1066 program.exit_message_function(format, ap);
1071 if (mode & ERR_HELP)
1072 fprintf_newline(program.error_file,
1073 "%s: Try option '--help' for more information.",
1074 program.command_basename);
1076 if (mode & ERR_EXIT)
1077 fprintf_newline(program.error_file, "%s%s: aborting",
1078 program.command_basename, process_name);
1080 if (mode & ERR_EXIT)
1082 if (mode & ERR_FROM_SERVER)
1083 exit(1); /* child process: normal exit */
1085 program.exit_function(1); /* main process: clean up stuff */
1090 /* ------------------------------------------------------------------------- */
1091 /* checked memory allocation and freeing functions */
1092 /* ------------------------------------------------------------------------- */
1094 void *checked_malloc(unsigned int size)
1101 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1106 void *checked_calloc(unsigned int size)
1110 ptr = calloc(1, size);
1113 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1118 void *checked_realloc(void *ptr, unsigned int size)
1120 ptr = realloc(ptr, size);
1123 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1128 void checked_free(void *ptr)
1130 if (ptr != NULL) /* this check should be done by free() anyway */
1134 void clear_mem(void *ptr, unsigned int size)
1136 #if defined(PLATFORM_WIN32)
1137 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1138 char *cptr = (char *)ptr;
1143 memset(ptr, 0, size);
1148 /* ------------------------------------------------------------------------- */
1149 /* various helper functions */
1150 /* ------------------------------------------------------------------------- */
1152 inline void swap_numbers(int *i1, int *i2)
1160 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1172 /* the "put" variants of the following file access functions check for the file
1173 pointer being != NULL and return the number of bytes they have or would have
1174 written; this allows for chunk writing functions to first determine the size
1175 of the (not yet written) chunk, write the correct chunk size and finally
1176 write the chunk itself */
1178 int getFile8BitInteger(File *file)
1180 return getByteFromFile(file);
1183 int putFile8BitInteger(FILE *file, int value)
1191 int getFile16BitInteger(File *file, int byte_order)
1193 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1194 return ((getByteFromFile(file) << 8) |
1195 (getByteFromFile(file) << 0));
1196 else /* BYTE_ORDER_LITTLE_ENDIAN */
1197 return ((getByteFromFile(file) << 0) |
1198 (getByteFromFile(file) << 8));
1201 int putFile16BitInteger(FILE *file, int value, int byte_order)
1205 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1207 fputc((value >> 8) & 0xff, file);
1208 fputc((value >> 0) & 0xff, file);
1210 else /* BYTE_ORDER_LITTLE_ENDIAN */
1212 fputc((value >> 0) & 0xff, file);
1213 fputc((value >> 8) & 0xff, file);
1220 int getFile32BitInteger(File *file, int byte_order)
1222 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1223 return ((getByteFromFile(file) << 24) |
1224 (getByteFromFile(file) << 16) |
1225 (getByteFromFile(file) << 8) |
1226 (getByteFromFile(file) << 0));
1227 else /* BYTE_ORDER_LITTLE_ENDIAN */
1228 return ((getByteFromFile(file) << 0) |
1229 (getByteFromFile(file) << 8) |
1230 (getByteFromFile(file) << 16) |
1231 (getByteFromFile(file) << 24));
1234 int putFile32BitInteger(FILE *file, int value, int byte_order)
1238 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1240 fputc((value >> 24) & 0xff, file);
1241 fputc((value >> 16) & 0xff, file);
1242 fputc((value >> 8) & 0xff, file);
1243 fputc((value >> 0) & 0xff, file);
1245 else /* BYTE_ORDER_LITTLE_ENDIAN */
1247 fputc((value >> 0) & 0xff, file);
1248 fputc((value >> 8) & 0xff, file);
1249 fputc((value >> 16) & 0xff, file);
1250 fputc((value >> 24) & 0xff, file);
1257 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1260 const int chunk_name_length = 4;
1262 /* read chunk name */
1263 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1266 if (chunk_size != NULL)
1268 /* read chunk size */
1269 *chunk_size = getFile32BitInteger(file, byte_order);
1272 return (checkEndOfFile(file) ? FALSE : TRUE);
1275 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1280 /* write chunk name */
1282 fputs(chunk_name, file);
1284 num_bytes += strlen(chunk_name);
1286 if (chunk_size >= 0)
1288 /* write chunk size */
1290 putFile32BitInteger(file, chunk_size, byte_order);
1298 int getFileVersion(File *file)
1300 int version_major = getByteFromFile(file);
1301 int version_minor = getByteFromFile(file);
1302 int version_patch = getByteFromFile(file);
1303 int version_build = getByteFromFile(file);
1305 return VERSION_IDENT(version_major, version_minor, version_patch,
1309 int putFileVersion(FILE *file, int version)
1313 int version_major = VERSION_MAJOR(version);
1314 int version_minor = VERSION_MINOR(version);
1315 int version_patch = VERSION_PATCH(version);
1316 int version_build = VERSION_BUILD(version);
1318 fputc(version_major, file);
1319 fputc(version_minor, file);
1320 fputc(version_patch, file);
1321 fputc(version_build, file);
1327 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1331 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1332 buffer[i] = getByteFromFile(file);
1335 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1339 for(i = 0; i < bytes; i++)
1340 fputc(buffer[i], file);
1343 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1345 while (bytes-- && !checkEndOfFile(file))
1346 getByteFromFile(file);
1349 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1356 /* ------------------------------------------------------------------------- */
1357 /* functions to translate key identifiers between different format */
1358 /* ------------------------------------------------------------------------- */
1360 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1361 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1362 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1363 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1365 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1374 /* normal cursor keys */
1375 { KSYM_Left, "XK_Left", "cursor left" },
1376 { KSYM_Right, "XK_Right", "cursor right" },
1377 { KSYM_Up, "XK_Up", "cursor up" },
1378 { KSYM_Down, "XK_Down", "cursor down" },
1380 /* keypad cursor keys */
1382 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1383 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1384 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1385 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1388 /* other keypad keys */
1389 #ifdef KSYM_KP_Enter
1390 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1391 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1392 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1393 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1394 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1395 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1399 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1400 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1401 { KSYM_Control_L, "XK_Control_L", "left control" },
1402 { KSYM_Control_R, "XK_Control_R", "right control" },
1403 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1404 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1405 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1406 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1407 #if !defined(TARGET_SDL2)
1408 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1409 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1411 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1412 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1414 /* some special keys */
1415 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1416 { KSYM_Delete, "XK_Delete", "delete" },
1417 { KSYM_Insert, "XK_Insert", "insert" },
1418 { KSYM_Tab, "XK_Tab", "tab" },
1419 { KSYM_Home, "XK_Home", "home" },
1420 { KSYM_End, "XK_End", "end" },
1421 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1422 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1424 #if defined(TARGET_SDL2)
1425 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1426 { KSYM_Back, "XK_Back", "back" }, /* back key */
1429 /* ASCII 0x20 to 0x40 keys (except numbers) */
1430 { KSYM_space, "XK_space", "space" },
1431 { KSYM_exclam, "XK_exclam", "!" },
1432 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1433 { KSYM_numbersign, "XK_numbersign", "#" },
1434 { KSYM_dollar, "XK_dollar", "$" },
1435 { KSYM_percent, "XK_percent", "%" },
1436 { KSYM_ampersand, "XK_ampersand", "&" },
1437 { KSYM_apostrophe, "XK_apostrophe", "'" },
1438 { KSYM_parenleft, "XK_parenleft", "(" },
1439 { KSYM_parenright, "XK_parenright", ")" },
1440 { KSYM_asterisk, "XK_asterisk", "*" },
1441 { KSYM_plus, "XK_plus", "+" },
1442 { KSYM_comma, "XK_comma", "," },
1443 { KSYM_minus, "XK_minus", "-" },
1444 { KSYM_period, "XK_period", "." },
1445 { KSYM_slash, "XK_slash", "/" },
1446 { KSYM_colon, "XK_colon", ":" },
1447 { KSYM_semicolon, "XK_semicolon", ";" },
1448 { KSYM_less, "XK_less", "<" },
1449 { KSYM_equal, "XK_equal", "=" },
1450 { KSYM_greater, "XK_greater", ">" },
1451 { KSYM_question, "XK_question", "?" },
1452 { KSYM_at, "XK_at", "@" },
1454 /* more ASCII keys */
1455 { KSYM_bracketleft, "XK_bracketleft", "[" },
1456 { KSYM_backslash, "XK_backslash", "\\" },
1457 { KSYM_bracketright,"XK_bracketright", "]" },
1458 { KSYM_asciicircum, "XK_asciicircum", "^" },
1459 { KSYM_underscore, "XK_underscore", "_" },
1460 { KSYM_grave, "XK_grave", "grave" },
1461 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1462 { KSYM_braceleft, "XK_braceleft", "brace left" },
1463 { KSYM_bar, "XK_bar", "bar" },
1464 { KSYM_braceright, "XK_braceright", "brace right" },
1465 { KSYM_asciitilde, "XK_asciitilde", "~" },
1467 /* special (non-ASCII) keys */
1468 { KSYM_degree, "XK_degree", "degree" },
1469 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1470 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1471 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1472 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1473 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1474 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1475 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1477 #if defined(TARGET_SDL2)
1478 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1479 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1480 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1481 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1482 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1483 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1484 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1485 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1486 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1488 /* other keys (for reverse mapping only) */
1489 { KSYM_space, "XK_space", " " },
1492 #if defined(TARGET_SDL2)
1493 /* keypad keys are not in numerical order in SDL2 */
1494 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1495 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1496 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1497 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1498 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1499 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1500 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1501 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1502 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1503 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1506 /* end-of-array identifier */
1512 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1514 static char name_buffer[30];
1517 if (key >= KSYM_A && key <= KSYM_Z)
1518 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1519 else if (key >= KSYM_a && key <= KSYM_z)
1520 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1521 else if (key >= KSYM_0 && key <= KSYM_9)
1522 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1523 #if !defined(TARGET_SDL2)
1524 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1525 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1527 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1528 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1529 else if (key == KSYM_UNDEFINED)
1530 strcpy(name_buffer, "(undefined)");
1537 if (key == translate_key[i].key)
1539 strcpy(name_buffer, translate_key[i].name);
1543 while (translate_key[++i].name);
1545 if (!translate_key[i].name)
1546 strcpy(name_buffer, "(unknown)");
1549 *name = name_buffer;
1551 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1553 static char name_buffer[30];
1556 if (key >= KSYM_A && key <= KSYM_Z)
1557 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1558 else if (key >= KSYM_a && key <= KSYM_z)
1559 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1560 else if (key >= KSYM_0 && key <= KSYM_9)
1561 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1562 #if !defined(TARGET_SDL2)
1563 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1564 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1566 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1567 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1568 else if (key == KSYM_UNDEFINED)
1569 strcpy(name_buffer, "[undefined]");
1576 if (key == translate_key[i].key)
1578 strcpy(name_buffer, translate_key[i].x11name);
1582 while (translate_key[++i].x11name);
1584 if (!translate_key[i].x11name)
1585 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1588 *x11name = name_buffer;
1590 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1592 Key key = KSYM_UNDEFINED;
1593 char *name_ptr = *name;
1595 if (strlen(*name) == 1)
1597 char c = name_ptr[0];
1599 if (c >= 'A' && c <= 'Z')
1600 key = KSYM_A + (Key)(c - 'A');
1601 else if (c >= 'a' && c <= 'z')
1602 key = KSYM_a + (Key)(c - 'a');
1603 else if (c >= '0' && c <= '9')
1604 key = KSYM_0 + (Key)(c - '0');
1607 if (key == KSYM_UNDEFINED)
1613 if (strEqual(translate_key[i].name, *name))
1615 key = translate_key[i].key;
1619 while (translate_key[++i].x11name);
1622 if (key == KSYM_UNDEFINED)
1623 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1627 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1629 Key key = KSYM_UNDEFINED;
1630 char *name_ptr = *x11name;
1632 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1634 char c = name_ptr[3];
1636 if (c >= 'A' && c <= 'Z')
1637 key = KSYM_A + (Key)(c - 'A');
1638 else if (c >= 'a' && c <= 'z')
1639 key = KSYM_a + (Key)(c - 'a');
1640 else if (c >= '0' && c <= '9')
1641 key = KSYM_0 + (Key)(c - '0');
1643 #if !defined(TARGET_SDL2)
1644 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1646 char c = name_ptr[6];
1648 if (c >= '0' && c <= '9')
1649 key = KSYM_KP_0 + (Key)(c - '0');
1652 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1654 char c1 = name_ptr[4];
1655 char c2 = name_ptr[5];
1658 if ((c1 >= '0' && c1 <= '9') &&
1659 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1660 d = atoi(&name_ptr[4]);
1662 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1663 key = KSYM_F1 + (Key)(d - 1);
1665 else if (strPrefix(name_ptr, "XK_"))
1671 if (strEqual(name_ptr, translate_key[i].x11name))
1673 key = translate_key[i].key;
1677 while (translate_key[++i].x11name);
1679 else if (strPrefix(name_ptr, "0x"))
1681 unsigned int value = 0;
1687 char c = *name_ptr++;
1690 if (c >= '0' && c <= '9')
1692 else if (c >= 'a' && c <= 'f')
1693 d = (int)(c - 'a' + 10);
1694 else if (c >= 'A' && c <= 'F')
1695 d = (int)(c - 'A' + 10);
1703 value = value * 16 + d;
1714 char *getKeyNameFromKey(Key key)
1718 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1722 char *getX11KeyNameFromKey(Key key)
1726 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1730 Key getKeyFromKeyName(char *name)
1734 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1738 Key getKeyFromX11KeyName(char *x11name)
1742 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1746 char getCharFromKey(Key key)
1752 } translate_key_char[] =
1754 /* special (non-ASCII) keys (ISO-8859-1) */
1755 { KSYM_degree, CHAR_BYTE_DEGREE },
1756 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1757 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1758 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1759 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1760 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1761 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1762 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1764 /* end-of-array identifier */
1768 char *keyname = getKeyNameFromKey(key);
1771 if (strlen(keyname) == 1)
1773 else if (strEqual(keyname, "space"))
1781 if (key == translate_key_char[i].key)
1783 c = translate_key_char[i].key_char;
1788 while (translate_key_char[++i].key_char);
1794 char getValidConfigValueChar(char c)
1796 if (c == '#' || /* used to mark comments */
1797 c == '\\') /* used to mark continued lines */
1804 /* ------------------------------------------------------------------------- */
1805 /* functions to translate string identifiers to integer or boolean value */
1806 /* ------------------------------------------------------------------------- */
1808 int get_integer_from_string(char *s)
1810 static char *number_text[][3] =
1812 { "0", "zero", "null", },
1813 { "1", "one", "first" },
1814 { "2", "two", "second" },
1815 { "3", "three", "third" },
1816 { "4", "four", "fourth" },
1817 { "5", "five", "fifth" },
1818 { "6", "six", "sixth" },
1819 { "7", "seven", "seventh" },
1820 { "8", "eight", "eighth" },
1821 { "9", "nine", "ninth" },
1822 { "10", "ten", "tenth" },
1823 { "11", "eleven", "eleventh" },
1824 { "12", "twelve", "twelfth" },
1826 { NULL, NULL, NULL },
1830 char *s_lower = getStringToLower(s);
1833 for (i = 0; number_text[i][0] != NULL; i++)
1834 for (j = 0; j < 3; j++)
1835 if (strEqual(s_lower, number_text[i][j]))
1840 if (strEqual(s_lower, "false") ||
1841 strEqual(s_lower, "no") ||
1842 strEqual(s_lower, "off"))
1844 else if (strEqual(s_lower, "true") ||
1845 strEqual(s_lower, "yes") ||
1846 strEqual(s_lower, "on"))
1857 boolean get_boolean_from_string(char *s)
1859 char *s_lower = getStringToLower(s);
1860 boolean result = FALSE;
1862 if (strEqual(s_lower, "true") ||
1863 strEqual(s_lower, "yes") ||
1864 strEqual(s_lower, "on") ||
1865 get_integer_from_string(s) == 1)
1873 int get_switch3_from_string(char *s)
1875 char *s_lower = getStringToLower(s);
1878 if (strEqual(s_lower, "true") ||
1879 strEqual(s_lower, "yes") ||
1880 strEqual(s_lower, "on") ||
1881 get_integer_from_string(s) == 1)
1883 else if (strEqual(s_lower, "auto"))
1892 /* ------------------------------------------------------------------------- */
1893 /* functions for generic lists */
1894 /* ------------------------------------------------------------------------- */
1896 ListNode *newListNode()
1898 return checked_calloc(sizeof(ListNode));
1901 void addNodeToList(ListNode **node_first, char *key, void *content)
1903 ListNode *node_new = newListNode();
1905 node_new->key = getStringCopy(key);
1906 node_new->content = content;
1907 node_new->next = *node_first;
1908 *node_first = node_new;
1911 void deleteNodeFromList(ListNode **node_first, char *key,
1912 void (*destructor_function)(void *))
1914 if (node_first == NULL || *node_first == NULL)
1917 if (strEqual((*node_first)->key, key))
1919 checked_free((*node_first)->key);
1920 if (destructor_function)
1921 destructor_function((*node_first)->content);
1922 *node_first = (*node_first)->next;
1925 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1928 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1930 if (node_first == NULL)
1933 if (strEqual(node_first->key, key))
1936 return getNodeFromKey(node_first->next, key);
1939 int getNumNodes(ListNode *node_first)
1941 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1944 void dumpList(ListNode *node_first)
1946 ListNode *node = node_first;
1950 printf("['%s' (%d)]\n", node->key,
1951 ((struct ListNodeInfo *)node->content)->num_references);
1955 printf("[%d nodes]\n", getNumNodes(node_first));
1959 /* ------------------------------------------------------------------------- */
1960 /* functions for file handling */
1961 /* ------------------------------------------------------------------------- */
1963 File *openFile(char *filename, char *mode)
1965 File *file = checked_calloc(sizeof(File));
1967 file->file = fopen(filename, mode);
1969 if (file->file != NULL)
1971 file->filename = getStringCopy(filename);
1976 #if defined(PLATFORM_ANDROID)
1977 file->asset_file = SDL_RWFromFile(filename, mode);
1979 if (file->asset_file != NULL)
1981 file->file_is_asset = TRUE;
1982 file->filename = getStringCopy(filename);
1993 int closeFile(File *file)
2000 #if defined(PLATFORM_ANDROID)
2001 if (file->asset_file)
2002 result = SDL_RWclose(file->asset_file);
2006 result = fclose(file->file);
2008 checked_free(file->filename);
2014 int checkEndOfFile(File *file)
2016 #if defined(PLATFORM_ANDROID)
2017 if (file->file_is_asset)
2018 return file->end_of_file;
2021 return feof(file->file);
2024 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2026 #if defined(PLATFORM_ANDROID)
2027 if (file->file_is_asset)
2029 if (file->end_of_file)
2032 size_t num_items_read =
2033 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2035 if (num_items_read < num_items)
2036 file->end_of_file = TRUE;
2038 return num_items_read;
2042 return fread(buffer, item_size, num_items, file->file);
2045 int seekFile(File *file, long offset, int whence)
2047 #if defined(PLATFORM_ANDROID)
2048 if (file->file_is_asset)
2050 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2051 whence == SEEK_CUR ? RW_SEEK_CUR :
2052 whence == SEEK_END ? RW_SEEK_END : 0);
2054 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2058 return fseek(file->file, offset, whence);
2061 int getByteFromFile(File *file)
2063 #if defined(PLATFORM_ANDROID)
2064 if (file->file_is_asset)
2066 if (file->end_of_file)
2070 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2072 if (num_bytes_read < 1)
2073 file->end_of_file = TRUE;
2075 return (file->end_of_file ? EOF : (int)c);
2079 return fgetc(file->file);
2082 char *getStringFromFile(File *file, char *line, int size)
2084 #if defined(PLATFORM_ANDROID)
2085 if (file->file_is_asset)
2087 if (file->end_of_file)
2090 char *line_ptr = line;
2091 int num_bytes_read = 0;
2093 while (num_bytes_read < size - 1 &&
2094 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2095 *line_ptr++ != '\n')
2100 if (strlen(line) == 0)
2102 file->end_of_file = TRUE;
2111 return fgets(line, size, file->file);
2115 /* ------------------------------------------------------------------------- */
2116 /* functions for directory handling */
2117 /* ------------------------------------------------------------------------- */
2119 Directory *openDirectory(char *dir_name)
2121 Directory *dir = checked_calloc(sizeof(Directory));
2123 dir->dir = opendir(dir_name);
2125 if (dir->dir != NULL)
2127 dir->filename = getStringCopy(dir_name);
2132 #if defined(PLATFORM_ANDROID)
2133 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2135 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2137 checked_free(asset_toc_filename);
2139 if (dir->asset_toc_file != NULL)
2141 dir->directory_is_asset = TRUE;
2142 dir->filename = getStringCopy(dir_name);
2153 int closeDirectory(Directory *dir)
2160 #if defined(PLATFORM_ANDROID)
2161 if (dir->asset_toc_file)
2162 result = SDL_RWclose(dir->asset_toc_file);
2166 result = closedir(dir->dir);
2169 freeDirectoryEntry(dir->dir_entry);
2171 checked_free(dir->filename);
2177 DirectoryEntry *readDirectory(Directory *dir)
2180 freeDirectoryEntry(dir->dir_entry);
2182 dir->dir_entry = NULL;
2184 #if defined(PLATFORM_ANDROID)
2185 if (dir->directory_is_asset)
2187 char line[MAX_LINE_LEN];
2188 char *line_ptr = line;
2189 int num_bytes_read = 0;
2191 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2192 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2201 if (strlen(line) == 0)
2204 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2206 dir->dir_entry->is_directory = FALSE;
2207 if (line[strlen(line) - 1] == '/')
2209 dir->dir_entry->is_directory = TRUE;
2211 line[strlen(line) - 1] = '\0';
2214 dir->dir_entry->basename = getStringCopy(line);
2215 dir->dir_entry->filename = getPath2(dir->filename, line);
2217 return dir->dir_entry;
2221 struct dirent *dir_entry = readdir(dir->dir);
2223 if (dir_entry == NULL)
2226 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2228 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2229 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2231 struct stat file_status;
2233 dir->dir_entry->is_directory =
2234 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2235 (file_status.st_mode & S_IFMT) == S_IFDIR);
2237 return dir->dir_entry;
2240 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2242 if (dir_entry == NULL)
2245 checked_free(dir_entry->basename);
2246 checked_free(dir_entry->filename);
2247 checked_free(dir_entry);
2251 /* ------------------------------------------------------------------------- */
2252 /* functions for checking files and filenames */
2253 /* ------------------------------------------------------------------------- */
2255 boolean directoryExists(char *dir_name)
2257 if (dir_name == NULL)
2260 struct stat file_status;
2261 boolean success = (stat(dir_name, &file_status) == 0 &&
2262 (file_status.st_mode & S_IFMT) == S_IFDIR);
2264 #if defined(PLATFORM_ANDROID)
2267 // this might be an asset directory; check by trying to open toc file
2268 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2269 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2271 checked_free(asset_toc_filename);
2273 success = (file != NULL);
2283 boolean fileExists(char *filename)
2285 if (filename == NULL)
2288 boolean success = (access(filename, F_OK) == 0);
2290 #if defined(PLATFORM_ANDROID)
2293 // this might be an asset file; check by trying to open it
2294 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2296 success = (file != NULL);
2306 boolean fileHasPrefix(char *basename, char *prefix)
2308 static char *basename_lower = NULL;
2309 int basename_length, prefix_length;
2311 checked_free(basename_lower);
2313 if (basename == NULL || prefix == NULL)
2316 basename_lower = getStringToLower(basename);
2317 basename_length = strlen(basename_lower);
2318 prefix_length = strlen(prefix);
2320 if (basename_length > prefix_length + 1 &&
2321 basename_lower[prefix_length] == '.' &&
2322 strncmp(basename_lower, prefix, prefix_length) == 0)
2328 boolean fileHasSuffix(char *basename, char *suffix)
2330 static char *basename_lower = NULL;
2331 int basename_length, suffix_length;
2333 checked_free(basename_lower);
2335 if (basename == NULL || suffix == NULL)
2338 basename_lower = getStringToLower(basename);
2339 basename_length = strlen(basename_lower);
2340 suffix_length = strlen(suffix);
2342 if (basename_length > suffix_length + 1 &&
2343 basename_lower[basename_length - suffix_length - 1] == '.' &&
2344 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2350 static boolean FileCouldBeArtwork(char *filename)
2352 char *basename = getBaseNamePtr(filename);
2354 return (!strEqual(basename, ".") &&
2355 !strEqual(basename, "..") &&
2356 !fileHasSuffix(basename, "txt") &&
2357 !fileHasSuffix(basename, "conf") &&
2358 !directoryExists(filename));
2361 boolean FileIsGraphic(char *filename)
2363 return FileCouldBeArtwork(filename);
2366 boolean FileIsSound(char *filename)
2368 return FileCouldBeArtwork(filename);
2371 boolean FileIsMusic(char *filename)
2373 return FileCouldBeArtwork(filename);
2376 boolean FileIsArtworkType(char *filename, int type)
2378 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2379 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2380 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2386 /* ------------------------------------------------------------------------- */
2387 /* functions for loading artwork configuration information */
2388 /* ------------------------------------------------------------------------- */
2390 char *get_mapped_token(char *token)
2392 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2393 static char *map_token_prefix[][2] =
2395 { "char_procent", "char_percent" },
2400 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2402 int len_token_prefix = strlen(map_token_prefix[i][0]);
2404 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2405 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2411 /* This function checks if a string <s> of the format "string1, string2, ..."
2412 exactly contains a string <s_contained>. */
2414 static boolean string_has_parameter(char *s, char *s_contained)
2418 if (s == NULL || s_contained == NULL)
2421 if (strlen(s_contained) > strlen(s))
2424 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2426 char next_char = s[strlen(s_contained)];
2428 /* check if next character is delimiter or whitespace */
2429 return (next_char == ',' || next_char == '\0' ||
2430 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2433 /* check if string contains another parameter string after a comma */
2434 substring = strchr(s, ',');
2435 if (substring == NULL) /* string does not contain a comma */
2438 /* advance string pointer to next character after the comma */
2441 /* skip potential whitespaces after the comma */
2442 while (*substring == ' ' || *substring == '\t')
2445 return string_has_parameter(substring, s_contained);
2448 int get_parameter_value(char *value_raw, char *suffix, int type)
2450 char *value = getStringToLower(value_raw);
2451 int result = 0; /* probably a save default value */
2453 if (strEqual(suffix, ".direction"))
2455 result = (strEqual(value, "left") ? MV_LEFT :
2456 strEqual(value, "right") ? MV_RIGHT :
2457 strEqual(value, "up") ? MV_UP :
2458 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2460 else if (strEqual(suffix, ".align"))
2462 result = (strEqual(value, "left") ? ALIGN_LEFT :
2463 strEqual(value, "right") ? ALIGN_RIGHT :
2464 strEqual(value, "center") ? ALIGN_CENTER :
2465 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2467 else if (strEqual(suffix, ".valign"))
2469 result = (strEqual(value, "top") ? VALIGN_TOP :
2470 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2471 strEqual(value, "middle") ? VALIGN_MIDDLE :
2472 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2474 else if (strEqual(suffix, ".anim_mode"))
2476 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2477 string_has_parameter(value, "loop") ? ANIM_LOOP :
2478 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2479 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2480 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2481 string_has_parameter(value, "random") ? ANIM_RANDOM :
2482 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2483 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2484 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2485 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2486 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2487 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2490 if (string_has_parameter(value, "reverse"))
2491 result |= ANIM_REVERSE;
2493 if (string_has_parameter(value, "opaque_player"))
2494 result |= ANIM_OPAQUE_PLAYER;
2496 if (string_has_parameter(value, "static_panel"))
2497 result |= ANIM_STATIC_PANEL;
2499 else if (strEqual(suffix, ".class"))
2501 result = get_hash_from_key(value);
2503 else if (strEqual(suffix, ".style"))
2505 result = STYLE_DEFAULT;
2507 if (string_has_parameter(value, "accurate_borders"))
2508 result |= STYLE_ACCURATE_BORDERS;
2510 if (string_has_parameter(value, "inner_corners"))
2511 result |= STYLE_INNER_CORNERS;
2513 else if (strEqual(suffix, ".fade_mode"))
2515 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2516 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2517 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2518 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2521 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2523 result = gfx.get_font_from_token_function(value);
2525 else /* generic parameter of type integer or boolean */
2527 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2528 type == TYPE_INTEGER ? get_integer_from_string(value) :
2529 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2530 ARG_UNDEFINED_VALUE);
2538 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2540 static struct ScreenModeInfo screen_mode;
2541 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2542 char *screen_mode_string_copy;
2543 char *screen_mode_string_pos_w;
2544 char *screen_mode_string_pos_h;
2546 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2549 screen_mode_string_copy = getStringCopy(screen_mode_string);
2551 screen_mode_string_pos_w = screen_mode_string_copy;
2552 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2553 *screen_mode_string_pos_h++ = '\0';
2555 screen_mode.width = atoi(screen_mode_string_pos_w);
2556 screen_mode.height = atoi(screen_mode_string_pos_h);
2558 return &screen_mode;
2561 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2564 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2565 float aspect_ratio_new;
2570 *x = i * aspect_ratio + 0.000001;
2573 aspect_ratio_new = (float)*x / (float)*y;
2577 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2580 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2581 struct ListNodeInfo ***, int *);
2583 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2584 struct ConfigTypeInfo *suffix_list,
2585 char **ignore_tokens,
2586 int num_file_list_entries)
2588 struct FileInfo *file_list;
2589 int num_file_list_entries_found = 0;
2590 int num_suffix_list_entries = 0;
2594 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2596 for (i = 0; suffix_list[i].token != NULL; i++)
2597 num_suffix_list_entries++;
2599 /* always start with reliable default values */
2600 for (i = 0; i < num_file_list_entries; i++)
2602 file_list[i].token = NULL;
2604 file_list[i].default_filename = NULL;
2605 file_list[i].filename = NULL;
2607 if (num_suffix_list_entries > 0)
2609 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2611 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2612 file_list[i].parameter = checked_calloc(parameter_array_size);
2614 for (j = 0; j < num_suffix_list_entries; j++)
2616 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2617 setString(&file_list[i].parameter[j], suffix_list[j].value);
2620 file_list[i].redefined = FALSE;
2621 file_list[i].fallback_to_default = FALSE;
2622 file_list[i].default_is_cloned = FALSE;
2628 for (i = 0; config_list[i].token != NULL; i++)
2630 int len_config_token = strlen(config_list[i].token);
2631 boolean is_file_entry = TRUE;
2633 for (j = 0; suffix_list[j].token != NULL; j++)
2635 int len_suffix = strlen(suffix_list[j].token);
2637 if (len_suffix < len_config_token &&
2638 strEqual(&config_list[i].token[len_config_token - len_suffix],
2639 suffix_list[j].token))
2641 setString(&file_list[list_pos].default_parameter[j],
2642 config_list[i].value);
2644 is_file_entry = FALSE;
2650 /* the following tokens are no file definitions, but other config tokens */
2651 for (j = 0; ignore_tokens[j] != NULL; j++)
2652 if (strEqual(config_list[i].token, ignore_tokens[j]))
2653 is_file_entry = FALSE;
2660 if (list_pos >= num_file_list_entries)
2663 file_list[list_pos].token = config_list[i].token;
2664 file_list[list_pos].default_filename = config_list[i].value;
2667 if (strSuffix(config_list[i].token, ".clone_from"))
2668 file_list[list_pos].default_is_cloned = TRUE;
2671 num_file_list_entries_found = list_pos + 1;
2672 if (num_file_list_entries_found != num_file_list_entries)
2674 Error(ERR_INFO_LINE, "-");
2675 Error(ERR_INFO, "inconsistant config list information:");
2676 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2677 num_file_list_entries);
2678 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2679 num_file_list_entries_found);
2680 Error(ERR_EXIT, "please fix");
2686 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2688 int len_token = strlen(token);
2689 int len_suffix = strlen(suffix);
2691 if (start_pos < 0) /* compare suffix from end of string */
2692 start_pos += len_token;
2694 if (start_pos < 0 || start_pos + len_suffix > len_token)
2697 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2700 if (token[start_pos + len_suffix] == '\0')
2703 if (token[start_pos + len_suffix] == '.')
2709 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2711 static void read_token_parameters(SetupFileHash *setup_file_hash,
2712 struct ConfigTypeInfo *suffix_list,
2713 struct FileInfo *file_list_entry)
2715 /* check for config token that is the base token without any suffixes */
2716 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2717 char *known_token_value = KNOWN_TOKEN_VALUE;
2720 if (filename != NULL)
2722 setString(&file_list_entry->filename, filename);
2724 /* when file definition found, set all parameters to default values */
2725 for (i = 0; suffix_list[i].token != NULL; i++)
2726 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2728 file_list_entry->redefined = TRUE;
2730 /* mark config file token as well known from default config */
2731 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2734 /* check for config tokens that can be build by base token and suffixes */
2735 for (i = 0; suffix_list[i].token != NULL; i++)
2737 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2738 char *value = getHashEntry(setup_file_hash, token);
2742 setString(&file_list_entry->parameter[i], value);
2744 /* mark config file token as well known from default config */
2745 setHashEntry(setup_file_hash, token, known_token_value);
2752 static void add_dynamic_file_list_entry(struct FileInfo **list,
2753 int *num_list_entries,
2754 SetupFileHash *extra_file_hash,
2755 struct ConfigTypeInfo *suffix_list,
2756 int num_suffix_list_entries,
2759 struct FileInfo *new_list_entry;
2760 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2762 (*num_list_entries)++;
2763 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2764 new_list_entry = &(*list)[*num_list_entries - 1];
2766 new_list_entry->token = getStringCopy(token);
2767 new_list_entry->default_filename = NULL;
2768 new_list_entry->filename = NULL;
2769 new_list_entry->parameter = checked_calloc(parameter_array_size);
2771 new_list_entry->redefined = FALSE;
2772 new_list_entry->fallback_to_default = FALSE;
2773 new_list_entry->default_is_cloned = FALSE;
2775 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2778 static void add_property_mapping(struct PropertyMapping **list,
2779 int *num_list_entries,
2780 int base_index, int ext1_index,
2781 int ext2_index, int ext3_index,
2784 struct PropertyMapping *new_list_entry;
2786 (*num_list_entries)++;
2787 *list = checked_realloc(*list,
2788 *num_list_entries * sizeof(struct PropertyMapping));
2789 new_list_entry = &(*list)[*num_list_entries - 1];
2791 new_list_entry->base_index = base_index;
2792 new_list_entry->ext1_index = ext1_index;
2793 new_list_entry->ext2_index = ext2_index;
2794 new_list_entry->ext3_index = ext3_index;
2796 new_list_entry->artwork_index = artwork_index;
2799 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2802 struct FileInfo *file_list = artwork_info->file_list;
2803 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2804 char **base_prefixes = artwork_info->base_prefixes;
2805 char **ext1_suffixes = artwork_info->ext1_suffixes;
2806 char **ext2_suffixes = artwork_info->ext2_suffixes;
2807 char **ext3_suffixes = artwork_info->ext3_suffixes;
2808 char **ignore_tokens = artwork_info->ignore_tokens;
2809 int num_file_list_entries = artwork_info->num_file_list_entries;
2810 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2811 int num_base_prefixes = artwork_info->num_base_prefixes;
2812 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2813 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2814 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2815 int num_ignore_tokens = artwork_info->num_ignore_tokens;
2816 SetupFileHash *setup_file_hash, *valid_file_hash;
2817 SetupFileHash *extra_file_hash, *empty_file_hash;
2818 char *known_token_value = KNOWN_TOKEN_VALUE;
2821 if (filename == NULL)
2824 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2827 /* separate valid (defined) from empty (undefined) config token values */
2828 valid_file_hash = newSetupFileHash();
2829 empty_file_hash = newSetupFileHash();
2830 BEGIN_HASH_ITERATION(setup_file_hash, itr)
2832 char *value = HASH_ITERATION_VALUE(itr);
2834 setHashEntry(*value ? valid_file_hash : empty_file_hash,
2835 HASH_ITERATION_TOKEN(itr), value);
2837 END_HASH_ITERATION(setup_file_hash, itr)
2839 /* at this point, we do not need the setup file hash anymore -- free it */
2840 freeSetupFileHash(setup_file_hash);
2842 /* map deprecated to current tokens (using prefix match and replace) */
2843 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2845 char *token = HASH_ITERATION_TOKEN(itr);
2846 char *mapped_token = get_mapped_token(token);
2848 if (mapped_token != NULL)
2850 char *value = HASH_ITERATION_VALUE(itr);
2852 /* add mapped token */
2853 setHashEntry(valid_file_hash, mapped_token, value);
2855 /* ignore old token (by setting it to "known" keyword) */
2856 setHashEntry(valid_file_hash, token, known_token_value);
2861 END_HASH_ITERATION(valid_file_hash, itr)
2863 /* read parameters for all known config file tokens */
2864 for (i = 0; i < num_file_list_entries; i++)
2865 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2867 /* set all tokens that can be ignored here to "known" keyword */
2868 for (i = 0; i < num_ignore_tokens; i++)
2869 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2871 /* copy all unknown config file tokens to extra config hash */
2872 extra_file_hash = newSetupFileHash();
2873 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2875 char *value = HASH_ITERATION_VALUE(itr);
2877 if (!strEqual(value, known_token_value))
2878 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2880 END_HASH_ITERATION(valid_file_hash, itr)
2882 /* at this point, we do not need the valid file hash anymore -- free it */
2883 freeSetupFileHash(valid_file_hash);
2885 /* now try to determine valid, dynamically defined config tokens */
2887 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2889 struct FileInfo **dynamic_file_list =
2890 &artwork_info->dynamic_file_list;
2891 int *num_dynamic_file_list_entries =
2892 &artwork_info->num_dynamic_file_list_entries;
2893 struct PropertyMapping **property_mapping =
2894 &artwork_info->property_mapping;
2895 int *num_property_mapping_entries =
2896 &artwork_info->num_property_mapping_entries;
2897 int current_summarized_file_list_entry =
2898 artwork_info->num_file_list_entries +
2899 artwork_info->num_dynamic_file_list_entries;
2900 char *token = HASH_ITERATION_TOKEN(itr);
2901 int len_token = strlen(token);
2903 boolean base_prefix_found = FALSE;
2904 boolean parameter_suffix_found = FALSE;
2906 /* skip all parameter definitions (handled by read_token_parameters()) */
2907 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2909 int len_suffix = strlen(suffix_list[i].token);
2911 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2912 parameter_suffix_found = TRUE;
2915 if (parameter_suffix_found)
2918 /* ---------- step 0: search for matching base prefix ---------- */
2921 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2923 char *base_prefix = base_prefixes[i];
2924 int len_base_prefix = strlen(base_prefix);
2925 boolean ext1_suffix_found = FALSE;
2926 boolean ext2_suffix_found = FALSE;
2927 boolean ext3_suffix_found = FALSE;
2928 boolean exact_match = FALSE;
2929 int base_index = -1;
2930 int ext1_index = -1;
2931 int ext2_index = -1;
2932 int ext3_index = -1;
2934 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2936 if (!base_prefix_found)
2941 if (start_pos + len_base_prefix == len_token) /* exact match */
2945 add_dynamic_file_list_entry(dynamic_file_list,
2946 num_dynamic_file_list_entries,
2949 num_suffix_list_entries,
2951 add_property_mapping(property_mapping,
2952 num_property_mapping_entries,
2953 base_index, -1, -1, -1,
2954 current_summarized_file_list_entry);
2958 /* ---------- step 1: search for matching first suffix ---------- */
2960 start_pos += len_base_prefix;
2961 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
2963 char *ext1_suffix = ext1_suffixes[j];
2964 int len_ext1_suffix = strlen(ext1_suffix);
2966 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2968 if (!ext1_suffix_found)
2973 if (start_pos + len_ext1_suffix == len_token) /* exact match */
2977 add_dynamic_file_list_entry(dynamic_file_list,
2978 num_dynamic_file_list_entries,
2981 num_suffix_list_entries,
2983 add_property_mapping(property_mapping,
2984 num_property_mapping_entries,
2985 base_index, ext1_index, -1, -1,
2986 current_summarized_file_list_entry);
2990 start_pos += len_ext1_suffix;
2996 /* ---------- step 2: search for matching second suffix ---------- */
2998 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3000 char *ext2_suffix = ext2_suffixes[k];
3001 int len_ext2_suffix = strlen(ext2_suffix);
3003 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3005 if (!ext2_suffix_found)
3010 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3014 add_dynamic_file_list_entry(dynamic_file_list,
3015 num_dynamic_file_list_entries,
3018 num_suffix_list_entries,
3020 add_property_mapping(property_mapping,
3021 num_property_mapping_entries,
3022 base_index, ext1_index, ext2_index, -1,
3023 current_summarized_file_list_entry);
3027 start_pos += len_ext2_suffix;
3033 /* ---------- step 3: search for matching third suffix ---------- */
3035 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3037 char *ext3_suffix = ext3_suffixes[l];
3038 int len_ext3_suffix = strlen(ext3_suffix);
3040 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3042 if (!ext3_suffix_found)
3047 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3051 add_dynamic_file_list_entry(dynamic_file_list,
3052 num_dynamic_file_list_entries,
3055 num_suffix_list_entries,
3057 add_property_mapping(property_mapping,
3058 num_property_mapping_entries,
3059 base_index, ext1_index, ext2_index, ext3_index,
3060 current_summarized_file_list_entry);
3066 END_HASH_ITERATION(extra_file_hash, itr)
3068 if (artwork_info->num_dynamic_file_list_entries > 0)
3070 artwork_info->dynamic_artwork_list =
3071 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3072 artwork_info->sizeof_artwork_list_entry);
3075 if (options.verbose && IS_PARENT_PROCESS())
3077 SetupFileList *setup_file_list, *list;
3078 boolean dynamic_tokens_found = FALSE;
3079 boolean unknown_tokens_found = FALSE;
3080 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3082 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3083 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3085 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3087 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3088 dynamic_tokens_found = TRUE;
3090 unknown_tokens_found = TRUE;
3092 END_HASH_ITERATION(extra_file_hash, itr)
3094 if (options.debug && dynamic_tokens_found)
3096 Error(ERR_INFO_LINE, "-");
3097 Error(ERR_INFO, "dynamic token(s) found in config file:");
3098 Error(ERR_INFO, "- config file: '%s'", filename);
3100 for (list = setup_file_list; list != NULL; list = list->next)
3102 char *value = getHashEntry(extra_file_hash, list->token);
3104 if (value != NULL && strEqual(value, known_token_value))
3105 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3108 Error(ERR_INFO_LINE, "-");
3111 if (unknown_tokens_found)
3113 Error(ERR_INFO_LINE, "-");
3114 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3115 Error(ERR_INFO, "- config file: '%s'", filename);
3117 for (list = setup_file_list; list != NULL; list = list->next)
3119 char *value = getHashEntry(extra_file_hash, list->token);
3121 if (value != NULL && !strEqual(value, known_token_value))
3122 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3125 Error(ERR_INFO_LINE, "-");
3128 if (undefined_values_found)
3130 Error(ERR_INFO_LINE, "-");
3131 Error(ERR_INFO, "warning: undefined values found in config file:");
3132 Error(ERR_INFO, "- config file: '%s'", filename);
3134 for (list = setup_file_list; list != NULL; list = list->next)
3136 char *value = getHashEntry(empty_file_hash, list->token);
3139 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3142 Error(ERR_INFO_LINE, "-");
3145 freeSetupFileList(setup_file_list);
3148 freeSetupFileHash(extra_file_hash);
3149 freeSetupFileHash(empty_file_hash);
3152 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3154 struct FileInfo *file_list = artwork_info->file_list;
3155 int num_file_list_entries = artwork_info->num_file_list_entries;
3156 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3157 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3160 DrawInitText("Loading artwork config", 120, FC_GREEN);
3161 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3163 /* always start with reliable default values */
3164 for (i = 0; i < num_file_list_entries; i++)
3166 setString(&file_list[i].filename, file_list[i].default_filename);
3168 for (j = 0; j < num_suffix_list_entries; j++)
3169 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3171 file_list[i].redefined = FALSE;
3172 file_list[i].fallback_to_default = FALSE;
3175 /* free previous dynamic artwork file array */
3176 if (artwork_info->dynamic_file_list != NULL)
3178 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3180 free(artwork_info->dynamic_file_list[i].token);
3181 free(artwork_info->dynamic_file_list[i].filename);
3182 free(artwork_info->dynamic_file_list[i].parameter);
3185 free(artwork_info->dynamic_file_list);
3186 artwork_info->dynamic_file_list = NULL;
3188 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3189 &artwork_info->num_dynamic_file_list_entries);
3192 /* free previous property mapping */
3193 if (artwork_info->property_mapping != NULL)
3195 free(artwork_info->property_mapping);
3197 artwork_info->property_mapping = NULL;
3198 artwork_info->num_property_mapping_entries = 0;
3201 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3203 /* first look for special artwork configured in level series config */
3204 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3206 if (fileExists(filename_base))
3207 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3210 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3212 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3213 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3216 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3217 struct ListNodeInfo **listnode)
3221 char *filename = (*listnode)->source_filename;
3223 if (--(*listnode)->num_references <= 0)
3224 deleteNodeFromList(&artwork_info->content_list, filename,
3225 artwork_info->free_artwork);
3231 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3232 struct ListNodeInfo **listnode,
3233 struct FileInfo *file_list_entry)
3243 char *basename = file_list_entry->filename;
3244 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3246 if (filename == NULL)
3248 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3250 basename = file_list_entry->default_filename;
3252 /* fail for cloned default artwork that has no default filename defined */
3253 if (file_list_entry->default_is_cloned &&
3254 strEqual(basename, UNDEFINED_FILENAME))
3256 int error_mode = ERR_WARN;
3258 /* we can get away without sounds and music, but not without graphics */
3259 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3260 error_mode = ERR_EXIT;
3262 Error(error_mode, "token '%s' was cloned and has no default filename",
3263 file_list_entry->token);
3268 /* dynamic artwork has no default filename / skip empty default artwork */
3269 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3272 file_list_entry->fallback_to_default = TRUE;
3274 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3276 filename = getCustomArtworkFilename(basename, artwork_info->type);
3278 if (filename == NULL)
3280 int error_mode = ERR_WARN;
3282 /* we can get away without sounds and music, but not without graphics */
3283 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3284 error_mode = ERR_EXIT;
3286 Error(error_mode, "cannot find default artwork file '%s'", basename);
3292 /* check if the old and the new artwork file are the same */
3293 if (*listnode && strEqual((*listnode)->source_filename, filename))
3295 /* The old and new artwork are the same (have the same filename and path).
3296 This usually means that this artwork does not exist in this artwork set
3297 and a fallback to the existing artwork is done. */
3302 /* delete existing artwork file entry */
3303 deleteArtworkListEntry(artwork_info, listnode);
3305 /* check if the new artwork file already exists in the list of artwork */
3306 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3308 *listnode = (struct ListNodeInfo *)node->content;
3309 (*listnode)->num_references++;
3314 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3315 DrawInitText(basename, 150, FC_YELLOW);
3317 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3319 /* add new artwork file entry to the list of artwork files */
3320 (*listnode)->num_references = 1;
3321 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3326 int error_mode = ERR_WARN;
3328 /* we can get away without sounds and music, but not without graphics */
3329 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3330 error_mode = ERR_EXIT;
3332 Error(error_mode, "cannot load artwork file '%s'", basename);
3338 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3339 struct ListNodeInfo **listnode,
3340 struct FileInfo *file_list_entry)
3342 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3344 deleteArtworkListEntry(artwork_info, listnode);
3349 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3352 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3354 struct FileInfo *file_list = artwork_info->file_list;
3355 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3356 int num_file_list_entries = artwork_info->num_file_list_entries;
3357 int num_dynamic_file_list_entries =
3358 artwork_info->num_dynamic_file_list_entries;
3361 print_timestamp_init("ReloadCustomArtworkList");
3363 for (i = 0; i < num_file_list_entries; i++)
3364 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3367 for (i = 0; i < num_dynamic_file_list_entries; i++)
3368 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3369 &dynamic_file_list[i]);
3371 print_timestamp_done("ReloadCustomArtworkList");
3374 dumpList(artwork_info->content_list);
3378 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3379 struct ListNodeInfo ***list,
3380 int *num_list_entries)
3387 for (i = 0; i < *num_list_entries; i++)
3388 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3392 *num_list_entries = 0;
3395 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3397 if (artwork_info == NULL)
3400 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3401 &artwork_info->num_file_list_entries);
3403 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3404 &artwork_info->num_dynamic_file_list_entries);
3408 /* ------------------------------------------------------------------------- */
3409 /* functions only needed for non-Unix (non-command-line) systems */
3410 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3411 /* (now also added for Windows, to create files in user data directory) */
3412 /* ------------------------------------------------------------------------- */
3414 char *getErrorFilename(char *basename)
3416 return getPath2(getUserGameDataDir(), basename);
3419 void openErrorFile()
3421 InitUserDataDirectory();
3423 if ((program.error_file = fopen(program.error_filename, MODE_WRITE)) == NULL)
3425 program.error_file = stderr;
3427 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3428 program.error_filename, strerror(errno));
3431 /* error output should be unbuffered so it is not truncated in a crash */
3432 setbuf(program.error_file, NULL);
3435 void closeErrorFile()
3437 if (program.error_file != stderr) /* do not close stream 'stderr' */
3438 fclose(program.error_file);
3441 void dumpErrorFile()
3443 FILE *error_file = fopen(program.error_filename, MODE_READ);
3445 if (error_file != NULL)
3447 while (!feof(error_file))
3448 fputc(fgetc(error_file), stderr);
3454 void NotifyUserAboutErrorFile()
3456 #if defined(PLATFORM_WIN32)
3457 char *title_text = getStringCat2(program.program_title, " Error Message");
3458 char *error_text = getStringCat2("The program was aborted due to an error; "
3459 "for details, see the following error file:"
3460 STRING_NEWLINE, program.error_filename);
3462 MessageBox(NULL, error_text, title_text, MB_OK);
3467 /* ------------------------------------------------------------------------- */
3468 /* the following is only for debugging purpose and normally not used */
3469 /* ------------------------------------------------------------------------- */
3473 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3474 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3476 #define DEBUG_NUM_TIMESTAMPS 10
3477 #define DEBUG_TIME_IN_MICROSECONDS 0
3479 #if DEBUG_TIME_IN_MICROSECONDS
3480 static double Counter_Microseconds()
3482 static struct timeval base_time = { 0, 0 };
3483 struct timeval current_time;
3486 gettimeofday(¤t_time, NULL);
3488 /* reset base time in case of wrap-around */
3489 if (current_time.tv_sec < base_time.tv_sec)
3490 base_time = current_time;
3493 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3494 ((double)(current_time.tv_usec - base_time.tv_usec));
3496 return counter; /* return microseconds since last init */
3500 char *debug_print_timestamp_get_padding(int padding_size)
3502 static char *padding = NULL;
3503 int max_padding_size = 100;
3505 if (padding == NULL)
3507 padding = checked_calloc(max_padding_size + 1);
3508 memset(padding, ' ', max_padding_size);
3511 return &padding[MAX(0, max_padding_size - padding_size)];
3514 void debug_print_timestamp(int counter_nr, char *message)
3516 int indent_size = 8;
3517 int padding_size = 40;
3518 float timestamp_interval;
3521 Error(ERR_EXIT, "debugging: invalid negative counter");
3522 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3523 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3525 #if DEBUG_TIME_IN_MICROSECONDS
3526 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3529 counter[counter_nr][0] = Counter_Microseconds();
3531 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3534 counter[counter_nr][0] = Counter();
3537 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3538 counter[counter_nr][1] = counter[counter_nr][0];
3541 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3542 debug_print_timestamp_get_padding(counter_nr * indent_size),
3544 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3545 timestamp_interval / 1000,
3549 void debug_print_parent_only(char *format, ...)
3551 if (!IS_PARENT_PROCESS())
3558 va_start(ap, format);
3559 vprintf(format, ap);
3568 void print_timestamp_ext(char *message, char *mode)
3570 #if DEBUG_PRINT_INIT_TIMESTAMPS
3571 static char *debug_message = NULL;
3572 static char *last_message = NULL;
3573 static int counter_nr = 0;
3574 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3576 checked_free(debug_message);
3577 debug_message = getStringCat3(mode, " ", message);
3579 if (strEqual(mode, "INIT"))
3581 debug_print_timestamp(counter_nr, NULL);
3583 if (counter_nr + 1 < max_depth)
3584 debug_print_timestamp(counter_nr, debug_message);
3588 debug_print_timestamp(counter_nr, NULL);
3590 else if (strEqual(mode, "DONE"))
3594 if (counter_nr + 1 < max_depth ||
3595 (counter_nr == 0 && max_depth == 1))
3597 last_message = message;
3599 if (counter_nr == 0 && max_depth == 1)
3601 checked_free(debug_message);
3602 debug_message = getStringCat3("TIME", " ", message);
3605 debug_print_timestamp(counter_nr, debug_message);
3608 else if (!strEqual(mode, "TIME") ||
3609 !strEqual(message, last_message))
3611 if (counter_nr < max_depth)
3612 debug_print_timestamp(counter_nr, debug_message);
3617 void print_timestamp_init(char *message)
3619 print_timestamp_ext(message, "INIT");
3622 void print_timestamp_time(char *message)
3624 print_timestamp_ext(message, "TIME");
3627 void print_timestamp_done(char *message)
3629 print_timestamp_ext(message, "DONE");