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 /* logging functions */
42 /* ------------------------------------------------------------------------- */
44 #define DUPLICATE_LOG_OUTPUT_TO_STDERR TRUE
47 #if defined(PLATFORM_ANDROID)
48 static int android_log_prio = ANDROID_LOG_INFO;
49 static char *android_log_buffer = NULL;
51 static void append_to_android_log_buffer(char *format, va_list ap)
53 char text_new[MAX_OUTPUT_LINESIZE];
55 // print text to temporary string
56 vsnprintf(text_new, MAX_OUTPUT_LINESIZE, format, ap);
58 if (android_log_buffer == NULL)
60 android_log_buffer = getStringCopy(text_new);
64 char *android_log_buffer_old = android_log_buffer;
66 // append new text to existing text
67 android_log_buffer = getStringCat2(android_log_buffer, text_new);
69 checked_free(android_log_buffer_old);
73 static void vprintf_log_nonewline(char *format, va_list ap)
75 // add log output to buffer until text with newline is printed
76 append_to_android_log_buffer(format, ap);
79 static void vprintf_log(char *format, va_list ap)
81 // add log output to buffer
82 append_to_android_log_buffer(format, ap);
84 // __android_log_vprint(android_log_prio, program.program_title, format, ap);
85 __android_log_write(android_log_prio, program.program_title,
88 checked_free(android_log_buffer);
89 android_log_buffer = NULL;
94 static void vprintf_log_nonewline(char *format, va_list ap)
96 FILE *file = program.error_file;
98 #if DUPLICATE_LOG_OUTPUT_TO_STDERR
104 vfprintf(stderr, format, ap2);
110 vfprintf(file, format, ap);
113 static void vprintf_log(char *format, va_list ap)
115 FILE *file = program.error_file;
116 char *newline = STRING_NEWLINE;
118 #if DUPLICATE_LOG_OUTPUT_TO_STDERR
124 vfprintf(stderr, format, ap2);
125 fprintf(stderr, "%s", newline);
131 vfprintf(file, format, ap);
132 fprintf(file, "%s", newline);
136 static void printf_log_nonewline(char *format, ...)
140 va_start(ap, format);
141 vprintf_log_nonewline(format, ap);
145 static void printf_log(char *format, ...)
149 va_start(ap, format);
150 vprintf_log(format, ap);
154 static void printf_log_line(char *line_chars, int line_length)
158 for (i = 0; i < line_length; i++)
159 printf_log_nonewline("%s", line_chars);
165 /* ------------------------------------------------------------------------- */
166 /* platform independent wrappers for printf() et al. */
167 /* ------------------------------------------------------------------------- */
169 void fprintf_line(FILE *file, char *line_chars, int line_length)
173 for (i = 0; i < line_length; i++)
174 fprintf(file, "%s", line_chars);
179 void fprintf_line_with_prefix(FILE *file, char *prefix, char *line_chars,
182 fprintf(file, "%s", prefix);
183 fprintf_line(file, line_chars, line_length);
186 void printf_line(char *line_chars, int line_length)
188 fprintf_line(stdout, line_chars, line_length);
191 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
193 fprintf_line_with_prefix(stdout, prefix, line_chars, line_length);
197 /* ------------------------------------------------------------------------- */
198 /* string functions */
199 /* ------------------------------------------------------------------------- */
201 /* int2str() returns a number converted to a string;
202 the used memory is static, but will be overwritten by later calls,
203 so if you want to save the result, copy it to a private string buffer;
204 there can be 10 local calls of int2str() without buffering the result --
205 the 11th call will then destroy the result from the first call and so on.
208 char *int2str(int number, int size)
210 static char shift_array[10][40];
211 static int shift_counter = 0;
212 char *s = shift_array[shift_counter];
214 shift_counter = (shift_counter + 1) % 10;
221 sprintf(s, " %09d", number);
222 return &s[strlen(s) - size];
226 sprintf(s, "%d", number);
232 /* something similar to "int2str()" above, but allocates its own memory
233 and has a different interface; we cannot use "itoa()", because this
234 seems to be already defined when cross-compiling to the win32 target */
236 char *i_to_a(unsigned int i)
238 static char *a = NULL;
242 if (i > 2147483647) /* yes, this is a kludge */
245 a = checked_malloc(10 + 1);
253 /* calculate base-2 logarithm of argument (rounded down to integer;
254 this function returns the number of the highest bit set in argument) */
256 int log_2(unsigned int x)
262 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
269 boolean getTokenValueFromString(char *string, char **token, char **value)
271 return getTokenValueFromSetupLine(string, token, value);
275 /* ------------------------------------------------------------------------- */
276 /* counter functions */
277 /* ------------------------------------------------------------------------- */
279 /* maximal allowed length of a command line option */
280 #define MAX_OPTION_LEN 256
282 static unsigned int getCurrentMS()
284 return SDL_GetTicks();
287 static unsigned int mainCounter(int mode)
289 static unsigned int base_ms = 0;
290 unsigned int current_ms;
292 /* get current system milliseconds */
293 current_ms = getCurrentMS();
295 /* reset base timestamp in case of counter reset or wrap-around */
296 if (mode == INIT_COUNTER || current_ms < base_ms)
297 base_ms = current_ms;
299 /* return milliseconds since last counter reset */
300 return current_ms - base_ms;
303 void InitCounter() /* set counter back to zero */
305 mainCounter(INIT_COUNTER);
308 unsigned int Counter() /* get milliseconds since last call of InitCounter() */
310 return mainCounter(READ_COUNTER);
313 static void sleep_milliseconds(unsigned int milliseconds_delay)
315 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
319 /* we want to wait only a few ms -- if we assume that we have a
320 kernel timer resolution of 10 ms, we would wait far to long;
321 therefore it's better to do a short interval of busy waiting
322 to get our sleeping time more accurate */
324 unsigned int base_counter = Counter(), actual_counter = Counter();
326 while (actual_counter < base_counter + milliseconds_delay &&
327 actual_counter >= base_counter)
328 actual_counter = Counter();
332 SDL_Delay(milliseconds_delay);
336 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
338 sleep_milliseconds(delay);
341 boolean FrameReached(unsigned int *frame_counter_var,
342 unsigned int frame_delay)
344 unsigned int actual_frame_counter = FrameCounter;
346 if (actual_frame_counter >= *frame_counter_var &&
347 actual_frame_counter < *frame_counter_var + frame_delay)
350 *frame_counter_var = actual_frame_counter;
355 boolean DelayReached(unsigned int *counter_var,
358 unsigned int actual_counter = Counter();
360 if (actual_counter >= *counter_var &&
361 actual_counter < *counter_var + delay)
364 *counter_var = actual_counter;
369 void WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
371 unsigned int actual_counter;
375 actual_counter = Counter();
377 if (actual_counter >= *counter_var &&
378 actual_counter < *counter_var + delay)
379 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
384 *counter_var = actual_counter;
388 /* ------------------------------------------------------------------------- */
389 /* random generator functions */
390 /* ------------------------------------------------------------------------- */
392 unsigned int init_random_number(int nr, int seed)
394 if (seed == NEW_RANDOMIZE)
396 /* default random seed */
397 seed = (int)time(NULL); // seconds since the epoch
399 #if !defined(PLATFORM_WIN32)
400 /* add some more randomness */
401 struct timeval current_time;
403 gettimeofday(¤t_time, NULL);
405 seed += (int)current_time.tv_usec; // microseconds since the epoch
408 /* add some more randomness */
409 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
411 /* add some more randomness */
412 seed += GetSimpleRandom(1000000);
415 srandom_linux_libc(nr, (unsigned int) seed);
417 return (unsigned int) seed;
420 unsigned int get_random_number(int nr, int max)
422 return (max > 0 ? random_linux_libc(nr) % max : 0);
426 /* ------------------------------------------------------------------------- */
427 /* system info functions */
428 /* ------------------------------------------------------------------------- */
430 #if !defined(PLATFORM_ANDROID)
431 static char *get_corrected_real_name(char *real_name)
433 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
434 char *from_ptr = real_name;
435 char *to_ptr = real_name_new;
437 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
438 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
440 /* the name field read from "passwd" file may also contain additional
441 user information, separated by commas, which will be removed here */
442 if (*from_ptr == ',')
445 /* the user's real name may contain 'german sharp s' characters,
446 which have no equivalent in upper case letters (used by our fonts) */
447 if (*from_ptr == CHAR_BYTE_SHARP_S)
454 *to_ptr++ = *from_ptr++;
459 return real_name_new;
465 static char *login_name = NULL;
467 #if defined(PLATFORM_WIN32)
468 if (login_name == NULL)
470 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
471 login_name = checked_malloc(buffer_size);
473 if (GetUserName(login_name, &buffer_size) == 0)
474 strcpy(login_name, ANONYMOUS_NAME);
477 if (login_name == NULL)
481 if ((pwd = getpwuid(getuid())) == NULL)
482 login_name = ANONYMOUS_NAME;
484 login_name = getStringCopy(pwd->pw_name);
493 static char *real_name = NULL;
495 #if defined(PLATFORM_WIN32)
496 if (real_name == NULL)
498 static char buffer[MAX_USERNAME_LEN + 1];
499 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
501 if (GetUserName(buffer, &buffer_size) != 0)
502 real_name = get_corrected_real_name(buffer);
504 real_name = ANONYMOUS_NAME;
506 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
507 if (real_name == NULL)
511 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
512 real_name = get_corrected_real_name(pwd->pw_gecos);
514 real_name = ANONYMOUS_NAME;
517 real_name = ANONYMOUS_NAME;
523 time_t getFileTimestampEpochSeconds(char *filename)
525 struct stat file_status;
527 if (stat(filename, &file_status) != 0) /* cannot stat file */
530 return file_status.st_mtime;
534 /* ------------------------------------------------------------------------- */
535 /* path manipulation functions */
536 /* ------------------------------------------------------------------------- */
538 static char *getLastPathSeparatorPtr(char *filename)
540 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
542 if (last_separator == NULL) /* also try DOS/Windows variant */
543 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
545 return last_separator;
548 char *getBaseNamePtr(char *filename)
550 char *last_separator = getLastPathSeparatorPtr(filename);
552 if (last_separator != NULL)
553 return last_separator + 1; /* separator found: strip base path */
555 return filename; /* no separator found: filename has no path */
558 char *getBaseName(char *filename)
560 return getStringCopy(getBaseNamePtr(filename));
563 char *getBasePath(char *filename)
565 char *basepath = getStringCopy(filename);
566 char *last_separator = getLastPathSeparatorPtr(basepath);
568 if (last_separator != NULL)
569 *last_separator = '\0'; /* separator found: strip basename */
571 basepath = "."; /* no separator found: use current path */
576 static char *getProgramMainDataPath()
578 char *main_data_path = getStringCopy(program.command_basepath);
580 #if defined(PLATFORM_MACOSX)
581 static char *main_data_binary_subdir = NULL;
583 if (main_data_binary_subdir == NULL)
585 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
587 strlen(MAC_APP_BINARY_SUBDIR) + 1);
589 sprintf(main_data_binary_subdir, "%s.app/%s",
590 program.program_title, MAC_APP_BINARY_SUBDIR);
593 // cut relative path to Mac OS X application binary directory from path
594 if (strSuffix(main_data_path, main_data_binary_subdir))
595 main_data_path[strlen(main_data_path) -
596 strlen(main_data_binary_subdir)] = '\0';
598 // cut trailing path separator from path (but not if path is root directory)
599 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
600 main_data_path[strlen(main_data_path) - 1] = '\0';
603 return main_data_path;
607 /* ------------------------------------------------------------------------- */
608 /* various string functions */
609 /* ------------------------------------------------------------------------- */
611 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
613 if (s1 == NULL || s2 == NULL || sep == NULL)
616 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
619 sprintf(complete_string, "%s%s%s", s1, sep, s2);
621 return complete_string;
624 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
626 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
629 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
630 strlen(s2) + strlen(sep) +
633 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
635 return complete_string;
638 char *getStringCat2(char *s1, char *s2)
640 return getStringCat2WithSeparator(s1, s2, "");
643 char *getStringCat3(char *s1, char *s2, char *s3)
645 return getStringCat3WithSeparator(s1, s2, s3, "");
648 char *getPath2(char *path1, char *path2)
650 #if defined(PLATFORM_ANDROID)
651 // workaround for reading from APK assets directory -- skip leading "./"
652 if (strEqual(path1, "."))
653 return getStringCopy(path2);
656 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
659 char *getPath3(char *path1, char *path2, char *path3)
661 #if defined(PLATFORM_ANDROID)
662 // workaround for reading from APK assets directory -- skip leading "./"
663 if (strEqual(path1, "."))
664 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
667 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
670 char *getImg2(char *path1, char *path2)
672 char *filename = getPath2(path1, path2);
674 if (!fileExists(filename) && strSuffix(path2, ".png"))
676 // backward compatibility: if PNG file not found, check for PCX file
677 char *path2pcx = getStringCopy(path2);
679 strcpy(&path2pcx[strlen(path2pcx) - 3], "pcx");
683 filename = getPath2(path1, path2pcx);
691 char *getImg3(char *path1, char *path2, char *path3)
693 char *filename = getPath3(path1, path2, path3);
695 if (!fileExists(filename) && strSuffix(path3, ".png"))
697 // backward compatibility: if PNG file not found, check for PCX file
698 char *path3pcx = getStringCopy(path3);
700 strcpy(&path3pcx[strlen(path3pcx) - 3], "pcx");
704 filename = getPath3(path1, path2, path3pcx);
712 char *getStringCopy(const char *s)
719 s_copy = checked_malloc(strlen(s) + 1);
725 char *getStringCopyN(const char *s, int n)
728 int s_len = MAX(0, n);
733 s_copy = checked_malloc(s_len + 1);
734 strncpy(s_copy, s, s_len);
735 s_copy[s_len] = '\0';
740 char *getStringCopyNStatic(const char *s, int n)
742 static char *s_copy = NULL;
744 checked_free(s_copy);
746 s_copy = getStringCopyN(s, n);
751 char *getStringToLower(const char *s)
753 char *s_copy = checked_malloc(strlen(s) + 1);
754 char *s_ptr = s_copy;
757 *s_ptr++ = tolower(*s++);
763 void setString(char **old_value, char *new_value)
765 checked_free(*old_value);
767 *old_value = getStringCopy(new_value);
770 boolean strEqual(char *s1, char *s2)
772 return (s1 == NULL && s2 == NULL ? TRUE :
773 s1 == NULL && s2 != NULL ? FALSE :
774 s1 != NULL && s2 == NULL ? FALSE :
775 strcmp(s1, s2) == 0);
778 boolean strEqualN(char *s1, char *s2, int n)
780 return (s1 == NULL && s2 == NULL ? TRUE :
781 s1 == NULL && s2 != NULL ? FALSE :
782 s1 != NULL && s2 == NULL ? FALSE :
783 strncmp(s1, s2, n) == 0);
786 boolean strPrefix(char *s, char *prefix)
788 return (s == NULL && prefix == NULL ? TRUE :
789 s == NULL && prefix != NULL ? FALSE :
790 s != NULL && prefix == NULL ? FALSE :
791 strncmp(s, prefix, strlen(prefix)) == 0);
794 boolean strSuffix(char *s, char *suffix)
796 return (s == NULL && suffix == NULL ? TRUE :
797 s == NULL && suffix != NULL ? FALSE :
798 s != NULL && suffix == NULL ? FALSE :
799 strlen(s) < strlen(suffix) ? FALSE :
800 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
803 boolean strPrefixLower(char *s, char *prefix)
805 char *s_lower = getStringToLower(s);
806 boolean match = strPrefix(s_lower, prefix);
813 boolean strSuffixLower(char *s, char *suffix)
815 char *s_lower = getStringToLower(s);
816 boolean match = strSuffix(s_lower, suffix);
824 /* ------------------------------------------------------------------------- */
825 /* command line option handling functions */
826 /* ------------------------------------------------------------------------- */
828 void GetOptions(char *argv[],
829 void (*print_usage_function)(void),
830 void (*print_version_function)(void))
832 char *ro_base_path = RO_BASE_PATH;
833 char *rw_base_path = RW_BASE_PATH;
834 char **options_left = &argv[1];
836 /* if the program is configured to start from current directory (default),
837 determine program package directory from program binary (some versions
838 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
839 set the current working directory to the program package directory) */
841 if (strEqual(ro_base_path, "."))
842 ro_base_path = getProgramMainDataPath();
843 if (strEqual(rw_base_path, "."))
844 rw_base_path = getProgramMainDataPath();
846 /* initialize global program options */
847 options.display_name = NULL;
848 options.server_host = NULL;
849 options.server_port = 0;
851 options.ro_base_directory = ro_base_path;
852 options.rw_base_directory = rw_base_path;
853 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
854 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
855 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
856 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
857 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
859 options.execute_command = NULL;
860 options.special_flags = NULL;
862 options.serveronly = FALSE;
863 options.network = FALSE;
864 options.verbose = FALSE;
865 options.debug = FALSE;
868 options.verbose = TRUE;
870 #if !defined(PLATFORM_UNIX)
871 if (*options_left == NULL) /* no options given -- enable verbose mode */
872 options.verbose = TRUE;
876 while (*options_left)
878 char option_str[MAX_OPTION_LEN];
879 char *option = options_left[0];
880 char *next_option = options_left[1];
881 char *option_arg = NULL;
882 int option_len = strlen(option);
884 if (option_len >= MAX_OPTION_LEN)
885 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
887 strcpy(option_str, option); /* copy argument into buffer */
890 if (strEqual(option, "--")) /* stop scanning arguments */
893 if (strPrefix(option, "--")) /* treat '--' like '-' */
896 option_arg = strchr(option, '=');
897 if (option_arg == NULL) /* no '=' in option */
898 option_arg = next_option;
901 *option_arg++ = '\0'; /* cut argument from option */
902 if (*option_arg == '\0') /* no argument after '=' */
903 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
906 option_len = strlen(option);
908 if (strEqual(option, "-"))
910 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
912 else if (strncmp(option, "-help", option_len) == 0)
914 print_usage_function();
918 else if (strncmp(option, "-display", option_len) == 0)
920 if (option_arg == NULL)
921 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
923 options.display_name = option_arg;
924 if (option_arg == next_option)
927 else if (strncmp(option, "-basepath", option_len) == 0)
929 if (option_arg == NULL)
930 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
932 /* this should be extended to separate options for ro and rw data */
933 options.ro_base_directory = ro_base_path = option_arg;
934 options.rw_base_directory = rw_base_path = option_arg;
935 if (option_arg == next_option)
938 /* adjust paths for sub-directories in base directory accordingly */
939 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
940 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
941 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
942 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
943 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
945 else if (strncmp(option, "-levels", option_len) == 0)
947 if (option_arg == NULL)
948 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
950 options.level_directory = option_arg;
951 if (option_arg == next_option)
954 else if (strncmp(option, "-graphics", option_len) == 0)
956 if (option_arg == NULL)
957 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
959 options.graphics_directory = option_arg;
960 if (option_arg == next_option)
963 else if (strncmp(option, "-sounds", option_len) == 0)
965 if (option_arg == NULL)
966 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
968 options.sounds_directory = option_arg;
969 if (option_arg == next_option)
972 else if (strncmp(option, "-music", option_len) == 0)
974 if (option_arg == NULL)
975 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
977 options.music_directory = option_arg;
978 if (option_arg == next_option)
981 else if (strncmp(option, "-network", option_len) == 0)
983 options.network = TRUE;
985 else if (strncmp(option, "-serveronly", option_len) == 0)
987 options.serveronly = TRUE;
989 else if (strncmp(option, "-debug", option_len) == 0)
991 options.debug = TRUE;
993 else if (strncmp(option, "-verbose", option_len) == 0)
995 options.verbose = TRUE;
997 else if (strncmp(option, "-version", option_len) == 0 ||
998 strncmp(option, "-V", option_len) == 0)
1000 print_version_function();
1004 else if (strPrefix(option, "-D"))
1006 options.special_flags = getStringCopy(&option[2]);
1008 else if (strncmp(option, "-execute", option_len) == 0)
1010 if (option_arg == NULL)
1011 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1013 options.execute_command = option_arg;
1014 if (option_arg == next_option)
1017 /* when doing batch processing, always enable verbose mode (warnings) */
1018 options.verbose = TRUE;
1020 else if (*option == '-')
1022 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1024 else if (options.server_host == NULL)
1026 options.server_host = *options_left;
1028 else if (options.server_port == 0)
1030 options.server_port = atoi(*options_left);
1031 if (options.server_port < 1024)
1032 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1035 Error(ERR_EXIT_HELP, "too many arguments");
1042 /* ------------------------------------------------------------------------- */
1043 /* error handling functions */
1044 /* ------------------------------------------------------------------------- */
1046 #define MAX_INTERNAL_ERROR_SIZE 1024
1048 /* used by SetError() and GetError() to store internal error messages */
1049 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1051 void SetError(char *format, ...)
1055 va_start(ap, format);
1056 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1062 return internal_error;
1065 void Error(int mode, char *format, ...)
1067 static boolean last_line_was_separator = FALSE;
1068 char *process_name = "";
1070 #if defined(PLATFORM_ANDROID)
1071 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1072 mode & ERR_INFO ? ANDROID_LOG_INFO :
1073 mode & ERR_WARN ? ANDROID_LOG_WARN :
1074 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1075 ANDROID_LOG_UNKNOWN);
1078 /* display warnings only when running in verbose mode */
1079 if (mode & ERR_WARN && !options.verbose)
1082 if (mode == ERR_INFO_LINE)
1084 if (!last_line_was_separator)
1085 printf_log_line(format, 79);
1087 last_line_was_separator = TRUE;
1092 last_line_was_separator = FALSE;
1094 if (mode & ERR_SOUND_SERVER)
1095 process_name = " sound server";
1096 else if (mode & ERR_NETWORK_SERVER)
1097 process_name = " network server";
1098 else if (mode & ERR_NETWORK_CLIENT)
1099 process_name = " network client **";
1103 #if !defined(PLATFORM_ANDROID)
1104 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1107 if (mode & ERR_WARN)
1108 printf_log_nonewline("warning: ");
1110 if (mode & ERR_EXIT)
1111 printf_log_nonewline("fatal error: ");
1115 va_start(ap, format);
1116 vprintf_log(format, ap);
1119 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1121 va_start(ap, format);
1122 program.exit_message_function(format, ap);
1127 if (mode & ERR_HELP)
1128 printf_log("%s: Try option '--help' for more information.",
1129 program.command_basename);
1131 if (mode & ERR_EXIT)
1132 printf_log("%s%s: aborting", program.command_basename, process_name);
1134 if (mode & ERR_EXIT)
1136 if (mode & ERR_FROM_SERVER)
1137 exit(1); /* child process: normal exit */
1139 program.exit_function(1); /* main process: clean up stuff */
1144 /* ------------------------------------------------------------------------- */
1145 /* checked memory allocation and freeing functions */
1146 /* ------------------------------------------------------------------------- */
1148 void *checked_malloc(unsigned int size)
1155 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1160 void *checked_calloc(unsigned int size)
1164 ptr = calloc(1, size);
1167 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1172 void *checked_realloc(void *ptr, unsigned int size)
1174 ptr = realloc(ptr, size);
1177 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1182 void checked_free(void *ptr)
1184 if (ptr != NULL) /* this check should be done by free() anyway */
1188 void clear_mem(void *ptr, unsigned int size)
1190 #if defined(PLATFORM_WIN32)
1191 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1192 char *cptr = (char *)ptr;
1197 memset(ptr, 0, size);
1202 /* ------------------------------------------------------------------------- */
1203 /* various helper functions */
1204 /* ------------------------------------------------------------------------- */
1206 inline void swap_numbers(int *i1, int *i2)
1214 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1226 /* the "put" variants of the following file access functions check for the file
1227 pointer being != NULL and return the number of bytes they have or would have
1228 written; this allows for chunk writing functions to first determine the size
1229 of the (not yet written) chunk, write the correct chunk size and finally
1230 write the chunk itself */
1232 int getFile8BitInteger(File *file)
1234 return getByteFromFile(file);
1237 int putFile8BitInteger(FILE *file, int value)
1245 int getFile16BitInteger(File *file, int byte_order)
1247 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1248 return ((getByteFromFile(file) << 8) |
1249 (getByteFromFile(file) << 0));
1250 else /* BYTE_ORDER_LITTLE_ENDIAN */
1251 return ((getByteFromFile(file) << 0) |
1252 (getByteFromFile(file) << 8));
1255 int putFile16BitInteger(FILE *file, int value, int byte_order)
1259 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1261 fputc((value >> 8) & 0xff, file);
1262 fputc((value >> 0) & 0xff, file);
1264 else /* BYTE_ORDER_LITTLE_ENDIAN */
1266 fputc((value >> 0) & 0xff, file);
1267 fputc((value >> 8) & 0xff, file);
1274 int getFile32BitInteger(File *file, int byte_order)
1276 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1277 return ((getByteFromFile(file) << 24) |
1278 (getByteFromFile(file) << 16) |
1279 (getByteFromFile(file) << 8) |
1280 (getByteFromFile(file) << 0));
1281 else /* BYTE_ORDER_LITTLE_ENDIAN */
1282 return ((getByteFromFile(file) << 0) |
1283 (getByteFromFile(file) << 8) |
1284 (getByteFromFile(file) << 16) |
1285 (getByteFromFile(file) << 24));
1288 int putFile32BitInteger(FILE *file, int value, int byte_order)
1292 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1294 fputc((value >> 24) & 0xff, file);
1295 fputc((value >> 16) & 0xff, file);
1296 fputc((value >> 8) & 0xff, file);
1297 fputc((value >> 0) & 0xff, file);
1299 else /* BYTE_ORDER_LITTLE_ENDIAN */
1301 fputc((value >> 0) & 0xff, file);
1302 fputc((value >> 8) & 0xff, file);
1303 fputc((value >> 16) & 0xff, file);
1304 fputc((value >> 24) & 0xff, file);
1311 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1314 const int chunk_name_length = 4;
1316 /* read chunk name */
1317 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1320 if (chunk_size != NULL)
1322 /* read chunk size */
1323 *chunk_size = getFile32BitInteger(file, byte_order);
1326 return (checkEndOfFile(file) ? FALSE : TRUE);
1329 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1334 /* write chunk name */
1336 fputs(chunk_name, file);
1338 num_bytes += strlen(chunk_name);
1340 if (chunk_size >= 0)
1342 /* write chunk size */
1344 putFile32BitInteger(file, chunk_size, byte_order);
1352 int getFileVersion(File *file)
1354 int version_major = getByteFromFile(file);
1355 int version_minor = getByteFromFile(file);
1356 int version_patch = getByteFromFile(file);
1357 int version_build = getByteFromFile(file);
1359 return VERSION_IDENT(version_major, version_minor, version_patch,
1363 int putFileVersion(FILE *file, int version)
1367 int version_major = VERSION_MAJOR(version);
1368 int version_minor = VERSION_MINOR(version);
1369 int version_patch = VERSION_PATCH(version);
1370 int version_build = VERSION_BUILD(version);
1372 fputc(version_major, file);
1373 fputc(version_minor, file);
1374 fputc(version_patch, file);
1375 fputc(version_build, file);
1381 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1385 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1386 buffer[i] = getByteFromFile(file);
1389 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1393 for(i = 0; i < bytes; i++)
1394 fputc(buffer[i], file);
1397 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1399 while (bytes-- && !checkEndOfFile(file))
1400 getByteFromFile(file);
1403 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1410 /* ------------------------------------------------------------------------- */
1411 /* functions to translate key identifiers between different format */
1412 /* ------------------------------------------------------------------------- */
1414 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1415 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1416 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1417 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1419 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1428 /* normal cursor keys */
1429 { KSYM_Left, "XK_Left", "cursor left" },
1430 { KSYM_Right, "XK_Right", "cursor right" },
1431 { KSYM_Up, "XK_Up", "cursor up" },
1432 { KSYM_Down, "XK_Down", "cursor down" },
1434 /* keypad cursor keys */
1436 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1437 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1438 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1439 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1442 /* other keypad keys */
1443 #ifdef KSYM_KP_Enter
1444 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1445 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1446 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1447 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1448 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1449 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1453 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1454 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1455 { KSYM_Control_L, "XK_Control_L", "left control" },
1456 { KSYM_Control_R, "XK_Control_R", "right control" },
1457 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1458 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1459 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1460 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1461 #if !defined(TARGET_SDL2)
1462 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1463 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1465 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1466 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1468 /* some special keys */
1469 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1470 { KSYM_Delete, "XK_Delete", "delete" },
1471 { KSYM_Insert, "XK_Insert", "insert" },
1472 { KSYM_Tab, "XK_Tab", "tab" },
1473 { KSYM_Home, "XK_Home", "home" },
1474 { KSYM_End, "XK_End", "end" },
1475 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1476 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1478 #if defined(TARGET_SDL2)
1479 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1480 { KSYM_Back, "XK_Back", "back" }, /* back key */
1483 /* ASCII 0x20 to 0x40 keys (except numbers) */
1484 { KSYM_space, "XK_space", "space" },
1485 { KSYM_exclam, "XK_exclam", "!" },
1486 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1487 { KSYM_numbersign, "XK_numbersign", "#" },
1488 { KSYM_dollar, "XK_dollar", "$" },
1489 { KSYM_percent, "XK_percent", "%" },
1490 { KSYM_ampersand, "XK_ampersand", "&" },
1491 { KSYM_apostrophe, "XK_apostrophe", "'" },
1492 { KSYM_parenleft, "XK_parenleft", "(" },
1493 { KSYM_parenright, "XK_parenright", ")" },
1494 { KSYM_asterisk, "XK_asterisk", "*" },
1495 { KSYM_plus, "XK_plus", "+" },
1496 { KSYM_comma, "XK_comma", "," },
1497 { KSYM_minus, "XK_minus", "-" },
1498 { KSYM_period, "XK_period", "." },
1499 { KSYM_slash, "XK_slash", "/" },
1500 { KSYM_colon, "XK_colon", ":" },
1501 { KSYM_semicolon, "XK_semicolon", ";" },
1502 { KSYM_less, "XK_less", "<" },
1503 { KSYM_equal, "XK_equal", "=" },
1504 { KSYM_greater, "XK_greater", ">" },
1505 { KSYM_question, "XK_question", "?" },
1506 { KSYM_at, "XK_at", "@" },
1508 /* more ASCII keys */
1509 { KSYM_bracketleft, "XK_bracketleft", "[" },
1510 { KSYM_backslash, "XK_backslash", "\\" },
1511 { KSYM_bracketright,"XK_bracketright", "]" },
1512 { KSYM_asciicircum, "XK_asciicircum", "^" },
1513 { KSYM_underscore, "XK_underscore", "_" },
1514 { KSYM_grave, "XK_grave", "grave" },
1515 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1516 { KSYM_braceleft, "XK_braceleft", "brace left" },
1517 { KSYM_bar, "XK_bar", "bar" },
1518 { KSYM_braceright, "XK_braceright", "brace right" },
1519 { KSYM_asciitilde, "XK_asciitilde", "~" },
1521 /* special (non-ASCII) keys */
1522 { KSYM_degree, "XK_degree", "degree" },
1523 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1524 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1525 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1526 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1527 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1528 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1529 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1531 #if defined(TARGET_SDL2)
1532 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1533 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1534 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1535 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1536 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1537 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1538 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1539 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1540 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1542 /* other keys (for reverse mapping only) */
1543 { KSYM_space, "XK_space", " " },
1546 #if defined(TARGET_SDL2)
1547 /* keypad keys are not in numerical order in SDL2 */
1548 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1549 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1550 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1551 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1552 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1553 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1554 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1555 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1556 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1557 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1560 /* end-of-array identifier */
1566 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1568 static char name_buffer[30];
1571 if (key >= KSYM_A && key <= KSYM_Z)
1572 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1573 else if (key >= KSYM_a && key <= KSYM_z)
1574 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1575 else if (key >= KSYM_0 && key <= KSYM_9)
1576 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1577 #if !defined(TARGET_SDL2)
1578 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1579 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1581 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1582 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1583 else if (key == KSYM_UNDEFINED)
1584 strcpy(name_buffer, "(undefined)");
1591 if (key == translate_key[i].key)
1593 strcpy(name_buffer, translate_key[i].name);
1597 while (translate_key[++i].name);
1599 if (!translate_key[i].name)
1600 strcpy(name_buffer, "(unknown)");
1603 *name = name_buffer;
1605 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1607 static char name_buffer[30];
1610 if (key >= KSYM_A && key <= KSYM_Z)
1611 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1612 else if (key >= KSYM_a && key <= KSYM_z)
1613 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1614 else if (key >= KSYM_0 && key <= KSYM_9)
1615 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1616 #if !defined(TARGET_SDL2)
1617 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1618 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1620 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1621 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1622 else if (key == KSYM_UNDEFINED)
1623 strcpy(name_buffer, "[undefined]");
1630 if (key == translate_key[i].key)
1632 strcpy(name_buffer, translate_key[i].x11name);
1636 while (translate_key[++i].x11name);
1638 if (!translate_key[i].x11name)
1639 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1642 *x11name = name_buffer;
1644 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1646 Key key = KSYM_UNDEFINED;
1647 char *name_ptr = *name;
1649 if (strlen(*name) == 1)
1651 char c = name_ptr[0];
1653 if (c >= 'A' && c <= 'Z')
1654 key = KSYM_A + (Key)(c - 'A');
1655 else if (c >= 'a' && c <= 'z')
1656 key = KSYM_a + (Key)(c - 'a');
1657 else if (c >= '0' && c <= '9')
1658 key = KSYM_0 + (Key)(c - '0');
1661 if (key == KSYM_UNDEFINED)
1667 if (strEqual(translate_key[i].name, *name))
1669 key = translate_key[i].key;
1673 while (translate_key[++i].x11name);
1676 if (key == KSYM_UNDEFINED)
1677 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1681 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1683 Key key = KSYM_UNDEFINED;
1684 char *name_ptr = *x11name;
1686 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1688 char c = name_ptr[3];
1690 if (c >= 'A' && c <= 'Z')
1691 key = KSYM_A + (Key)(c - 'A');
1692 else if (c >= 'a' && c <= 'z')
1693 key = KSYM_a + (Key)(c - 'a');
1694 else if (c >= '0' && c <= '9')
1695 key = KSYM_0 + (Key)(c - '0');
1697 #if !defined(TARGET_SDL2)
1698 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1700 char c = name_ptr[6];
1702 if (c >= '0' && c <= '9')
1703 key = KSYM_KP_0 + (Key)(c - '0');
1706 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1708 char c1 = name_ptr[4];
1709 char c2 = name_ptr[5];
1712 if ((c1 >= '0' && c1 <= '9') &&
1713 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1714 d = atoi(&name_ptr[4]);
1716 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1717 key = KSYM_F1 + (Key)(d - 1);
1719 else if (strPrefix(name_ptr, "XK_"))
1725 if (strEqual(name_ptr, translate_key[i].x11name))
1727 key = translate_key[i].key;
1731 while (translate_key[++i].x11name);
1733 else if (strPrefix(name_ptr, "0x"))
1735 unsigned int value = 0;
1741 char c = *name_ptr++;
1744 if (c >= '0' && c <= '9')
1746 else if (c >= 'a' && c <= 'f')
1747 d = (int)(c - 'a' + 10);
1748 else if (c >= 'A' && c <= 'F')
1749 d = (int)(c - 'A' + 10);
1757 value = value * 16 + d;
1768 char *getKeyNameFromKey(Key key)
1772 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1776 char *getX11KeyNameFromKey(Key key)
1780 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1784 Key getKeyFromKeyName(char *name)
1788 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1792 Key getKeyFromX11KeyName(char *x11name)
1796 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1800 char getCharFromKey(Key key)
1806 } translate_key_char[] =
1808 /* special (non-ASCII) keys (ISO-8859-1) */
1809 { KSYM_degree, CHAR_BYTE_DEGREE },
1810 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1811 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1812 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1813 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1814 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1815 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1816 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1818 /* end-of-array identifier */
1822 char *keyname = getKeyNameFromKey(key);
1825 if (strlen(keyname) == 1)
1827 else if (strEqual(keyname, "space"))
1835 if (key == translate_key_char[i].key)
1837 c = translate_key_char[i].key_char;
1842 while (translate_key_char[++i].key_char);
1848 char getValidConfigValueChar(char c)
1850 if (c == '#' || /* used to mark comments */
1851 c == '\\') /* used to mark continued lines */
1858 /* ------------------------------------------------------------------------- */
1859 /* functions to translate string identifiers to integer or boolean value */
1860 /* ------------------------------------------------------------------------- */
1862 int get_integer_from_string(char *s)
1864 static char *number_text[][3] =
1866 { "0", "zero", "null", },
1867 { "1", "one", "first" },
1868 { "2", "two", "second" },
1869 { "3", "three", "third" },
1870 { "4", "four", "fourth" },
1871 { "5", "five", "fifth" },
1872 { "6", "six", "sixth" },
1873 { "7", "seven", "seventh" },
1874 { "8", "eight", "eighth" },
1875 { "9", "nine", "ninth" },
1876 { "10", "ten", "tenth" },
1877 { "11", "eleven", "eleventh" },
1878 { "12", "twelve", "twelfth" },
1880 { NULL, NULL, NULL },
1884 char *s_lower = getStringToLower(s);
1887 for (i = 0; number_text[i][0] != NULL; i++)
1888 for (j = 0; j < 3; j++)
1889 if (strEqual(s_lower, number_text[i][j]))
1894 if (strEqual(s_lower, "false") ||
1895 strEqual(s_lower, "no") ||
1896 strEqual(s_lower, "off"))
1898 else if (strEqual(s_lower, "true") ||
1899 strEqual(s_lower, "yes") ||
1900 strEqual(s_lower, "on"))
1911 boolean get_boolean_from_string(char *s)
1913 char *s_lower = getStringToLower(s);
1914 boolean result = FALSE;
1916 if (strEqual(s_lower, "true") ||
1917 strEqual(s_lower, "yes") ||
1918 strEqual(s_lower, "on") ||
1919 get_integer_from_string(s) == 1)
1927 int get_switch3_from_string(char *s)
1929 char *s_lower = getStringToLower(s);
1932 if (strEqual(s_lower, "true") ||
1933 strEqual(s_lower, "yes") ||
1934 strEqual(s_lower, "on") ||
1935 get_integer_from_string(s) == 1)
1937 else if (strEqual(s_lower, "auto"))
1946 /* ------------------------------------------------------------------------- */
1947 /* functions for generic lists */
1948 /* ------------------------------------------------------------------------- */
1950 ListNode *newListNode()
1952 return checked_calloc(sizeof(ListNode));
1955 void addNodeToList(ListNode **node_first, char *key, void *content)
1957 ListNode *node_new = newListNode();
1959 node_new->key = getStringCopy(key);
1960 node_new->content = content;
1961 node_new->next = *node_first;
1962 *node_first = node_new;
1965 void deleteNodeFromList(ListNode **node_first, char *key,
1966 void (*destructor_function)(void *))
1968 if (node_first == NULL || *node_first == NULL)
1971 if (strEqual((*node_first)->key, key))
1973 checked_free((*node_first)->key);
1974 if (destructor_function)
1975 destructor_function((*node_first)->content);
1976 *node_first = (*node_first)->next;
1979 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1982 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1984 if (node_first == NULL)
1987 if (strEqual(node_first->key, key))
1990 return getNodeFromKey(node_first->next, key);
1993 int getNumNodes(ListNode *node_first)
1995 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1998 void dumpList(ListNode *node_first)
2000 ListNode *node = node_first;
2004 printf("['%s' (%d)]\n", node->key,
2005 ((struct ListNodeInfo *)node->content)->num_references);
2009 printf("[%d nodes]\n", getNumNodes(node_first));
2013 /* ------------------------------------------------------------------------- */
2014 /* functions for file handling */
2015 /* ------------------------------------------------------------------------- */
2017 File *openFile(char *filename, char *mode)
2019 File *file = checked_calloc(sizeof(File));
2021 file->file = fopen(filename, mode);
2023 if (file->file != NULL)
2025 file->filename = getStringCopy(filename);
2030 #if defined(PLATFORM_ANDROID)
2031 file->asset_file = SDL_RWFromFile(filename, mode);
2033 if (file->asset_file != NULL)
2035 file->file_is_asset = TRUE;
2036 file->filename = getStringCopy(filename);
2047 int closeFile(File *file)
2054 #if defined(PLATFORM_ANDROID)
2055 if (file->asset_file)
2056 result = SDL_RWclose(file->asset_file);
2060 result = fclose(file->file);
2062 checked_free(file->filename);
2068 int checkEndOfFile(File *file)
2070 #if defined(PLATFORM_ANDROID)
2071 if (file->file_is_asset)
2072 return file->end_of_file;
2075 return feof(file->file);
2078 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2080 #if defined(PLATFORM_ANDROID)
2081 if (file->file_is_asset)
2083 if (file->end_of_file)
2086 size_t num_items_read =
2087 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2089 if (num_items_read < num_items)
2090 file->end_of_file = TRUE;
2092 return num_items_read;
2096 return fread(buffer, item_size, num_items, file->file);
2099 int seekFile(File *file, long offset, int whence)
2101 #if defined(PLATFORM_ANDROID)
2102 if (file->file_is_asset)
2104 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2105 whence == SEEK_CUR ? RW_SEEK_CUR :
2106 whence == SEEK_END ? RW_SEEK_END : 0);
2108 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2112 return fseek(file->file, offset, whence);
2115 int getByteFromFile(File *file)
2117 #if defined(PLATFORM_ANDROID)
2118 if (file->file_is_asset)
2120 if (file->end_of_file)
2124 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2126 if (num_bytes_read < 1)
2127 file->end_of_file = TRUE;
2129 return (file->end_of_file ? EOF : (int)c);
2133 return fgetc(file->file);
2136 char *getStringFromFile(File *file, char *line, int size)
2138 #if defined(PLATFORM_ANDROID)
2139 if (file->file_is_asset)
2141 if (file->end_of_file)
2144 char *line_ptr = line;
2145 int num_bytes_read = 0;
2147 while (num_bytes_read < size - 1 &&
2148 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2149 *line_ptr++ != '\n')
2154 if (strlen(line) == 0)
2156 file->end_of_file = TRUE;
2165 return fgets(line, size, file->file);
2169 /* ------------------------------------------------------------------------- */
2170 /* functions for directory handling */
2171 /* ------------------------------------------------------------------------- */
2173 Directory *openDirectory(char *dir_name)
2175 Directory *dir = checked_calloc(sizeof(Directory));
2177 dir->dir = opendir(dir_name);
2179 if (dir->dir != NULL)
2181 dir->filename = getStringCopy(dir_name);
2186 #if defined(PLATFORM_ANDROID)
2187 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2189 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2191 checked_free(asset_toc_filename);
2193 if (dir->asset_toc_file != NULL)
2195 dir->directory_is_asset = TRUE;
2196 dir->filename = getStringCopy(dir_name);
2207 int closeDirectory(Directory *dir)
2214 #if defined(PLATFORM_ANDROID)
2215 if (dir->asset_toc_file)
2216 result = SDL_RWclose(dir->asset_toc_file);
2220 result = closedir(dir->dir);
2223 freeDirectoryEntry(dir->dir_entry);
2225 checked_free(dir->filename);
2231 DirectoryEntry *readDirectory(Directory *dir)
2234 freeDirectoryEntry(dir->dir_entry);
2236 dir->dir_entry = NULL;
2238 #if defined(PLATFORM_ANDROID)
2239 if (dir->directory_is_asset)
2241 char line[MAX_LINE_LEN];
2242 char *line_ptr = line;
2243 int num_bytes_read = 0;
2245 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2246 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2255 if (strlen(line) == 0)
2258 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2260 dir->dir_entry->is_directory = FALSE;
2261 if (line[strlen(line) - 1] == '/')
2263 dir->dir_entry->is_directory = TRUE;
2265 line[strlen(line) - 1] = '\0';
2268 dir->dir_entry->basename = getStringCopy(line);
2269 dir->dir_entry->filename = getPath2(dir->filename, line);
2271 return dir->dir_entry;
2275 struct dirent *dir_entry = readdir(dir->dir);
2277 if (dir_entry == NULL)
2280 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2282 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2283 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2285 struct stat file_status;
2287 dir->dir_entry->is_directory =
2288 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2289 (file_status.st_mode & S_IFMT) == S_IFDIR);
2291 return dir->dir_entry;
2294 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2296 if (dir_entry == NULL)
2299 checked_free(dir_entry->basename);
2300 checked_free(dir_entry->filename);
2301 checked_free(dir_entry);
2305 /* ------------------------------------------------------------------------- */
2306 /* functions for checking files and filenames */
2307 /* ------------------------------------------------------------------------- */
2309 boolean directoryExists(char *dir_name)
2311 if (dir_name == NULL)
2314 struct stat file_status;
2315 boolean success = (stat(dir_name, &file_status) == 0 &&
2316 (file_status.st_mode & S_IFMT) == S_IFDIR);
2318 #if defined(PLATFORM_ANDROID)
2321 // this might be an asset directory; check by trying to open toc file
2322 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2323 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2325 checked_free(asset_toc_filename);
2327 success = (file != NULL);
2337 boolean fileExists(char *filename)
2339 if (filename == NULL)
2342 boolean success = (access(filename, F_OK) == 0);
2344 #if defined(PLATFORM_ANDROID)
2347 // this might be an asset file; check by trying to open it
2348 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2350 success = (file != NULL);
2360 boolean fileHasPrefix(char *basename, char *prefix)
2362 static char *basename_lower = NULL;
2363 int basename_length, prefix_length;
2365 checked_free(basename_lower);
2367 if (basename == NULL || prefix == NULL)
2370 basename_lower = getStringToLower(basename);
2371 basename_length = strlen(basename_lower);
2372 prefix_length = strlen(prefix);
2374 if (basename_length > prefix_length + 1 &&
2375 basename_lower[prefix_length] == '.' &&
2376 strncmp(basename_lower, prefix, prefix_length) == 0)
2382 boolean fileHasSuffix(char *basename, char *suffix)
2384 static char *basename_lower = NULL;
2385 int basename_length, suffix_length;
2387 checked_free(basename_lower);
2389 if (basename == NULL || suffix == NULL)
2392 basename_lower = getStringToLower(basename);
2393 basename_length = strlen(basename_lower);
2394 suffix_length = strlen(suffix);
2396 if (basename_length > suffix_length + 1 &&
2397 basename_lower[basename_length - suffix_length - 1] == '.' &&
2398 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2404 static boolean FileCouldBeArtwork(char *filename)
2406 char *basename = getBaseNamePtr(filename);
2408 return (!strEqual(basename, ".") &&
2409 !strEqual(basename, "..") &&
2410 !fileHasSuffix(basename, "txt") &&
2411 !fileHasSuffix(basename, "conf") &&
2412 !directoryExists(filename));
2415 boolean FileIsGraphic(char *filename)
2417 return FileCouldBeArtwork(filename);
2420 boolean FileIsSound(char *filename)
2422 return FileCouldBeArtwork(filename);
2425 boolean FileIsMusic(char *filename)
2427 return FileCouldBeArtwork(filename);
2430 boolean FileIsArtworkType(char *filename, int type)
2432 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2433 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2434 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2440 /* ------------------------------------------------------------------------- */
2441 /* functions for loading artwork configuration information */
2442 /* ------------------------------------------------------------------------- */
2444 char *get_mapped_token(char *token)
2446 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2447 static char *map_token_prefix[][2] =
2449 { "char_procent", "char_percent" },
2454 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2456 int len_token_prefix = strlen(map_token_prefix[i][0]);
2458 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2459 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2465 /* This function checks if a string <s> of the format "string1, string2, ..."
2466 exactly contains a string <s_contained>. */
2468 static boolean string_has_parameter(char *s, char *s_contained)
2472 if (s == NULL || s_contained == NULL)
2475 if (strlen(s_contained) > strlen(s))
2478 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2480 char next_char = s[strlen(s_contained)];
2482 /* check if next character is delimiter or whitespace */
2483 return (next_char == ',' || next_char == '\0' ||
2484 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2487 /* check if string contains another parameter string after a comma */
2488 substring = strchr(s, ',');
2489 if (substring == NULL) /* string does not contain a comma */
2492 /* advance string pointer to next character after the comma */
2495 /* skip potential whitespaces after the comma */
2496 while (*substring == ' ' || *substring == '\t')
2499 return string_has_parameter(substring, s_contained);
2502 int get_parameter_value(char *value_raw, char *suffix, int type)
2504 char *value = getStringToLower(value_raw);
2505 int result = 0; /* probably a save default value */
2507 if (strEqual(suffix, ".direction"))
2509 result = (strEqual(value, "left") ? MV_LEFT :
2510 strEqual(value, "right") ? MV_RIGHT :
2511 strEqual(value, "up") ? MV_UP :
2512 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2514 else if (strEqual(suffix, ".align"))
2516 result = (strEqual(value, "left") ? ALIGN_LEFT :
2517 strEqual(value, "right") ? ALIGN_RIGHT :
2518 strEqual(value, "center") ? ALIGN_CENTER :
2519 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2521 else if (strEqual(suffix, ".valign"))
2523 result = (strEqual(value, "top") ? VALIGN_TOP :
2524 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2525 strEqual(value, "middle") ? VALIGN_MIDDLE :
2526 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2528 else if (strEqual(suffix, ".anim_mode"))
2530 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2531 string_has_parameter(value, "loop") ? ANIM_LOOP :
2532 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2533 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2534 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2535 string_has_parameter(value, "random") ? ANIM_RANDOM :
2536 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2537 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2538 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2539 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2540 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2541 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2544 if (string_has_parameter(value, "reverse"))
2545 result |= ANIM_REVERSE;
2547 if (string_has_parameter(value, "opaque_player"))
2548 result |= ANIM_OPAQUE_PLAYER;
2550 if (string_has_parameter(value, "static_panel"))
2551 result |= ANIM_STATIC_PANEL;
2553 else if (strEqual(suffix, ".class"))
2555 result = get_hash_from_key(value);
2557 else if (strEqual(suffix, ".style"))
2559 result = STYLE_DEFAULT;
2561 if (string_has_parameter(value, "accurate_borders"))
2562 result |= STYLE_ACCURATE_BORDERS;
2564 if (string_has_parameter(value, "inner_corners"))
2565 result |= STYLE_INNER_CORNERS;
2567 else if (strEqual(suffix, ".fade_mode"))
2569 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2570 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2571 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2572 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2575 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2577 result = gfx.get_font_from_token_function(value);
2579 else /* generic parameter of type integer or boolean */
2581 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2582 type == TYPE_INTEGER ? get_integer_from_string(value) :
2583 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2584 ARG_UNDEFINED_VALUE);
2592 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2594 static struct ScreenModeInfo screen_mode;
2595 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2596 char *screen_mode_string_copy;
2597 char *screen_mode_string_pos_w;
2598 char *screen_mode_string_pos_h;
2600 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2603 screen_mode_string_copy = getStringCopy(screen_mode_string);
2605 screen_mode_string_pos_w = screen_mode_string_copy;
2606 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2607 *screen_mode_string_pos_h++ = '\0';
2609 screen_mode.width = atoi(screen_mode_string_pos_w);
2610 screen_mode.height = atoi(screen_mode_string_pos_h);
2612 return &screen_mode;
2615 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2618 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2619 float aspect_ratio_new;
2624 *x = i * aspect_ratio + 0.000001;
2627 aspect_ratio_new = (float)*x / (float)*y;
2631 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2634 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2635 struct ListNodeInfo ***, int *);
2637 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2638 struct ConfigTypeInfo *suffix_list,
2639 char **ignore_tokens,
2640 int num_file_list_entries)
2642 struct FileInfo *file_list;
2643 int num_file_list_entries_found = 0;
2644 int num_suffix_list_entries = 0;
2648 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2650 for (i = 0; suffix_list[i].token != NULL; i++)
2651 num_suffix_list_entries++;
2653 /* always start with reliable default values */
2654 for (i = 0; i < num_file_list_entries; i++)
2656 file_list[i].token = NULL;
2658 file_list[i].default_filename = NULL;
2659 file_list[i].filename = NULL;
2661 if (num_suffix_list_entries > 0)
2663 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2665 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2666 file_list[i].parameter = checked_calloc(parameter_array_size);
2668 for (j = 0; j < num_suffix_list_entries; j++)
2670 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2671 setString(&file_list[i].parameter[j], suffix_list[j].value);
2674 file_list[i].redefined = FALSE;
2675 file_list[i].fallback_to_default = FALSE;
2676 file_list[i].default_is_cloned = FALSE;
2682 for (i = 0; config_list[i].token != NULL; i++)
2684 int len_config_token = strlen(config_list[i].token);
2685 boolean is_file_entry = TRUE;
2687 for (j = 0; suffix_list[j].token != NULL; j++)
2689 int len_suffix = strlen(suffix_list[j].token);
2691 if (len_suffix < len_config_token &&
2692 strEqual(&config_list[i].token[len_config_token - len_suffix],
2693 suffix_list[j].token))
2695 setString(&file_list[list_pos].default_parameter[j],
2696 config_list[i].value);
2698 is_file_entry = FALSE;
2704 /* the following tokens are no file definitions, but other config tokens */
2705 for (j = 0; ignore_tokens[j] != NULL; j++)
2706 if (strEqual(config_list[i].token, ignore_tokens[j]))
2707 is_file_entry = FALSE;
2714 if (list_pos >= num_file_list_entries)
2717 file_list[list_pos].token = config_list[i].token;
2718 file_list[list_pos].default_filename = config_list[i].value;
2721 if (strSuffix(config_list[i].token, ".clone_from"))
2722 file_list[list_pos].default_is_cloned = TRUE;
2725 num_file_list_entries_found = list_pos + 1;
2726 if (num_file_list_entries_found != num_file_list_entries)
2728 Error(ERR_INFO_LINE, "-");
2729 Error(ERR_INFO, "inconsistant config list information:");
2730 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2731 num_file_list_entries);
2732 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2733 num_file_list_entries_found);
2734 Error(ERR_EXIT, "please fix");
2740 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2742 int len_token = strlen(token);
2743 int len_suffix = strlen(suffix);
2745 if (start_pos < 0) /* compare suffix from end of string */
2746 start_pos += len_token;
2748 if (start_pos < 0 || start_pos + len_suffix > len_token)
2751 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2754 if (token[start_pos + len_suffix] == '\0')
2757 if (token[start_pos + len_suffix] == '.')
2763 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2765 static void read_token_parameters(SetupFileHash *setup_file_hash,
2766 struct ConfigTypeInfo *suffix_list,
2767 struct FileInfo *file_list_entry)
2769 /* check for config token that is the base token without any suffixes */
2770 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2771 char *known_token_value = KNOWN_TOKEN_VALUE;
2774 if (filename != NULL)
2776 setString(&file_list_entry->filename, filename);
2778 /* when file definition found, set all parameters to default values */
2779 for (i = 0; suffix_list[i].token != NULL; i++)
2780 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2782 file_list_entry->redefined = TRUE;
2784 /* mark config file token as well known from default config */
2785 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2788 /* check for config tokens that can be build by base token and suffixes */
2789 for (i = 0; suffix_list[i].token != NULL; i++)
2791 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2792 char *value = getHashEntry(setup_file_hash, token);
2796 setString(&file_list_entry->parameter[i], value);
2798 /* mark config file token as well known from default config */
2799 setHashEntry(setup_file_hash, token, known_token_value);
2806 static void add_dynamic_file_list_entry(struct FileInfo **list,
2807 int *num_list_entries,
2808 SetupFileHash *extra_file_hash,
2809 struct ConfigTypeInfo *suffix_list,
2810 int num_suffix_list_entries,
2813 struct FileInfo *new_list_entry;
2814 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2816 (*num_list_entries)++;
2817 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2818 new_list_entry = &(*list)[*num_list_entries - 1];
2820 new_list_entry->token = getStringCopy(token);
2821 new_list_entry->default_filename = NULL;
2822 new_list_entry->filename = NULL;
2823 new_list_entry->parameter = checked_calloc(parameter_array_size);
2825 new_list_entry->redefined = FALSE;
2826 new_list_entry->fallback_to_default = FALSE;
2827 new_list_entry->default_is_cloned = FALSE;
2829 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2832 static void add_property_mapping(struct PropertyMapping **list,
2833 int *num_list_entries,
2834 int base_index, int ext1_index,
2835 int ext2_index, int ext3_index,
2838 struct PropertyMapping *new_list_entry;
2840 (*num_list_entries)++;
2841 *list = checked_realloc(*list,
2842 *num_list_entries * sizeof(struct PropertyMapping));
2843 new_list_entry = &(*list)[*num_list_entries - 1];
2845 new_list_entry->base_index = base_index;
2846 new_list_entry->ext1_index = ext1_index;
2847 new_list_entry->ext2_index = ext2_index;
2848 new_list_entry->ext3_index = ext3_index;
2850 new_list_entry->artwork_index = artwork_index;
2853 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2856 struct FileInfo *file_list = artwork_info->file_list;
2857 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2858 char **base_prefixes = artwork_info->base_prefixes;
2859 char **ext1_suffixes = artwork_info->ext1_suffixes;
2860 char **ext2_suffixes = artwork_info->ext2_suffixes;
2861 char **ext3_suffixes = artwork_info->ext3_suffixes;
2862 char **ignore_tokens = artwork_info->ignore_tokens;
2863 int num_file_list_entries = artwork_info->num_file_list_entries;
2864 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2865 int num_base_prefixes = artwork_info->num_base_prefixes;
2866 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2867 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2868 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2869 int num_ignore_tokens = artwork_info->num_ignore_tokens;
2870 SetupFileHash *setup_file_hash, *valid_file_hash;
2871 SetupFileHash *extra_file_hash, *empty_file_hash;
2872 char *known_token_value = KNOWN_TOKEN_VALUE;
2875 if (filename == NULL)
2878 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2881 /* separate valid (defined) from empty (undefined) config token values */
2882 valid_file_hash = newSetupFileHash();
2883 empty_file_hash = newSetupFileHash();
2884 BEGIN_HASH_ITERATION(setup_file_hash, itr)
2886 char *value = HASH_ITERATION_VALUE(itr);
2888 setHashEntry(*value ? valid_file_hash : empty_file_hash,
2889 HASH_ITERATION_TOKEN(itr), value);
2891 END_HASH_ITERATION(setup_file_hash, itr)
2893 /* at this point, we do not need the setup file hash anymore -- free it */
2894 freeSetupFileHash(setup_file_hash);
2896 /* map deprecated to current tokens (using prefix match and replace) */
2897 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2899 char *token = HASH_ITERATION_TOKEN(itr);
2900 char *mapped_token = get_mapped_token(token);
2902 if (mapped_token != NULL)
2904 char *value = HASH_ITERATION_VALUE(itr);
2906 /* add mapped token */
2907 setHashEntry(valid_file_hash, mapped_token, value);
2909 /* ignore old token (by setting it to "known" keyword) */
2910 setHashEntry(valid_file_hash, token, known_token_value);
2915 END_HASH_ITERATION(valid_file_hash, itr)
2917 /* read parameters for all known config file tokens */
2918 for (i = 0; i < num_file_list_entries; i++)
2919 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2921 /* set all tokens that can be ignored here to "known" keyword */
2922 for (i = 0; i < num_ignore_tokens; i++)
2923 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2925 /* copy all unknown config file tokens to extra config hash */
2926 extra_file_hash = newSetupFileHash();
2927 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2929 char *value = HASH_ITERATION_VALUE(itr);
2931 if (!strEqual(value, known_token_value))
2932 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2934 END_HASH_ITERATION(valid_file_hash, itr)
2936 /* at this point, we do not need the valid file hash anymore -- free it */
2937 freeSetupFileHash(valid_file_hash);
2939 /* now try to determine valid, dynamically defined config tokens */
2941 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2943 struct FileInfo **dynamic_file_list =
2944 &artwork_info->dynamic_file_list;
2945 int *num_dynamic_file_list_entries =
2946 &artwork_info->num_dynamic_file_list_entries;
2947 struct PropertyMapping **property_mapping =
2948 &artwork_info->property_mapping;
2949 int *num_property_mapping_entries =
2950 &artwork_info->num_property_mapping_entries;
2951 int current_summarized_file_list_entry =
2952 artwork_info->num_file_list_entries +
2953 artwork_info->num_dynamic_file_list_entries;
2954 char *token = HASH_ITERATION_TOKEN(itr);
2955 int len_token = strlen(token);
2957 boolean base_prefix_found = FALSE;
2958 boolean parameter_suffix_found = FALSE;
2960 /* skip all parameter definitions (handled by read_token_parameters()) */
2961 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2963 int len_suffix = strlen(suffix_list[i].token);
2965 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2966 parameter_suffix_found = TRUE;
2969 if (parameter_suffix_found)
2972 /* ---------- step 0: search for matching base prefix ---------- */
2975 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2977 char *base_prefix = base_prefixes[i];
2978 int len_base_prefix = strlen(base_prefix);
2979 boolean ext1_suffix_found = FALSE;
2980 boolean ext2_suffix_found = FALSE;
2981 boolean ext3_suffix_found = FALSE;
2982 boolean exact_match = FALSE;
2983 int base_index = -1;
2984 int ext1_index = -1;
2985 int ext2_index = -1;
2986 int ext3_index = -1;
2988 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2990 if (!base_prefix_found)
2995 if (start_pos + len_base_prefix == len_token) /* exact match */
2999 add_dynamic_file_list_entry(dynamic_file_list,
3000 num_dynamic_file_list_entries,
3003 num_suffix_list_entries,
3005 add_property_mapping(property_mapping,
3006 num_property_mapping_entries,
3007 base_index, -1, -1, -1,
3008 current_summarized_file_list_entry);
3012 /* ---------- step 1: search for matching first suffix ---------- */
3014 start_pos += len_base_prefix;
3015 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3017 char *ext1_suffix = ext1_suffixes[j];
3018 int len_ext1_suffix = strlen(ext1_suffix);
3020 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3022 if (!ext1_suffix_found)
3027 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3031 add_dynamic_file_list_entry(dynamic_file_list,
3032 num_dynamic_file_list_entries,
3035 num_suffix_list_entries,
3037 add_property_mapping(property_mapping,
3038 num_property_mapping_entries,
3039 base_index, ext1_index, -1, -1,
3040 current_summarized_file_list_entry);
3044 start_pos += len_ext1_suffix;
3050 /* ---------- step 2: search for matching second suffix ---------- */
3052 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3054 char *ext2_suffix = ext2_suffixes[k];
3055 int len_ext2_suffix = strlen(ext2_suffix);
3057 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3059 if (!ext2_suffix_found)
3064 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3068 add_dynamic_file_list_entry(dynamic_file_list,
3069 num_dynamic_file_list_entries,
3072 num_suffix_list_entries,
3074 add_property_mapping(property_mapping,
3075 num_property_mapping_entries,
3076 base_index, ext1_index, ext2_index, -1,
3077 current_summarized_file_list_entry);
3081 start_pos += len_ext2_suffix;
3087 /* ---------- step 3: search for matching third suffix ---------- */
3089 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3091 char *ext3_suffix = ext3_suffixes[l];
3092 int len_ext3_suffix = strlen(ext3_suffix);
3094 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3096 if (!ext3_suffix_found)
3101 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3105 add_dynamic_file_list_entry(dynamic_file_list,
3106 num_dynamic_file_list_entries,
3109 num_suffix_list_entries,
3111 add_property_mapping(property_mapping,
3112 num_property_mapping_entries,
3113 base_index, ext1_index, ext2_index, ext3_index,
3114 current_summarized_file_list_entry);
3120 END_HASH_ITERATION(extra_file_hash, itr)
3122 if (artwork_info->num_dynamic_file_list_entries > 0)
3124 artwork_info->dynamic_artwork_list =
3125 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3126 artwork_info->sizeof_artwork_list_entry);
3129 if (options.verbose && IS_PARENT_PROCESS())
3131 SetupFileList *setup_file_list, *list;
3132 boolean dynamic_tokens_found = FALSE;
3133 boolean unknown_tokens_found = FALSE;
3134 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3136 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3137 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3139 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3141 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3142 dynamic_tokens_found = TRUE;
3144 unknown_tokens_found = TRUE;
3146 END_HASH_ITERATION(extra_file_hash, itr)
3148 if (options.debug && dynamic_tokens_found)
3150 Error(ERR_INFO_LINE, "-");
3151 Error(ERR_INFO, "dynamic token(s) found in config file:");
3152 Error(ERR_INFO, "- config file: '%s'", filename);
3154 for (list = setup_file_list; list != NULL; list = list->next)
3156 char *value = getHashEntry(extra_file_hash, list->token);
3158 if (value != NULL && strEqual(value, known_token_value))
3159 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3162 Error(ERR_INFO_LINE, "-");
3165 if (unknown_tokens_found)
3167 Error(ERR_INFO_LINE, "-");
3168 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3169 Error(ERR_INFO, "- config file: '%s'", filename);
3171 for (list = setup_file_list; list != NULL; list = list->next)
3173 char *value = getHashEntry(extra_file_hash, list->token);
3175 if (value != NULL && !strEqual(value, known_token_value))
3176 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3179 Error(ERR_INFO_LINE, "-");
3182 if (undefined_values_found)
3184 Error(ERR_INFO_LINE, "-");
3185 Error(ERR_INFO, "warning: undefined values found in config file:");
3186 Error(ERR_INFO, "- config file: '%s'", filename);
3188 for (list = setup_file_list; list != NULL; list = list->next)
3190 char *value = getHashEntry(empty_file_hash, list->token);
3193 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3196 Error(ERR_INFO_LINE, "-");
3199 freeSetupFileList(setup_file_list);
3202 freeSetupFileHash(extra_file_hash);
3203 freeSetupFileHash(empty_file_hash);
3206 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3208 struct FileInfo *file_list = artwork_info->file_list;
3209 int num_file_list_entries = artwork_info->num_file_list_entries;
3210 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3211 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3214 DrawInitText("Loading artwork config", 120, FC_GREEN);
3215 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3217 /* always start with reliable default values */
3218 for (i = 0; i < num_file_list_entries; i++)
3220 setString(&file_list[i].filename, file_list[i].default_filename);
3222 for (j = 0; j < num_suffix_list_entries; j++)
3223 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3225 file_list[i].redefined = FALSE;
3226 file_list[i].fallback_to_default = FALSE;
3229 /* free previous dynamic artwork file array */
3230 if (artwork_info->dynamic_file_list != NULL)
3232 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3234 free(artwork_info->dynamic_file_list[i].token);
3235 free(artwork_info->dynamic_file_list[i].filename);
3236 free(artwork_info->dynamic_file_list[i].parameter);
3239 free(artwork_info->dynamic_file_list);
3240 artwork_info->dynamic_file_list = NULL;
3242 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3243 &artwork_info->num_dynamic_file_list_entries);
3246 /* free previous property mapping */
3247 if (artwork_info->property_mapping != NULL)
3249 free(artwork_info->property_mapping);
3251 artwork_info->property_mapping = NULL;
3252 artwork_info->num_property_mapping_entries = 0;
3255 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3257 /* first look for special artwork configured in level series config */
3258 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3260 if (fileExists(filename_base))
3261 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3264 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3266 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3267 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3270 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3271 struct ListNodeInfo **listnode)
3275 char *filename = (*listnode)->source_filename;
3277 if (--(*listnode)->num_references <= 0)
3278 deleteNodeFromList(&artwork_info->content_list, filename,
3279 artwork_info->free_artwork);
3285 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3286 struct ListNodeInfo **listnode,
3287 struct FileInfo *file_list_entry)
3297 char *basename = file_list_entry->filename;
3298 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3300 if (filename == NULL)
3302 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3304 basename = file_list_entry->default_filename;
3306 /* fail for cloned default artwork that has no default filename defined */
3307 if (file_list_entry->default_is_cloned &&
3308 strEqual(basename, UNDEFINED_FILENAME))
3310 int error_mode = ERR_WARN;
3312 /* we can get away without sounds and music, but not without graphics */
3313 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3314 error_mode = ERR_EXIT;
3316 Error(error_mode, "token '%s' was cloned and has no default filename",
3317 file_list_entry->token);
3322 /* dynamic artwork has no default filename / skip empty default artwork */
3323 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3326 file_list_entry->fallback_to_default = TRUE;
3328 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3330 filename = getCustomArtworkFilename(basename, artwork_info->type);
3332 if (filename == NULL)
3334 int error_mode = ERR_WARN;
3336 /* we can get away without sounds and music, but not without graphics */
3337 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3338 error_mode = ERR_EXIT;
3340 Error(error_mode, "cannot find default artwork file '%s'", basename);
3346 /* check if the old and the new artwork file are the same */
3347 if (*listnode && strEqual((*listnode)->source_filename, filename))
3349 /* The old and new artwork are the same (have the same filename and path).
3350 This usually means that this artwork does not exist in this artwork set
3351 and a fallback to the existing artwork is done. */
3356 /* delete existing artwork file entry */
3357 deleteArtworkListEntry(artwork_info, listnode);
3359 /* check if the new artwork file already exists in the list of artwork */
3360 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3362 *listnode = (struct ListNodeInfo *)node->content;
3363 (*listnode)->num_references++;
3368 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3369 DrawInitText(basename, 150, FC_YELLOW);
3371 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3373 /* add new artwork file entry to the list of artwork files */
3374 (*listnode)->num_references = 1;
3375 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3380 int error_mode = ERR_WARN;
3382 /* we can get away without sounds and music, but not without graphics */
3383 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3384 error_mode = ERR_EXIT;
3386 Error(error_mode, "cannot load artwork file '%s'", basename);
3392 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3393 struct ListNodeInfo **listnode,
3394 struct FileInfo *file_list_entry)
3396 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3398 deleteArtworkListEntry(artwork_info, listnode);
3403 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3406 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3408 struct FileInfo *file_list = artwork_info->file_list;
3409 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3410 int num_file_list_entries = artwork_info->num_file_list_entries;
3411 int num_dynamic_file_list_entries =
3412 artwork_info->num_dynamic_file_list_entries;
3415 print_timestamp_init("ReloadCustomArtworkList");
3417 for (i = 0; i < num_file_list_entries; i++)
3418 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3421 for (i = 0; i < num_dynamic_file_list_entries; i++)
3422 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3423 &dynamic_file_list[i]);
3425 print_timestamp_done("ReloadCustomArtworkList");
3428 dumpList(artwork_info->content_list);
3432 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3433 struct ListNodeInfo ***list,
3434 int *num_list_entries)
3441 for (i = 0; i < *num_list_entries; i++)
3442 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3446 *num_list_entries = 0;
3449 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3451 if (artwork_info == NULL)
3454 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3455 &artwork_info->num_file_list_entries);
3457 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3458 &artwork_info->num_dynamic_file_list_entries);
3462 /* ------------------------------------------------------------------------- */
3463 /* functions only needed for non-Unix (non-command-line) systems */
3464 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3465 /* (now also added for Windows, to create files in user data directory) */
3466 /* ------------------------------------------------------------------------- */
3468 char *getErrorFilename(char *basename)
3470 return getPath2(getUserGameDataDir(), basename);
3473 void openErrorFile()
3475 InitUserDataDirectory();
3477 if ((program.error_file = fopen(program.error_filename, MODE_WRITE)) == NULL)
3479 program.error_file = stderr;
3481 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3482 program.error_filename, strerror(errno));
3485 /* error output should be unbuffered so it is not truncated in a crash */
3486 setbuf(program.error_file, NULL);
3489 void closeErrorFile()
3491 if (program.error_file != stderr) /* do not close file 'stderr' */
3492 fclose(program.error_file);
3495 void dumpErrorFile()
3497 FILE *error_file = fopen(program.error_filename, MODE_READ);
3499 if (error_file != NULL)
3501 while (!feof(error_file))
3502 fputc(fgetc(error_file), stderr);
3508 void NotifyUserAboutErrorFile()
3510 #if defined(PLATFORM_WIN32)
3511 char *title_text = getStringCat2(program.program_title, " Error Message");
3512 char *error_text = getStringCat2("The program was aborted due to an error; "
3513 "for details, see the following error file:"
3514 STRING_NEWLINE, program.error_filename);
3516 MessageBox(NULL, error_text, title_text, MB_OK);
3521 /* ------------------------------------------------------------------------- */
3522 /* the following is only for debugging purpose and normally not used */
3523 /* ------------------------------------------------------------------------- */
3527 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3528 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3530 #define DEBUG_NUM_TIMESTAMPS 10
3531 #define DEBUG_TIME_IN_MICROSECONDS 0
3533 #if DEBUG_TIME_IN_MICROSECONDS
3534 static double Counter_Microseconds()
3536 static struct timeval base_time = { 0, 0 };
3537 struct timeval current_time;
3540 gettimeofday(¤t_time, NULL);
3542 /* reset base time in case of wrap-around */
3543 if (current_time.tv_sec < base_time.tv_sec)
3544 base_time = current_time;
3547 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3548 ((double)(current_time.tv_usec - base_time.tv_usec));
3550 return counter; /* return microseconds since last init */
3554 char *debug_print_timestamp_get_padding(int padding_size)
3556 static char *padding = NULL;
3557 int max_padding_size = 100;
3559 if (padding == NULL)
3561 padding = checked_calloc(max_padding_size + 1);
3562 memset(padding, ' ', max_padding_size);
3565 return &padding[MAX(0, max_padding_size - padding_size)];
3568 void debug_print_timestamp(int counter_nr, char *message)
3570 int indent_size = 8;
3571 int padding_size = 40;
3572 float timestamp_interval;
3575 Error(ERR_EXIT, "debugging: invalid negative counter");
3576 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3577 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3579 #if DEBUG_TIME_IN_MICROSECONDS
3580 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3583 counter[counter_nr][0] = Counter_Microseconds();
3585 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3588 counter[counter_nr][0] = Counter();
3591 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3592 counter[counter_nr][1] = counter[counter_nr][0];
3595 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3596 debug_print_timestamp_get_padding(counter_nr * indent_size),
3598 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3599 timestamp_interval / 1000,
3603 void debug_print_parent_only(char *format, ...)
3605 if (!IS_PARENT_PROCESS())
3612 va_start(ap, format);
3613 vprintf(format, ap);
3622 void print_timestamp_ext(char *message, char *mode)
3624 #if DEBUG_PRINT_INIT_TIMESTAMPS
3625 static char *debug_message = NULL;
3626 static char *last_message = NULL;
3627 static int counter_nr = 0;
3628 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3630 checked_free(debug_message);
3631 debug_message = getStringCat3(mode, " ", message);
3633 if (strEqual(mode, "INIT"))
3635 debug_print_timestamp(counter_nr, NULL);
3637 if (counter_nr + 1 < max_depth)
3638 debug_print_timestamp(counter_nr, debug_message);
3642 debug_print_timestamp(counter_nr, NULL);
3644 else if (strEqual(mode, "DONE"))
3648 if (counter_nr + 1 < max_depth ||
3649 (counter_nr == 0 && max_depth == 1))
3651 last_message = message;
3653 if (counter_nr == 0 && max_depth == 1)
3655 checked_free(debug_message);
3656 debug_message = getStringCat3("TIME", " ", message);
3659 debug_print_timestamp(counter_nr, debug_message);
3662 else if (!strEqual(mode, "TIME") ||
3663 !strEqual(message, last_message))
3665 if (counter_nr < max_depth)
3666 debug_print_timestamp(counter_nr, debug_message);
3671 void print_timestamp_init(char *message)
3673 print_timestamp_ext(message, "INIT");
3676 void print_timestamp_time(char *message)
3678 print_timestamp_ext(message, "TIME");
3681 void print_timestamp_done(char *message)
3683 print_timestamp_ext(message, "DONE");