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 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
44 #define DUPLICATE_LOG_OUT_TO_STDOUT TRUE
45 #define DUPLICATE_LOG_ERR_TO_STDERR TRUE
48 #if defined(PLATFORM_ANDROID)
49 static int android_log_prio = ANDROID_LOG_INFO;
50 static char *android_log_buffer = NULL;
52 static void append_to_android_log_buffer(char *format, va_list ap)
54 char text_new[MAX_OUTPUT_LINESIZE];
56 // print text to temporary string
57 vsnprintf(text_new, MAX_OUTPUT_LINESIZE, format, ap);
59 if (android_log_buffer == NULL)
61 android_log_buffer = getStringCopy(text_new);
65 char *android_log_buffer_old = android_log_buffer;
67 // append new text to existing text
68 android_log_buffer = getStringCat2(android_log_buffer, text_new);
70 checked_free(android_log_buffer_old);
74 static void vprintf_log_nonewline(char *format, va_list ap)
76 // add log output to buffer until text with newline is printed
77 append_to_android_log_buffer(format, ap);
80 static void vprintf_log(char *format, va_list ap)
82 // add log output to buffer
83 append_to_android_log_buffer(format, ap);
85 // __android_log_vprint(android_log_prio, program.program_title, format, ap);
86 __android_log_write(android_log_prio, program.program_title,
89 checked_free(android_log_buffer);
90 android_log_buffer = NULL;
95 static void vprintf_log_nonewline(char *format, va_list ap)
97 FILE *file = program.log_file[LOG_ERR_ID];
99 #if DUPLICATE_LOG_ERR_TO_STDERR
100 if (file != program.log_file_default[LOG_ERR_ID])
105 vfprintf(program.log_file_default[LOG_ERR_ID], format, ap2);
111 vfprintf(file, format, ap);
114 static void vprintf_log(char *format, va_list ap)
116 FILE *file = program.log_file[LOG_ERR_ID];
117 char *newline = STRING_NEWLINE;
119 #if DUPLICATE_LOG_ERR_TO_STDERR
120 if (file != program.log_file_default[LOG_ERR_ID])
125 vfprintf(program.log_file_default[LOG_ERR_ID], format, ap2);
126 fprintf(program.log_file_default[LOG_ERR_ID], "%s", newline);
132 vfprintf(file, format, ap);
133 fprintf(file, "%s", newline);
137 static void printf_log_nonewline(char *format, ...)
141 va_start(ap, format);
142 vprintf_log_nonewline(format, ap);
146 static void printf_log(char *format, ...)
150 va_start(ap, format);
151 vprintf_log(format, ap);
155 static void printf_log_line(char *line_chars, int line_length)
159 for (i = 0; i < line_length; i++)
160 printf_log_nonewline("%s", line_chars);
166 // ----------------------------------------------------------------------------
167 // platform independent wrappers for printf() et al.
168 // ----------------------------------------------------------------------------
170 void fprintf_line(FILE *file, char *line_chars, int line_length)
174 for (i = 0; i < line_length; i++)
175 fprintf(file, "%s", line_chars);
180 void fprintf_line_with_prefix(FILE *file, char *prefix, char *line_chars,
183 fprintf(file, "%s", prefix);
184 fprintf_line(file, line_chars, line_length);
187 void printf_line(char *line_chars, int line_length)
189 fprintf_line(stdout, line_chars, line_length);
192 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
194 fprintf_line_with_prefix(stdout, prefix, line_chars, line_length);
197 static void vPrint(char *format, va_list ap)
199 FILE *file = program.log_file[LOG_OUT_ID];
201 #if DUPLICATE_LOG_OUT_TO_STDOUT
202 if (file != program.log_file_default[LOG_OUT_ID])
207 vfprintf(program.log_file_default[LOG_OUT_ID], format, ap2);
213 vfprintf(file, format, ap);
216 void Print(char *format, ...)
220 va_start(ap, format);
225 void PrintNoLog(char *format, ...)
227 FILE *file = program.log_file_default[LOG_OUT_ID];
230 va_start(ap, format);
231 vfprintf(file, format, ap);
237 void PrintLine(char *line_chars, int line_length)
241 for (i = 0; i < line_length; i++)
247 void PrintLineWithPrefix(char *prefix, char *line_chars, int line_length)
250 PrintLine(line_chars, line_length);
254 // ----------------------------------------------------------------------------
256 // ----------------------------------------------------------------------------
258 /* int2str() returns a number converted to a string;
259 the used memory is static, but will be overwritten by later calls,
260 so if you want to save the result, copy it to a private string buffer;
261 there can be 10 local calls of int2str() without buffering the result --
262 the 11th call will then destroy the result from the first call and so on. */
264 char *int2str(int number, int size)
266 static char shift_array[10][40];
267 static int shift_counter = 0;
268 char *s = shift_array[shift_counter];
270 shift_counter = (shift_counter + 1) % 10;
277 sprintf(s, " %09d", number);
278 return &s[strlen(s) - size];
282 sprintf(s, "%d", number);
288 // something similar to "int2str()" above, but allocates its own memory
289 // and has a different interface; we cannot use "itoa()", because this
290 // seems to be already defined when cross-compiling to the win32 target
292 char *i_to_a(unsigned int i)
294 static char *a = NULL;
298 if (i > 2147483647) // yes, this is a kludge
301 a = checked_malloc(10 + 1);
309 // calculate base-2 logarithm of argument (rounded down to integer;
310 // this function returns the number of the highest bit set in argument)
312 int log_2(unsigned int x)
318 x -= (1 << e); // for rounding down (rounding up: remove this line)
325 boolean getTokenValueFromString(char *string, char **token, char **value)
327 return getTokenValueFromSetupLine(string, token, value);
331 // ----------------------------------------------------------------------------
333 // ----------------------------------------------------------------------------
335 // maximal allowed length of a command line option
336 #define MAX_OPTION_LEN 256
338 static unsigned int getCurrentMS(void)
340 return SDL_GetTicks();
343 static unsigned int mainCounter(int mode)
345 static unsigned int base_ms = 0;
346 unsigned int current_ms;
348 // get current system milliseconds
349 current_ms = getCurrentMS();
351 // reset base timestamp in case of counter reset or wrap-around
352 if (mode == INIT_COUNTER || current_ms < base_ms)
353 base_ms = current_ms;
355 // return milliseconds since last counter reset
356 return current_ms - base_ms;
359 void InitCounter() // set counter back to zero
361 mainCounter(INIT_COUNTER);
364 unsigned int Counter() // get milliseconds since last call of InitCounter()
366 return mainCounter(READ_COUNTER);
369 static void sleep_milliseconds(unsigned int milliseconds_delay)
371 SDL_Delay(milliseconds_delay);
374 void Delay(unsigned int delay) // Sleep specified number of milliseconds
376 sleep_milliseconds(delay);
379 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
380 unsigned int actual_counter)
382 if (actual_counter >= *counter_var &&
383 actual_counter < *counter_var + delay)
386 *counter_var = actual_counter;
391 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
393 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
396 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
398 return DelayReachedExt(counter_var, delay, Counter());
401 void ResetDelayCounterExt(unsigned int *counter_var,
402 unsigned int actual_counter)
404 DelayReachedExt(counter_var, 0, actual_counter);
407 void ResetFrameCounter(unsigned int *frame_counter_var)
409 FrameReached(frame_counter_var, 0);
412 void ResetDelayCounter(unsigned int *counter_var)
414 DelayReached(counter_var, 0);
417 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
419 unsigned int actual_counter;
424 actual_counter = Counter();
426 if (actual_counter >= *counter_var &&
427 actual_counter < *counter_var + delay)
428 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
433 if (*counter_var != 0 &&
435 actual_counter >= *counter_var + delay)
437 int lag = actual_counter - (*counter_var + delay);
438 int delay2 = (delay + 1) / 2;
441 skip_frames = (lag + delay2) / delay;
444 *counter_var = actual_counter;
449 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
450 int *loop_var, int last_loop_value)
452 int skip_frames = WaitUntilDelayReached(counter_var, delay);
456 printf("::: %d: %d ms", *loop_var, delay);
458 printf(" -> SKIP %d FRAME(S) [%d ms]", skip_frames, skip_frames * delay);
463 if (skip_frames == 0)
466 // when skipping frames, make sure to never skip the last frame, as
467 // this may be needed for animations to reach a defined end state;
468 // furthermore, we assume that this function is called at the end
469 // of a "for" loop, which continues by incrementing the loop variable
470 // by one before checking the loop condition again; therefore we have
471 // to check against the last loop value minus one here
475 if (*loop_var < last_loop_value) // never skip the last frame
477 *loop_var += skip_frames;
479 if (*loop_var > last_loop_value) // never skip the last frame
480 *loop_var = last_loop_value;
485 // ----------------------------------------------------------------------------
486 // random generator functions
487 // ----------------------------------------------------------------------------
489 unsigned int init_random_number(int nr, int seed)
491 if (seed == NEW_RANDOMIZE)
493 // default random seed
494 seed = (int)time(NULL); // seconds since the epoch
496 #if !defined(PLATFORM_WIN32)
497 // add some more randomness
498 struct timeval current_time;
500 gettimeofday(¤t_time, NULL);
502 seed += (int)current_time.tv_usec; // microseconds since the epoch
505 // add some more randomness
506 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
508 // add some more randomness
509 seed += GetSimpleRandom(1000000);
512 srandom_linux_libc(nr, (unsigned int) seed);
514 return (unsigned int) seed;
517 unsigned int get_random_number(int nr, int max)
519 return (max > 0 ? random_linux_libc(nr) % max : 0);
523 // ----------------------------------------------------------------------------
524 // system info functions
525 // ----------------------------------------------------------------------------
527 #if !defined(PLATFORM_ANDROID)
528 static char *get_corrected_real_name(char *real_name)
530 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
531 char *from_ptr = real_name;
532 char *to_ptr = real_name_new;
534 // copy the name string, but not more than MAX_USERNAME_LEN characters
535 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
537 // the name field read from "passwd" file may also contain additional
538 // user information, separated by commas, which will be removed here
539 if (*from_ptr == ',')
542 // the user's real name may contain 'german sharp s' characters,
543 // which have no equivalent in upper case letters (used by our fonts)
544 if (*from_ptr == CHAR_BYTE_SHARP_S)
551 *to_ptr++ = *from_ptr++;
556 return real_name_new;
560 char *getLoginName(void)
562 static char *login_name = NULL;
564 #if defined(PLATFORM_WIN32)
565 if (login_name == NULL)
567 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
568 login_name = checked_malloc(buffer_size);
570 if (GetUserName(login_name, &buffer_size) == 0)
571 strcpy(login_name, ANONYMOUS_NAME);
573 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
574 if (login_name == NULL)
578 if ((pwd = getpwuid(getuid())) == NULL)
579 login_name = ANONYMOUS_NAME;
581 login_name = getStringCopy(pwd->pw_name);
584 login_name = ANONYMOUS_NAME;
590 char *getRealName(void)
592 static char *real_name = NULL;
594 #if defined(PLATFORM_WIN32)
595 if (real_name == NULL)
597 static char buffer[MAX_USERNAME_LEN + 1];
598 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
600 if (GetUserName(buffer, &buffer_size) != 0)
601 real_name = get_corrected_real_name(buffer);
603 real_name = ANONYMOUS_NAME;
605 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
606 if (real_name == NULL)
610 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
611 real_name = get_corrected_real_name(pwd->pw_gecos);
613 real_name = ANONYMOUS_NAME;
616 real_name = ANONYMOUS_NAME;
622 time_t getFileTimestampEpochSeconds(char *filename)
624 struct stat file_status;
626 if (stat(filename, &file_status) != 0) // cannot stat file
629 return file_status.st_mtime;
633 // ----------------------------------------------------------------------------
634 // path manipulation functions
635 // ----------------------------------------------------------------------------
637 static char *getLastPathSeparatorPtr(char *filename)
639 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
641 if (last_separator == NULL) // also try DOS/Windows variant
642 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
644 return last_separator;
647 char *getBaseNamePtr(char *filename)
649 char *last_separator = getLastPathSeparatorPtr(filename);
651 if (last_separator != NULL)
652 return last_separator + 1; // separator found: strip base path
654 return filename; // no separator found: filename has no path
657 char *getBaseName(char *filename)
659 return getStringCopy(getBaseNamePtr(filename));
662 char *getBaseNameNoSuffix(char *filename)
664 char *basename = getStringCopy(getBaseNamePtr(filename));
666 // remove trailing suffix (separated by dot or hyphen)
667 if (basename[0] != '.' && basename[0] != '-')
669 if (strchr(basename, '.') != NULL)
670 *strchr(basename, '.') = '\0';
672 if (strchr(basename, '-') != NULL)
673 *strchr(basename, '-') = '\0';
679 char *getBasePath(char *filename)
681 char *basepath = getStringCopy(filename);
682 char *last_separator = getLastPathSeparatorPtr(basepath);
684 // if no separator was found, use current directory
685 if (last_separator == NULL)
689 return getStringCopy(".");
692 // separator found: strip basename
693 *last_separator = '\0';
699 // ----------------------------------------------------------------------------
700 // various string functions
701 // ----------------------------------------------------------------------------
703 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
705 if (s1 == NULL || s2 == NULL || sep == NULL)
708 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
711 sprintf(complete_string, "%s%s%s", s1, sep, s2);
713 return complete_string;
716 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
718 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
721 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
722 strlen(s2) + strlen(sep) +
725 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
727 return complete_string;
730 char *getStringCat2(char *s1, char *s2)
732 return getStringCat2WithSeparator(s1, s2, "");
735 char *getStringCat3(char *s1, char *s2, char *s3)
737 return getStringCat3WithSeparator(s1, s2, s3, "");
740 char *getPath2(char *path1, char *path2)
742 #if defined(PLATFORM_ANDROID)
743 // workaround for reading from assets directory -- skip "." subdirs in path
744 if (strEqual(path1, "."))
745 return getStringCopy(path2);
746 else if (strEqual(path2, "."))
747 return getStringCopy(path1);
750 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
753 char *getPath3(char *path1, char *path2, char *path3)
755 #if defined(PLATFORM_ANDROID)
756 // workaround for reading from assets directory -- skip "." subdirs in path
757 if (strEqual(path1, "."))
758 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
759 else if (strEqual(path2, "."))
760 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
761 else if (strEqual(path3, "."))
762 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
765 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
768 static char *getPngOrPcxIfNotExists(char *filename)
770 // switch from PNG to PCX file and vice versa, if file does not exist
771 // (backwards compatibility with PCX files used in previous versions)
773 if (!fileExists(filename) && strSuffix(filename, ".png"))
774 strcpy(&filename[strlen(filename) - 3], "pcx");
775 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
776 strcpy(&filename[strlen(filename) - 3], "png");
781 char *getImg2(char *path1, char *path2)
783 return getPngOrPcxIfNotExists(getPath2(path1, path2));
786 char *getImg3(char *path1, char *path2, char *path3)
788 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
791 char *getStringCopy(const char *s)
798 s_copy = checked_malloc(strlen(s) + 1);
804 char *getStringCopyN(const char *s, int n)
807 int s_len = MAX(0, n);
812 s_copy = checked_malloc(s_len + 1);
813 strncpy(s_copy, s, s_len);
814 s_copy[s_len] = '\0';
819 char *getStringCopyNStatic(const char *s, int n)
821 static char *s_copy = NULL;
823 checked_free(s_copy);
825 s_copy = getStringCopyN(s, n);
830 char *getStringToLower(const char *s)
832 char *s_copy = checked_malloc(strlen(s) + 1);
833 char *s_ptr = s_copy;
836 *s_ptr++ = tolower(*s++);
842 void setString(char **old_value, char *new_value)
844 checked_free(*old_value);
846 *old_value = getStringCopy(new_value);
849 boolean strEqual(char *s1, char *s2)
851 return (s1 == NULL && s2 == NULL ? TRUE :
852 s1 == NULL && s2 != NULL ? FALSE :
853 s1 != NULL && s2 == NULL ? FALSE :
854 strcmp(s1, s2) == 0);
857 boolean strEqualN(char *s1, char *s2, int n)
859 return (s1 == NULL && s2 == NULL ? TRUE :
860 s1 == NULL && s2 != NULL ? FALSE :
861 s1 != NULL && s2 == NULL ? FALSE :
862 strncmp(s1, s2, n) == 0);
865 boolean strPrefix(char *s, char *prefix)
867 return (s == NULL && prefix == NULL ? TRUE :
868 s == NULL && prefix != NULL ? FALSE :
869 s != NULL && prefix == NULL ? FALSE :
870 strncmp(s, prefix, strlen(prefix)) == 0);
873 boolean strSuffix(char *s, char *suffix)
875 return (s == NULL && suffix == NULL ? TRUE :
876 s == NULL && suffix != NULL ? FALSE :
877 s != NULL && suffix == NULL ? FALSE :
878 strlen(s) < strlen(suffix) ? FALSE :
879 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
882 boolean strPrefixLower(char *s, char *prefix)
884 char *s_lower = getStringToLower(s);
885 boolean match = strPrefix(s_lower, prefix);
892 boolean strSuffixLower(char *s, char *suffix)
894 char *s_lower = getStringToLower(s);
895 boolean match = strSuffix(s_lower, suffix);
903 // ----------------------------------------------------------------------------
904 // command line option handling functions
905 // ----------------------------------------------------------------------------
907 void GetOptions(int argc, char *argv[],
908 void (*print_usage_function)(void),
909 void (*print_version_function)(void))
911 char *ro_base_path = getProgramMainDataPath(argv[0], RO_BASE_PATH);
912 char *rw_base_path = getProgramMainDataPath(argv[0], RW_BASE_PATH);
913 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
914 char **options_left = &argvplus[1];
916 // replace original "argv" with null-terminated array of string pointers
918 argvplus[argc] = argv[argc];
920 // initialize global program options
921 options.server_host = NULL;
922 options.server_port = 0;
924 options.ro_base_directory = ro_base_path;
925 options.rw_base_directory = rw_base_path;
926 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
927 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
928 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
929 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
930 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
931 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
933 options.execute_command = NULL;
934 options.special_flags = NULL;
936 options.mytapes = FALSE;
937 options.serveronly = FALSE;
938 options.network = FALSE;
939 options.verbose = FALSE;
940 options.debug = FALSE;
943 options.verbose = TRUE;
945 #if !defined(PLATFORM_UNIX)
946 if (*options_left == NULL) // no options given -- enable verbose mode
947 options.verbose = TRUE;
952 #if defined(PLATFORM_ANDROID)
953 options.debug = TRUE;
957 while (*options_left)
959 char option_str[MAX_OPTION_LEN];
960 char *option = options_left[0];
961 char *next_option = options_left[1];
962 char *option_arg = NULL;
963 int option_len = strlen(option);
965 if (option_len >= MAX_OPTION_LEN)
966 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
968 strcpy(option_str, option); // copy argument into buffer
971 if (strEqual(option, "--")) // stop scanning arguments
974 if (strPrefix(option, "--")) // treat '--' like '-'
977 option_arg = strchr(option, '=');
978 if (option_arg == NULL) // no '=' in option
979 option_arg = next_option;
982 *option_arg++ = '\0'; // cut argument from option
983 if (*option_arg == '\0') // no argument after '='
984 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
987 option_len = strlen(option);
989 if (strEqual(option, "-"))
991 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
993 else if (strncmp(option, "-help", option_len) == 0)
995 print_usage_function();
999 else if (strncmp(option, "-basepath", option_len) == 0)
1001 if (option_arg == NULL)
1002 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1004 // this should be extended to separate options for ro and rw data
1005 options.ro_base_directory = ro_base_path = option_arg;
1006 options.rw_base_directory = rw_base_path = option_arg;
1007 if (option_arg == next_option)
1010 // adjust paths for sub-directories in base directory accordingly
1011 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1012 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1013 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1014 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1015 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1016 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
1018 else if (strncmp(option, "-levels", option_len) == 0)
1020 if (option_arg == NULL)
1021 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1023 options.level_directory = option_arg;
1024 if (option_arg == next_option)
1027 else if (strncmp(option, "-graphics", option_len) == 0)
1029 if (option_arg == NULL)
1030 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1032 options.graphics_directory = option_arg;
1033 if (option_arg == next_option)
1036 else if (strncmp(option, "-sounds", option_len) == 0)
1038 if (option_arg == NULL)
1039 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1041 options.sounds_directory = option_arg;
1042 if (option_arg == next_option)
1045 else if (strncmp(option, "-music", option_len) == 0)
1047 if (option_arg == NULL)
1048 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1050 options.music_directory = option_arg;
1051 if (option_arg == next_option)
1054 else if (strncmp(option, "-mytapes", option_len) == 0)
1056 options.mytapes = TRUE;
1058 else if (strncmp(option, "-network", option_len) == 0)
1060 options.network = TRUE;
1062 else if (strncmp(option, "-serveronly", option_len) == 0)
1064 options.serveronly = TRUE;
1066 else if (strncmp(option, "-debug", option_len) == 0)
1068 options.debug = TRUE;
1070 else if (strncmp(option, "-verbose", option_len) == 0)
1072 options.verbose = TRUE;
1074 else if (strncmp(option, "-version", option_len) == 0 ||
1075 strncmp(option, "-V", option_len) == 0)
1077 print_version_function();
1081 else if (strPrefix(option, "-D"))
1083 options.special_flags = getStringCopy(&option[2]);
1085 else if (strncmp(option, "-execute", option_len) == 0)
1087 if (option_arg == NULL)
1088 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1090 options.execute_command = option_arg;
1091 if (option_arg == next_option)
1094 // when doing batch processing, always enable verbose mode (warnings)
1095 options.verbose = TRUE;
1097 #if defined(PLATFORM_MACOSX)
1098 else if (strPrefix(option, "-psn"))
1100 // ignore process serial number when launched via GUI on Mac OS X
1103 else if (*option == '-')
1105 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1107 else if (options.server_host == NULL)
1109 options.server_host = *options_left;
1111 else if (options.server_port == 0)
1113 options.server_port = atoi(*options_left);
1114 if (options.server_port < 1024)
1115 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1118 Error(ERR_EXIT_HELP, "too many arguments");
1125 // ----------------------------------------------------------------------------
1126 // error handling functions
1127 // ----------------------------------------------------------------------------
1129 #define MAX_INTERNAL_ERROR_SIZE 1024
1131 // used by SetError() and GetError() to store internal error messages
1132 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1134 void SetError(char *format, ...)
1138 va_start(ap, format);
1139 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1143 char *GetError(void)
1145 return internal_error;
1148 void Error(int mode, char *format, ...)
1150 static boolean last_line_was_separator = FALSE;
1151 char *process_name = "";
1153 if (program.log_file[LOG_ERR_ID] == NULL)
1156 #if defined(PLATFORM_ANDROID)
1157 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1158 mode & ERR_INFO ? ANDROID_LOG_INFO :
1159 mode & ERR_WARN ? ANDROID_LOG_WARN :
1160 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1161 ANDROID_LOG_UNKNOWN);
1164 // display debug messages only when running in debug mode
1165 if (mode & ERR_DEBUG && !options.debug)
1168 // display warnings only when running in verbose mode
1169 if (mode & ERR_WARN && !options.verbose)
1172 if (mode == ERR_INFO_LINE)
1174 if (!last_line_was_separator)
1175 printf_log_line(format, 79);
1177 last_line_was_separator = TRUE;
1182 last_line_was_separator = FALSE;
1184 if (mode & ERR_SOUND_SERVER)
1185 process_name = " sound server";
1186 else if (mode & ERR_NETWORK_SERVER)
1187 process_name = " network server";
1188 else if (mode & ERR_NETWORK_CLIENT)
1189 process_name = " network client **";
1193 #if !defined(PLATFORM_ANDROID)
1194 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1197 if (mode & ERR_WARN)
1198 printf_log_nonewline("warning: ");
1200 if (mode & ERR_EXIT)
1201 printf_log_nonewline("fatal error: ");
1205 va_start(ap, format);
1206 vprintf_log(format, ap);
1209 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1211 va_start(ap, format);
1212 program.exit_message_function(format, ap);
1217 if (mode & ERR_HELP)
1218 printf_log("%s: Try option '--help' for more information.",
1219 program.command_basename);
1221 if (mode & ERR_EXIT)
1222 printf_log("%s%s: aborting", program.command_basename, process_name);
1224 if (mode & ERR_EXIT)
1226 if (mode & ERR_FROM_SERVER)
1227 exit(1); // child process: normal exit
1229 program.exit_function(1); // main process: clean up stuff
1234 // ----------------------------------------------------------------------------
1235 // checked memory allocation and freeing functions
1236 // ----------------------------------------------------------------------------
1238 void *checked_malloc(unsigned int size)
1245 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1250 void *checked_calloc(unsigned int size)
1254 ptr = calloc(1, size);
1257 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1262 void *checked_realloc(void *ptr, unsigned int size)
1264 ptr = realloc(ptr, size);
1267 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1272 void checked_free(void *ptr)
1274 if (ptr != NULL) // this check should be done by free() anyway
1278 void clear_mem(void *ptr, unsigned int size)
1280 #if defined(PLATFORM_WIN32)
1281 // for unknown reason, memset() sometimes crashes when compiled with MinGW
1282 char *cptr = (char *)ptr;
1287 memset(ptr, 0, size);
1292 // ----------------------------------------------------------------------------
1293 // various helper functions
1294 // ----------------------------------------------------------------------------
1296 void swap_numbers(int *i1, int *i2)
1304 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1316 /* the "put" variants of the following file access functions check for the file
1317 pointer being != NULL and return the number of bytes they have or would have
1318 written; this allows for chunk writing functions to first determine the size
1319 of the (not yet written) chunk, write the correct chunk size and finally
1320 write the chunk itself */
1322 int getFile8BitInteger(File *file)
1324 return getByteFromFile(file);
1327 int putFile8BitInteger(FILE *file, int value)
1335 int getFile16BitInteger(File *file, int byte_order)
1337 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1338 return ((getByteFromFile(file) << 8) |
1339 (getByteFromFile(file) << 0));
1340 else // BYTE_ORDER_LITTLE_ENDIAN
1341 return ((getByteFromFile(file) << 0) |
1342 (getByteFromFile(file) << 8));
1345 int putFile16BitInteger(FILE *file, int value, int byte_order)
1349 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1351 fputc((value >> 8) & 0xff, file);
1352 fputc((value >> 0) & 0xff, file);
1354 else // BYTE_ORDER_LITTLE_ENDIAN
1356 fputc((value >> 0) & 0xff, file);
1357 fputc((value >> 8) & 0xff, file);
1364 int getFile32BitInteger(File *file, int byte_order)
1366 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1367 return ((getByteFromFile(file) << 24) |
1368 (getByteFromFile(file) << 16) |
1369 (getByteFromFile(file) << 8) |
1370 (getByteFromFile(file) << 0));
1371 else // BYTE_ORDER_LITTLE_ENDIAN
1372 return ((getByteFromFile(file) << 0) |
1373 (getByteFromFile(file) << 8) |
1374 (getByteFromFile(file) << 16) |
1375 (getByteFromFile(file) << 24));
1378 int putFile32BitInteger(FILE *file, int value, int byte_order)
1382 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1384 fputc((value >> 24) & 0xff, file);
1385 fputc((value >> 16) & 0xff, file);
1386 fputc((value >> 8) & 0xff, file);
1387 fputc((value >> 0) & 0xff, file);
1389 else // BYTE_ORDER_LITTLE_ENDIAN
1391 fputc((value >> 0) & 0xff, file);
1392 fputc((value >> 8) & 0xff, file);
1393 fputc((value >> 16) & 0xff, file);
1394 fputc((value >> 24) & 0xff, file);
1401 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1404 const int chunk_name_length = 4;
1407 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1410 if (chunk_size != NULL)
1413 *chunk_size = getFile32BitInteger(file, byte_order);
1416 return (checkEndOfFile(file) ? FALSE : TRUE);
1419 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1426 fputs(chunk_name, file);
1428 num_bytes += strlen(chunk_name);
1430 if (chunk_size >= 0)
1434 putFile32BitInteger(file, chunk_size, byte_order);
1442 int getFileVersion(File *file)
1444 int version_super = getByteFromFile(file);
1445 int version_major = getByteFromFile(file);
1446 int version_minor = getByteFromFile(file);
1447 int version_patch = getByteFromFile(file);
1449 return VERSION_IDENT(version_super, version_major, version_minor,
1453 int putFileVersion(FILE *file, int version)
1457 int version_super = VERSION_SUPER(version);
1458 int version_major = VERSION_MAJOR(version);
1459 int version_minor = VERSION_MINOR(version);
1460 int version_patch = VERSION_PATCH(version);
1462 fputc(version_super, file);
1463 fputc(version_major, file);
1464 fputc(version_minor, file);
1465 fputc(version_patch, file);
1471 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1475 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1476 buffer[i] = getByteFromFile(file);
1479 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1483 for (i = 0; i < bytes; i++)
1484 fputc(buffer[i], file);
1487 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1489 while (bytes-- && !checkEndOfFile(file))
1490 getByteFromFile(file);
1493 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1500 // ----------------------------------------------------------------------------
1501 // functions to translate key identifiers between different format
1502 // ----------------------------------------------------------------------------
1504 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1505 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1506 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1507 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1509 static void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1518 // return and escape keys
1519 { KSYM_Return, "XK_Return", "return" },
1520 { KSYM_Escape, "XK_Escape", "escape" },
1522 // normal cursor keys
1523 { KSYM_Left, "XK_Left", "cursor left" },
1524 { KSYM_Right, "XK_Right", "cursor right" },
1525 { KSYM_Up, "XK_Up", "cursor up" },
1526 { KSYM_Down, "XK_Down", "cursor down" },
1528 // keypad cursor keys
1530 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1531 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1532 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1533 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1536 // other keypad keys
1537 #ifdef KSYM_KP_Enter
1538 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1539 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1540 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1541 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1542 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1543 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1547 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1548 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1549 { KSYM_Control_L, "XK_Control_L", "left control" },
1550 { KSYM_Control_R, "XK_Control_R", "right control" },
1551 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1552 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1553 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1554 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1555 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, // Alt-R
1556 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, // Ctrl-R
1558 // some special keys
1559 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1560 { KSYM_Delete, "XK_Delete", "delete" },
1561 { KSYM_Insert, "XK_Insert", "insert" },
1562 { KSYM_Tab, "XK_Tab", "tab" },
1563 { KSYM_Home, "XK_Home", "home" },
1564 { KSYM_End, "XK_End", "end" },
1565 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1566 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1568 { KSYM_Select, "XK_Select", "select" },
1569 { KSYM_Menu, "XK_Menu", "menu" }, // menu key
1570 { KSYM_Back, "XK_Back", "back" }, // back key
1571 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
1572 #if defined(PLATFORM_ANDROID)
1573 { KSYM_Rewind, "XK_Rewind", "rewind" },
1574 { KSYM_FastForward, "XK_FastForward", "fast forward" },
1577 // ASCII 0x20 to 0x40 keys (except numbers)
1578 { KSYM_space, "XK_space", "space" },
1579 { KSYM_exclam, "XK_exclam", "!" },
1580 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1581 { KSYM_numbersign, "XK_numbersign", "#" },
1582 { KSYM_dollar, "XK_dollar", "$" },
1583 { KSYM_percent, "XK_percent", "%" },
1584 { KSYM_ampersand, "XK_ampersand", "&" },
1585 { KSYM_apostrophe, "XK_apostrophe", "'" },
1586 { KSYM_parenleft, "XK_parenleft", "(" },
1587 { KSYM_parenright, "XK_parenright", ")" },
1588 { KSYM_asterisk, "XK_asterisk", "*" },
1589 { KSYM_plus, "XK_plus", "+" },
1590 { KSYM_comma, "XK_comma", "," },
1591 { KSYM_minus, "XK_minus", "-" },
1592 { KSYM_period, "XK_period", "." },
1593 { KSYM_slash, "XK_slash", "/" },
1594 { KSYM_colon, "XK_colon", ":" },
1595 { KSYM_semicolon, "XK_semicolon", ";" },
1596 { KSYM_less, "XK_less", "<" },
1597 { KSYM_equal, "XK_equal", "=" },
1598 { KSYM_greater, "XK_greater", ">" },
1599 { KSYM_question, "XK_question", "?" },
1600 { KSYM_at, "XK_at", "@" },
1603 { KSYM_bracketleft, "XK_bracketleft", "[" },
1604 { KSYM_backslash, "XK_backslash", "\\" },
1605 { KSYM_bracketright,"XK_bracketright", "]" },
1606 { KSYM_asciicircum, "XK_asciicircum", "^" },
1607 { KSYM_underscore, "XK_underscore", "_" },
1608 { KSYM_grave, "XK_grave", "grave" },
1609 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1610 { KSYM_braceleft, "XK_braceleft", "brace left" },
1611 { KSYM_bar, "XK_bar", "bar" },
1612 { KSYM_braceright, "XK_braceright", "brace right" },
1613 { KSYM_asciitilde, "XK_asciitilde", "~" },
1615 // special (non-ASCII) keys
1616 { KSYM_degree, "XK_degree", "degree" },
1617 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1618 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1619 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1620 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1621 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1622 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1623 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1625 // special (non-ASCII) keys (UTF-8, for reverse mapping only)
1626 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1627 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1628 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1629 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1630 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1631 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1632 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1633 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1635 // other keys (for reverse mapping only)
1636 { KSYM_space, "XK_space", " " },
1638 // keypad keys are not in numerical order in SDL2
1639 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1640 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1641 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1642 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1643 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1644 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1645 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1646 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1647 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1648 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1650 // end-of-array identifier
1656 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1658 static char name_buffer[30];
1661 if (key >= KSYM_A && key <= KSYM_Z)
1662 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1663 else if (key >= KSYM_a && key <= KSYM_z)
1664 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1665 else if (key >= KSYM_0 && key <= KSYM_9)
1666 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1667 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1668 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1669 else if (key == KSYM_UNDEFINED)
1670 strcpy(name_buffer, "(undefined)");
1677 if (key == translate_key[i].key)
1679 strcpy(name_buffer, translate_key[i].name);
1683 while (translate_key[++i].name);
1685 if (!translate_key[i].name)
1686 strcpy(name_buffer, "(unknown)");
1689 *name = name_buffer;
1691 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1693 static char name_buffer[30];
1696 if (key >= KSYM_A && key <= KSYM_Z)
1697 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1698 else if (key >= KSYM_a && key <= KSYM_z)
1699 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1700 else if (key >= KSYM_0 && key <= KSYM_9)
1701 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1702 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1703 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1704 else if (key == KSYM_UNDEFINED)
1705 strcpy(name_buffer, "[undefined]");
1712 if (key == translate_key[i].key)
1714 strcpy(name_buffer, translate_key[i].x11name);
1718 while (translate_key[++i].x11name);
1720 if (!translate_key[i].x11name)
1721 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1724 *x11name = name_buffer;
1726 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1728 Key key = KSYM_UNDEFINED;
1729 char *name_ptr = *name;
1731 if (strlen(*name) == 1)
1733 char c = name_ptr[0];
1735 if (c >= 'A' && c <= 'Z')
1736 key = KSYM_A + (Key)(c - 'A');
1737 else if (c >= 'a' && c <= 'z')
1738 key = KSYM_a + (Key)(c - 'a');
1739 else if (c >= '0' && c <= '9')
1740 key = KSYM_0 + (Key)(c - '0');
1743 if (key == KSYM_UNDEFINED)
1749 if (strEqual(translate_key[i].name, *name))
1751 key = translate_key[i].key;
1755 while (translate_key[++i].x11name);
1758 if (key == KSYM_UNDEFINED)
1759 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1763 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1765 Key key = KSYM_UNDEFINED;
1766 char *name_ptr = *x11name;
1768 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1770 char c = name_ptr[3];
1772 if (c >= 'A' && c <= 'Z')
1773 key = KSYM_A + (Key)(c - 'A');
1774 else if (c >= 'a' && c <= 'z')
1775 key = KSYM_a + (Key)(c - 'a');
1776 else if (c >= '0' && c <= '9')
1777 key = KSYM_0 + (Key)(c - '0');
1779 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1781 char c1 = name_ptr[4];
1782 char c2 = name_ptr[5];
1785 if ((c1 >= '0' && c1 <= '9') &&
1786 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1787 d = atoi(&name_ptr[4]);
1789 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1790 key = KSYM_F1 + (Key)(d - 1);
1792 else if (strPrefix(name_ptr, "XK_"))
1798 if (strEqual(name_ptr, translate_key[i].x11name))
1800 key = translate_key[i].key;
1804 while (translate_key[++i].x11name);
1806 else if (strPrefix(name_ptr, "0x"))
1808 unsigned int value = 0;
1814 char c = *name_ptr++;
1817 if (c >= '0' && c <= '9')
1819 else if (c >= 'a' && c <= 'f')
1820 d = (int)(c - 'a' + 10);
1821 else if (c >= 'A' && c <= 'F')
1822 d = (int)(c - 'A' + 10);
1830 value = value * 16 + d;
1841 char *getKeyNameFromKey(Key key)
1845 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1849 char *getX11KeyNameFromKey(Key key)
1853 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1857 Key getKeyFromKeyName(char *name)
1861 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1865 Key getKeyFromX11KeyName(char *x11name)
1869 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1873 char getCharFromKey(Key key)
1879 } translate_key_char[] =
1881 // special (non-ASCII) keys (ISO-8859-1)
1882 { KSYM_degree, CHAR_BYTE_DEGREE },
1883 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1884 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1885 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1886 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1887 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1888 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1889 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1891 // end-of-array identifier
1895 char *keyname = getKeyNameFromKey(key);
1898 if (strlen(keyname) == 1)
1900 else if (strEqual(keyname, "space"))
1908 if (key == translate_key_char[i].key)
1910 c = translate_key_char[i].key_char;
1915 while (translate_key_char[++i].key_char);
1921 char getValidConfigValueChar(char c)
1923 if (c == '#' || // used to mark comments
1924 c == '\\') // used to mark continued lines
1931 // ----------------------------------------------------------------------------
1932 // functions to translate string identifiers to integer or boolean value
1933 // ----------------------------------------------------------------------------
1935 int get_integer_from_string(char *s)
1937 static char *number_text[][3] =
1939 { "0", "zero", "null", },
1940 { "1", "one", "first" },
1941 { "2", "two", "second" },
1942 { "3", "three", "third" },
1943 { "4", "four", "fourth" },
1944 { "5", "five", "fifth" },
1945 { "6", "six", "sixth" },
1946 { "7", "seven", "seventh" },
1947 { "8", "eight", "eighth" },
1948 { "9", "nine", "ninth" },
1949 { "10", "ten", "tenth" },
1950 { "11", "eleven", "eleventh" },
1951 { "12", "twelve", "twelfth" },
1953 { NULL, NULL, NULL },
1957 char *s_lower = getStringToLower(s);
1960 for (i = 0; number_text[i][0] != NULL; i++)
1961 for (j = 0; j < 3; j++)
1962 if (strEqual(s_lower, number_text[i][j]))
1967 if (strEqual(s_lower, "false") ||
1968 strEqual(s_lower, "no") ||
1969 strEqual(s_lower, "off"))
1971 else if (strEqual(s_lower, "true") ||
1972 strEqual(s_lower, "yes") ||
1973 strEqual(s_lower, "on"))
1984 boolean get_boolean_from_string(char *s)
1986 char *s_lower = getStringToLower(s);
1987 boolean result = FALSE;
1989 if (strEqual(s_lower, "true") ||
1990 strEqual(s_lower, "yes") ||
1991 strEqual(s_lower, "on") ||
1992 get_integer_from_string(s) == 1)
2000 int get_switch3_from_string(char *s)
2002 char *s_lower = getStringToLower(s);
2005 if (strEqual(s_lower, "true") ||
2006 strEqual(s_lower, "yes") ||
2007 strEqual(s_lower, "on") ||
2008 get_integer_from_string(s) == 1)
2010 else if (strEqual(s_lower, "auto"))
2018 int get_player_nr_from_string(char *s)
2020 static char *player_text[] =
2030 char *s_lower = getStringToLower(s);
2034 for (i = 0; player_text[i] != NULL; i++)
2035 if (strEqual(s_lower, player_text[i]))
2044 // ----------------------------------------------------------------------------
2045 // functions for generic lists
2046 // ----------------------------------------------------------------------------
2048 ListNode *newListNode(void)
2050 return checked_calloc(sizeof(ListNode));
2053 void addNodeToList(ListNode **node_first, char *key, void *content)
2055 ListNode *node_new = newListNode();
2057 node_new->key = getStringCopy(key);
2058 node_new->content = content;
2059 node_new->next = *node_first;
2062 (*node_first)->prev = node_new;
2064 *node_first = node_new;
2067 void deleteNodeFromList(ListNode **node_first, char *key,
2068 void (*destructor_function)(void *))
2070 if (node_first == NULL || *node_first == NULL)
2073 if (strEqual((*node_first)->key, key))
2075 // after first recursion, (*node_first)->prev->next == *node_first,
2076 // so *node_first would be overwritten with (*node_first)->next
2077 // => use a copy of *node_first (and later of (*node_first)->next)
2078 ListNode *node = *node_first;
2079 ListNode *node_next = node->next;
2081 checked_free(node->key);
2083 if (destructor_function)
2084 destructor_function(node->content);
2087 node->prev->next = node->next;
2090 node->next->prev = node->prev;
2094 // after removing node, set list pointer to next valid list node
2095 // (this is important if the first node of the list was deleted)
2096 *node_first = node_next;
2100 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2104 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2106 if (node_first == NULL)
2109 if (strEqual(node_first->key, key))
2112 return getNodeFromKey(node_first->next, key);
2115 int getNumNodes(ListNode *node_first)
2117 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2121 static void dumpList(ListNode *node_first)
2123 ListNode *node = node_first;
2127 printf("['%s' (%d)]\n", node->key,
2128 ((struct ListNodeInfo *)node->content)->num_references);
2132 printf("[%d nodes]\n", getNumNodes(node_first));
2137 // ----------------------------------------------------------------------------
2138 // functions for file handling
2139 // ----------------------------------------------------------------------------
2141 #define MAX_BUFFER_SIZE 4096
2143 File *openFile(char *filename, char *mode)
2145 File *file = checked_calloc(sizeof(File));
2147 file->file = fopen(filename, mode);
2149 if (file->file != NULL)
2151 file->filename = getStringCopy(filename);
2156 #if defined(PLATFORM_ANDROID)
2157 file->asset_file = SDL_RWFromFile(filename, mode);
2159 if (file->asset_file != NULL)
2161 file->file_is_asset = TRUE;
2162 file->filename = getStringCopy(filename);
2173 int closeFile(File *file)
2180 #if defined(PLATFORM_ANDROID)
2181 if (file->asset_file)
2182 result = SDL_RWclose(file->asset_file);
2186 result = fclose(file->file);
2188 checked_free(file->filename);
2194 int checkEndOfFile(File *file)
2196 #if defined(PLATFORM_ANDROID)
2197 if (file->file_is_asset)
2198 return file->end_of_file;
2201 return feof(file->file);
2204 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2206 #if defined(PLATFORM_ANDROID)
2207 if (file->file_is_asset)
2209 if (file->end_of_file)
2212 size_t num_items_read =
2213 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2215 if (num_items_read < num_items)
2216 file->end_of_file = TRUE;
2218 return num_items_read;
2222 return fread(buffer, item_size, num_items, file->file);
2225 size_t writeFile(File *file, void *buffer, size_t item_size, size_t num_items)
2227 return fwrite(buffer, item_size, num_items, file->file);
2230 int seekFile(File *file, long offset, int whence)
2232 #if defined(PLATFORM_ANDROID)
2233 if (file->file_is_asset)
2235 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2236 whence == SEEK_CUR ? RW_SEEK_CUR :
2237 whence == SEEK_END ? RW_SEEK_END : 0);
2239 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2243 return fseek(file->file, offset, whence);
2246 int getByteFromFile(File *file)
2248 #if defined(PLATFORM_ANDROID)
2249 if (file->file_is_asset)
2251 if (file->end_of_file)
2255 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2257 if (num_bytes_read < 1)
2258 file->end_of_file = TRUE;
2260 return (file->end_of_file ? EOF : (int)c);
2264 return fgetc(file->file);
2267 char *getStringFromFile(File *file, char *line, int size)
2269 #if defined(PLATFORM_ANDROID)
2270 if (file->file_is_asset)
2272 if (file->end_of_file)
2275 char *line_ptr = line;
2276 int num_bytes_read = 0;
2278 while (num_bytes_read < size - 1 &&
2279 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2280 *line_ptr++ != '\n')
2285 if (strlen(line) == 0)
2287 file->end_of_file = TRUE;
2296 return fgets(line, size, file->file);
2299 int copyFile(char *filename_from, char *filename_to)
2301 File *file_from, *file_to;
2303 if ((file_from = openFile(filename_from, MODE_READ)) == NULL)
2308 if ((file_to = openFile(filename_to, MODE_WRITE)) == NULL)
2310 closeFile(file_from);
2315 while (!checkEndOfFile(file_from))
2317 byte buffer[MAX_BUFFER_SIZE];
2318 size_t bytes_read = readFile(file_from, buffer, 1, MAX_BUFFER_SIZE);
2320 writeFile(file_to, buffer, 1, bytes_read);
2323 closeFile(file_from);
2330 // ----------------------------------------------------------------------------
2331 // functions for directory handling
2332 // ----------------------------------------------------------------------------
2334 Directory *openDirectory(char *dir_name)
2336 Directory *dir = checked_calloc(sizeof(Directory));
2338 dir->dir = opendir(dir_name);
2340 if (dir->dir != NULL)
2342 dir->filename = getStringCopy(dir_name);
2347 #if defined(PLATFORM_ANDROID)
2348 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2350 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2352 checked_free(asset_toc_filename);
2354 if (dir->asset_toc_file != NULL)
2356 dir->directory_is_asset = TRUE;
2357 dir->filename = getStringCopy(dir_name);
2368 int closeDirectory(Directory *dir)
2375 #if defined(PLATFORM_ANDROID)
2376 if (dir->asset_toc_file)
2377 result = SDL_RWclose(dir->asset_toc_file);
2381 result = closedir(dir->dir);
2384 freeDirectoryEntry(dir->dir_entry);
2386 checked_free(dir->filename);
2392 DirectoryEntry *readDirectory(Directory *dir)
2395 freeDirectoryEntry(dir->dir_entry);
2397 dir->dir_entry = NULL;
2399 #if defined(PLATFORM_ANDROID)
2400 if (dir->directory_is_asset)
2402 char line[MAX_LINE_LEN];
2403 char *line_ptr = line;
2404 int num_bytes_read = 0;
2406 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2407 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2416 if (strlen(line) == 0)
2419 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2421 dir->dir_entry->is_directory = FALSE;
2422 if (line[strlen(line) - 1] == '/')
2424 dir->dir_entry->is_directory = TRUE;
2426 line[strlen(line) - 1] = '\0';
2429 dir->dir_entry->basename = getStringCopy(line);
2430 dir->dir_entry->filename = getPath2(dir->filename, line);
2432 return dir->dir_entry;
2436 struct dirent *dir_entry = readdir(dir->dir);
2438 if (dir_entry == NULL)
2441 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2443 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2444 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2446 struct stat file_status;
2448 dir->dir_entry->is_directory =
2449 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2450 S_ISDIR(file_status.st_mode));
2452 return dir->dir_entry;
2455 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2457 if (dir_entry == NULL)
2460 checked_free(dir_entry->basename);
2461 checked_free(dir_entry->filename);
2462 checked_free(dir_entry);
2466 // ----------------------------------------------------------------------------
2467 // functions for checking files and filenames
2468 // ----------------------------------------------------------------------------
2470 boolean directoryExists(char *dir_name)
2472 if (dir_name == NULL)
2475 struct stat file_status;
2476 boolean success = (stat(dir_name, &file_status) == 0 &&
2477 S_ISDIR(file_status.st_mode));
2479 #if defined(PLATFORM_ANDROID)
2482 // this might be an asset directory; check by trying to open toc file
2483 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2484 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2486 checked_free(asset_toc_filename);
2488 success = (file != NULL);
2498 boolean fileExists(char *filename)
2500 if (filename == NULL)
2503 boolean success = (access(filename, F_OK) == 0);
2505 #if defined(PLATFORM_ANDROID)
2508 // this might be an asset file; check by trying to open it
2509 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2511 success = (file != NULL);
2522 static boolean fileHasPrefix(char *basename, char *prefix)
2524 static char *basename_lower = NULL;
2525 int basename_length, prefix_length;
2527 checked_free(basename_lower);
2529 if (basename == NULL || prefix == NULL)
2532 basename_lower = getStringToLower(basename);
2533 basename_length = strlen(basename_lower);
2534 prefix_length = strlen(prefix);
2536 if (basename_length > prefix_length + 1 &&
2537 basename_lower[prefix_length] == '.' &&
2538 strncmp(basename_lower, prefix, prefix_length) == 0)
2545 static boolean fileHasSuffix(char *basename, char *suffix)
2547 static char *basename_lower = NULL;
2548 int basename_length, suffix_length;
2550 checked_free(basename_lower);
2552 if (basename == NULL || suffix == NULL)
2555 basename_lower = getStringToLower(basename);
2556 basename_length = strlen(basename_lower);
2557 suffix_length = strlen(suffix);
2559 if (basename_length > suffix_length + 1 &&
2560 basename_lower[basename_length - suffix_length - 1] == '.' &&
2561 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2567 static boolean FileCouldBeArtwork(char *filename)
2569 char *basename = getBaseNamePtr(filename);
2571 return (!strEqual(basename, ".") &&
2572 !strEqual(basename, "..") &&
2573 !fileHasSuffix(basename, "txt") &&
2574 !fileHasSuffix(basename, "conf") &&
2575 !directoryExists(filename));
2578 boolean FileIsGraphic(char *filename)
2580 return FileCouldBeArtwork(filename);
2583 boolean FileIsSound(char *filename)
2585 return FileCouldBeArtwork(filename);
2588 boolean FileIsMusic(char *filename)
2590 return FileCouldBeArtwork(filename);
2593 boolean FileIsArtworkType(char *filename, int type)
2595 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2596 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2597 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2603 // ----------------------------------------------------------------------------
2604 // functions for loading artwork configuration information
2605 // ----------------------------------------------------------------------------
2607 char *get_mapped_token(char *token)
2609 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
2610 static char *map_token_prefix[][2] =
2612 { "char_procent", "char_percent" },
2613 { "bd_magic_wall_filling", "bd_magic_wall.filling" },
2614 { "bd_magic_wall_emptying", "bd_magic_wall.emptying" },
2615 { "bd_butterfly_left", "bd_butterfly.left" },
2616 { "bd_butterfly_right", "bd_butterfly.right" },
2617 { "bd_butterfly_up", "bd_butterfly.up" },
2618 { "bd_butterfly_down", "bd_butterfly.down" },
2619 { "bd_firefly_left", "bd_firefly.left" },
2620 { "bd_firefly_right", "bd_firefly.right" },
2621 { "bd_firefly_up", "bd_firefly.up" },
2622 { "bd_firefly_down", "bd_firefly.down" },
2628 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2630 int len_token_prefix = strlen(map_token_prefix[i][0]);
2632 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2633 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2636 // change tokens containing ".gfx" by moving the "gfx" part to the very left
2637 char *gfx_substring = ".gfx";
2638 char *gfx_prefix = "gfx.";
2639 if (strstr(token, gfx_substring) != NULL)
2641 char *token_prefix = getStringCopy(token);
2642 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
2643 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
2646 // cut off token string at ".gfx" substring position
2647 *token_gfx_pos = '\0';
2649 // put together prefix "gfx." and token prefix and suffix without ".gfx"
2650 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
2654 return mapped_token;
2660 static char *get_special_base_token(struct ArtworkListInfo *artwork_info,
2663 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
2664 static struct ConfigTypeInfo prefix_list[] =
2666 { "global.anim_1" },
2667 { "global.anim_2" },
2668 { "global.anim_3" },
2669 { "global.anim_4" },
2670 { "global.anim_5" },
2671 { "global.anim_6" },
2672 { "global.anim_7" },
2673 { "global.anim_8" },
2674 { "global.anim_9" },
2675 { "global.anim_10" },
2676 { "global.anim_11" },
2677 { "global.anim_12" },
2678 { "global.anim_13" },
2679 { "global.anim_14" },
2680 { "global.anim_15" },
2681 { "global.anim_16" },
2682 { "global.anim_17" },
2683 { "global.anim_18" },
2684 { "global.anim_19" },
2685 { "global.anim_20" },
2686 { "global.anim_21" },
2687 { "global.anim_22" },
2688 { "global.anim_23" },
2689 { "global.anim_24" },
2690 { "global.anim_25" },
2691 { "global.anim_26" },
2692 { "global.anim_27" },
2693 { "global.anim_28" },
2694 { "global.anim_29" },
2695 { "global.anim_30" },
2696 { "global.anim_31" },
2697 { "global.anim_32" },
2701 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2702 boolean prefix_found = FALSE;
2706 // search for prefix to check if base token has to be created
2707 for (i = 0; prefix_list[i].token != NULL; i++)
2708 if (strPrefix(token, prefix_list[i].token))
2709 prefix_found = TRUE;
2714 // search for suffix (parameter) to determine base token length
2715 for (i = 0; suffix_list[i].token != NULL; i++)
2716 if (strSuffix(token, suffix_list[i].token))
2717 len_suffix = strlen(suffix_list[i].token);
2719 return getStringCopyN(token, strlen(token) - len_suffix);
2722 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2723 struct ListNodeInfo ***, int *);
2725 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2726 struct ConfigTypeInfo *suffix_list,
2727 char **ignore_tokens,
2728 int num_file_list_entries)
2730 SetupFileHash *ignore_tokens_hash;
2731 struct FileInfo *file_list;
2732 int num_file_list_entries_found = 0;
2733 int num_suffix_list_entries = 0;
2737 // create hash from list of tokens to be ignored (for quick access)
2738 ignore_tokens_hash = newSetupFileHash();
2739 for (i = 0; ignore_tokens[i] != NULL; i++)
2740 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
2742 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2744 for (i = 0; suffix_list[i].token != NULL; i++)
2745 num_suffix_list_entries++;
2747 // always start with reliable default values
2748 for (i = 0; i < num_file_list_entries; i++)
2750 file_list[i].token = NULL;
2752 file_list[i].default_filename = NULL;
2753 file_list[i].filename = NULL;
2755 if (num_suffix_list_entries > 0)
2757 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2759 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2760 file_list[i].parameter = checked_calloc(parameter_array_size);
2762 for (j = 0; j < num_suffix_list_entries; j++)
2764 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2765 setString(&file_list[i].parameter[j], suffix_list[j].value);
2768 file_list[i].redefined = FALSE;
2769 file_list[i].fallback_to_default = FALSE;
2770 file_list[i].default_is_cloned = FALSE;
2776 for (i = 0; config_list[i].token != NULL; i++)
2778 int len_config_token = strlen(config_list[i].token);
2779 boolean is_file_entry = TRUE;
2781 for (j = 0; suffix_list[j].token != NULL; j++)
2783 int len_suffix = strlen(suffix_list[j].token);
2785 if (len_suffix < len_config_token &&
2786 strEqual(&config_list[i].token[len_config_token - len_suffix],
2787 suffix_list[j].token))
2789 setString(&file_list[list_pos].default_parameter[j],
2790 config_list[i].value);
2792 is_file_entry = FALSE;
2798 // the following tokens are no file definitions, but other config tokens
2799 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
2800 is_file_entry = FALSE;
2807 if (list_pos >= num_file_list_entries)
2810 file_list[list_pos].token = config_list[i].token;
2811 file_list[list_pos].default_filename = config_list[i].value;
2814 if (strSuffix(config_list[i].token, ".clone_from"))
2815 file_list[list_pos].default_is_cloned = TRUE;
2818 num_file_list_entries_found = list_pos + 1;
2819 if (num_file_list_entries_found != num_file_list_entries)
2821 Error(ERR_INFO_LINE, "-");
2822 Error(ERR_INFO, "inconsistant config list information:");
2823 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2824 num_file_list_entries);
2825 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2826 num_file_list_entries_found);
2827 Error(ERR_EXIT, "please fix");
2830 freeSetupFileHash(ignore_tokens_hash);
2835 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2837 int len_token = strlen(token);
2838 int len_suffix = strlen(suffix);
2840 if (start_pos < 0) // compare suffix from end of string
2841 start_pos += len_token;
2843 if (start_pos < 0 || start_pos + len_suffix > len_token)
2846 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2849 if (token[start_pos + len_suffix] == '\0')
2852 if (token[start_pos + len_suffix] == '.')
2858 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2860 static void read_token_parameters(SetupFileHash *setup_file_hash,
2861 struct ConfigTypeInfo *suffix_list,
2862 struct FileInfo *file_list_entry)
2864 // check for config token that is the base token without any suffixes
2865 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2866 char *known_token_value = KNOWN_TOKEN_VALUE;
2869 if (filename != NULL)
2871 setString(&file_list_entry->filename, filename);
2873 // when file definition found, set all parameters to default values
2874 for (i = 0; suffix_list[i].token != NULL; i++)
2875 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2877 file_list_entry->redefined = TRUE;
2879 // mark config file token as well known from default config
2880 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2883 // check for config tokens that can be build by base token and suffixes
2884 for (i = 0; suffix_list[i].token != NULL; i++)
2886 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2887 char *value = getHashEntry(setup_file_hash, token);
2891 setString(&file_list_entry->parameter[i], value);
2893 // mark config file token as well known from default config
2894 setHashEntry(setup_file_hash, token, known_token_value);
2901 static void add_dynamic_file_list_entry(struct FileInfo **list,
2902 int *num_list_entries,
2903 SetupFileHash *extra_file_hash,
2904 struct ConfigTypeInfo *suffix_list,
2905 int num_suffix_list_entries,
2908 struct FileInfo *new_list_entry;
2909 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2911 (*num_list_entries)++;
2912 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2913 new_list_entry = &(*list)[*num_list_entries - 1];
2915 new_list_entry->token = getStringCopy(token);
2916 new_list_entry->default_filename = NULL;
2917 new_list_entry->filename = NULL;
2918 new_list_entry->parameter = checked_calloc(parameter_array_size);
2920 new_list_entry->redefined = FALSE;
2921 new_list_entry->fallback_to_default = FALSE;
2922 new_list_entry->default_is_cloned = FALSE;
2924 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2927 static void add_property_mapping(struct PropertyMapping **list,
2928 int *num_list_entries,
2929 int base_index, int ext1_index,
2930 int ext2_index, int ext3_index,
2933 struct PropertyMapping *new_list_entry;
2935 (*num_list_entries)++;
2936 *list = checked_realloc(*list,
2937 *num_list_entries * sizeof(struct PropertyMapping));
2938 new_list_entry = &(*list)[*num_list_entries - 1];
2940 new_list_entry->base_index = base_index;
2941 new_list_entry->ext1_index = ext1_index;
2942 new_list_entry->ext2_index = ext2_index;
2943 new_list_entry->ext3_index = ext3_index;
2945 new_list_entry->artwork_index = artwork_index;
2948 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2951 struct FileInfo *file_list = artwork_info->file_list;
2952 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2953 char **base_prefixes = artwork_info->base_prefixes;
2954 char **ext1_suffixes = artwork_info->ext1_suffixes;
2955 char **ext2_suffixes = artwork_info->ext2_suffixes;
2956 char **ext3_suffixes = artwork_info->ext3_suffixes;
2957 char **ignore_tokens = artwork_info->ignore_tokens;
2958 int num_file_list_entries = artwork_info->num_file_list_entries;
2959 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2960 int num_base_prefixes = artwork_info->num_base_prefixes;
2961 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2962 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2963 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2964 int num_ignore_tokens = artwork_info->num_ignore_tokens;
2965 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
2966 SetupFileHash *extra_file_hash, *empty_file_hash;
2967 char *known_token_value = KNOWN_TOKEN_VALUE;
2968 char *base_token_value = UNDEFINED_FILENAME;
2971 if (filename == NULL)
2974 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2977 // separate valid (defined) from empty (undefined) config token values
2978 valid_file_hash = newSetupFileHash();
2979 empty_file_hash = newSetupFileHash();
2980 BEGIN_HASH_ITERATION(setup_file_hash, itr)
2982 char *value = HASH_ITERATION_VALUE(itr);
2984 setHashEntry(*value ? valid_file_hash : empty_file_hash,
2985 HASH_ITERATION_TOKEN(itr), value);
2987 END_HASH_ITERATION(setup_file_hash, itr)
2989 // at this point, we do not need the setup file hash anymore -- free it
2990 freeSetupFileHash(setup_file_hash);
2992 // prevent changing hash while iterating over it by using a temporary copy
2993 valid_file_hash_tmp = newSetupFileHash();
2994 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2996 setHashEntry(valid_file_hash_tmp,
2997 HASH_ITERATION_TOKEN(itr),
2998 HASH_ITERATION_VALUE(itr));
3000 END_HASH_ITERATION(valid_file_hash, itr)
3002 // (iterate over same temporary hash, as modifications are independent)
3004 // map deprecated to current tokens (using prefix match and replace)
3005 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3007 char *token = HASH_ITERATION_TOKEN(itr);
3008 char *mapped_token = get_mapped_token(token);
3010 if (mapped_token != NULL)
3012 char *value = HASH_ITERATION_VALUE(itr);
3015 setHashEntry(valid_file_hash, mapped_token, value);
3017 // ignore old token (by setting it to "known" keyword)
3018 setHashEntry(valid_file_hash, token, known_token_value);
3023 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3025 // add special base tokens (using prefix match and replace)
3026 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3028 char *token = HASH_ITERATION_TOKEN(itr);
3029 char *base_token = get_special_base_token(artwork_info, token);
3031 if (base_token != NULL)
3033 // add base token only if it does not already exist
3034 if (getHashEntry(valid_file_hash, base_token) == NULL)
3035 setHashEntry(valid_file_hash, base_token, base_token_value);
3040 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3042 // free temporary hash used for iteration
3043 freeSetupFileHash(valid_file_hash_tmp);
3045 // read parameters for all known config file tokens
3046 for (i = 0; i < num_file_list_entries; i++)
3047 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3049 // set all tokens that can be ignored here to "known" keyword
3050 for (i = 0; i < num_ignore_tokens; i++)
3051 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3053 // copy all unknown config file tokens to extra config hash
3054 extra_file_hash = newSetupFileHash();
3055 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3057 char *value = HASH_ITERATION_VALUE(itr);
3059 if (!strEqual(value, known_token_value))
3060 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3062 END_HASH_ITERATION(valid_file_hash, itr)
3064 // at this point, we do not need the valid file hash anymore -- free it
3065 freeSetupFileHash(valid_file_hash);
3067 // now try to determine valid, dynamically defined config tokens
3069 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3071 struct FileInfo **dynamic_file_list =
3072 &artwork_info->dynamic_file_list;
3073 int *num_dynamic_file_list_entries =
3074 &artwork_info->num_dynamic_file_list_entries;
3075 struct PropertyMapping **property_mapping =
3076 &artwork_info->property_mapping;
3077 int *num_property_mapping_entries =
3078 &artwork_info->num_property_mapping_entries;
3079 int current_summarized_file_list_entry =
3080 artwork_info->num_file_list_entries +
3081 artwork_info->num_dynamic_file_list_entries;
3082 char *token = HASH_ITERATION_TOKEN(itr);
3083 int len_token = strlen(token);
3085 boolean base_prefix_found = FALSE;
3086 boolean parameter_suffix_found = FALSE;
3088 // skip all parameter definitions (handled by read_token_parameters())
3089 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3091 int len_suffix = strlen(suffix_list[i].token);
3093 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3094 parameter_suffix_found = TRUE;
3097 if (parameter_suffix_found)
3100 // ---------- step 0: search for matching base prefix ----------
3103 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3105 char *base_prefix = base_prefixes[i];
3106 int len_base_prefix = strlen(base_prefix);
3107 boolean ext1_suffix_found = FALSE;
3108 boolean ext2_suffix_found = FALSE;
3109 boolean ext3_suffix_found = FALSE;
3110 boolean exact_match = FALSE;
3111 int base_index = -1;
3112 int ext1_index = -1;
3113 int ext2_index = -1;
3114 int ext3_index = -1;
3116 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3118 if (!base_prefix_found)
3123 if (start_pos + len_base_prefix == len_token) // exact match
3127 add_dynamic_file_list_entry(dynamic_file_list,
3128 num_dynamic_file_list_entries,
3131 num_suffix_list_entries,
3133 add_property_mapping(property_mapping,
3134 num_property_mapping_entries,
3135 base_index, -1, -1, -1,
3136 current_summarized_file_list_entry);
3140 // ---------- step 1: search for matching first suffix ----------
3142 start_pos += len_base_prefix;
3143 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3145 char *ext1_suffix = ext1_suffixes[j];
3146 int len_ext1_suffix = strlen(ext1_suffix);
3148 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3150 if (!ext1_suffix_found)
3155 if (start_pos + len_ext1_suffix == len_token) // exact match
3159 add_dynamic_file_list_entry(dynamic_file_list,
3160 num_dynamic_file_list_entries,
3163 num_suffix_list_entries,
3165 add_property_mapping(property_mapping,
3166 num_property_mapping_entries,
3167 base_index, ext1_index, -1, -1,
3168 current_summarized_file_list_entry);
3172 start_pos += len_ext1_suffix;
3178 // ---------- step 2: search for matching second suffix ----------
3180 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3182 char *ext2_suffix = ext2_suffixes[k];
3183 int len_ext2_suffix = strlen(ext2_suffix);
3185 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3187 if (!ext2_suffix_found)
3192 if (start_pos + len_ext2_suffix == len_token) // exact match
3196 add_dynamic_file_list_entry(dynamic_file_list,
3197 num_dynamic_file_list_entries,
3200 num_suffix_list_entries,
3202 add_property_mapping(property_mapping,
3203 num_property_mapping_entries,
3204 base_index, ext1_index, ext2_index, -1,
3205 current_summarized_file_list_entry);
3209 start_pos += len_ext2_suffix;
3215 // ---------- step 3: search for matching third suffix ----------
3217 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3219 char *ext3_suffix = ext3_suffixes[l];
3220 int len_ext3_suffix = strlen(ext3_suffix);
3222 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3224 if (!ext3_suffix_found)
3229 if (start_pos + len_ext3_suffix == len_token) // exact match
3233 add_dynamic_file_list_entry(dynamic_file_list,
3234 num_dynamic_file_list_entries,
3237 num_suffix_list_entries,
3239 add_property_mapping(property_mapping,
3240 num_property_mapping_entries,
3241 base_index, ext1_index, ext2_index, ext3_index,
3242 current_summarized_file_list_entry);
3248 END_HASH_ITERATION(extra_file_hash, itr)
3250 if (artwork_info->num_dynamic_file_list_entries > 0)
3252 artwork_info->dynamic_artwork_list =
3253 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3254 artwork_info->sizeof_artwork_list_entry);
3257 if (options.verbose && IS_PARENT_PROCESS())
3259 SetupFileList *setup_file_list, *list;
3260 boolean dynamic_tokens_found = FALSE;
3261 boolean unknown_tokens_found = FALSE;
3262 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3264 // list may be NULL for empty artwork config files
3265 setup_file_list = loadSetupFileList(filename);
3267 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3269 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3270 dynamic_tokens_found = TRUE;
3272 unknown_tokens_found = TRUE;
3274 END_HASH_ITERATION(extra_file_hash, itr)
3276 if (options.debug && dynamic_tokens_found)
3278 Error(ERR_INFO_LINE, "-");
3279 Error(ERR_INFO, "dynamic token(s) found in config file:");
3280 Error(ERR_INFO, "- config file: '%s'", filename);
3282 for (list = setup_file_list; list != NULL; list = list->next)
3284 char *value = getHashEntry(extra_file_hash, list->token);
3286 if (value != NULL && strEqual(value, known_token_value))
3287 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3290 Error(ERR_INFO_LINE, "-");
3293 if (unknown_tokens_found)
3295 Error(ERR_INFO_LINE, "-");
3296 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3297 Error(ERR_INFO, "- config file: '%s'", filename);
3299 for (list = setup_file_list; list != NULL; list = list->next)
3301 char *value = getHashEntry(extra_file_hash, list->token);
3303 if (value != NULL && !strEqual(value, known_token_value))
3304 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3307 Error(ERR_INFO_LINE, "-");
3310 if (undefined_values_found)
3312 Error(ERR_INFO_LINE, "-");
3313 Error(ERR_INFO, "warning: undefined values found in config file:");
3314 Error(ERR_INFO, "- config file: '%s'", filename);
3316 for (list = setup_file_list; list != NULL; list = list->next)
3318 char *value = getHashEntry(empty_file_hash, list->token);
3321 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3324 Error(ERR_INFO_LINE, "-");
3327 freeSetupFileList(setup_file_list);
3330 freeSetupFileHash(extra_file_hash);
3331 freeSetupFileHash(empty_file_hash);
3334 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3336 struct FileInfo *file_list = artwork_info->file_list;
3337 int num_file_list_entries = artwork_info->num_file_list_entries;
3338 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3339 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3342 DrawInitText("Loading artwork config", 120, FC_GREEN);
3343 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3345 // always start with reliable default values
3346 for (i = 0; i < num_file_list_entries; i++)
3348 setString(&file_list[i].filename, file_list[i].default_filename);
3350 for (j = 0; j < num_suffix_list_entries; j++)
3351 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3353 file_list[i].redefined = FALSE;
3354 file_list[i].fallback_to_default = FALSE;
3357 // free previous dynamic artwork file array
3358 if (artwork_info->dynamic_file_list != NULL)
3360 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3362 free(artwork_info->dynamic_file_list[i].token);
3363 free(artwork_info->dynamic_file_list[i].filename);
3364 free(artwork_info->dynamic_file_list[i].parameter);
3367 free(artwork_info->dynamic_file_list);
3368 artwork_info->dynamic_file_list = NULL;
3370 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3371 &artwork_info->num_dynamic_file_list_entries);
3374 // free previous property mapping
3375 if (artwork_info->property_mapping != NULL)
3377 free(artwork_info->property_mapping);
3379 artwork_info->property_mapping = NULL;
3380 artwork_info->num_property_mapping_entries = 0;
3383 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3385 // first look for special artwork configured in level series config
3386 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3388 if (fileExists(filename_base))
3389 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3392 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3394 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3395 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3398 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3399 struct ListNodeInfo **listnode)
3403 char *filename = (*listnode)->source_filename;
3405 if (--(*listnode)->num_references <= 0)
3406 deleteNodeFromList(&artwork_info->content_list, filename,
3407 artwork_info->free_artwork);
3413 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3414 struct ListNodeInfo **listnode,
3415 struct FileInfo *file_list_entry)
3425 char *basename = file_list_entry->filename;
3426 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3428 if (filename == NULL)
3430 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3432 basename = file_list_entry->default_filename;
3434 // fail for cloned default artwork that has no default filename defined
3435 if (file_list_entry->default_is_cloned &&
3436 strEqual(basename, UNDEFINED_FILENAME))
3438 int error_mode = ERR_WARN;
3440 // we can get away without sounds and music, but not without graphics
3441 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3442 error_mode = ERR_EXIT;
3444 Error(error_mode, "token '%s' was cloned and has no default filename",
3445 file_list_entry->token);
3450 // dynamic artwork has no default filename / skip empty default artwork
3451 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3454 file_list_entry->fallback_to_default = TRUE;
3456 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3458 filename = getCustomArtworkFilename(basename, artwork_info->type);
3460 if (filename == NULL)
3462 int error_mode = ERR_WARN;
3464 // we can get away without sounds and music, but not without graphics
3465 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3466 error_mode = ERR_EXIT;
3468 Error(error_mode, "cannot find default artwork file '%s'", basename);
3474 // check if the old and the new artwork file are the same
3475 if (*listnode && strEqual((*listnode)->source_filename, filename))
3477 // The old and new artwork are the same (have the same filename and path).
3478 // This usually means that this artwork does not exist in this artwork set
3479 // and a fallback to the existing artwork is done.
3484 // delete existing artwork file entry
3485 deleteArtworkListEntry(artwork_info, listnode);
3487 // check if the new artwork file already exists in the list of artwork
3488 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3490 *listnode = (struct ListNodeInfo *)node->content;
3491 (*listnode)->num_references++;
3496 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3497 DrawInitText(basename, 150, FC_YELLOW);
3499 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3501 // add new artwork file entry to the list of artwork files
3502 (*listnode)->num_references = 1;
3503 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3508 int error_mode = ERR_WARN;
3510 // we can get away without sounds and music, but not without graphics
3511 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3512 error_mode = ERR_EXIT;
3514 Error(error_mode, "cannot load artwork file '%s'", basename);
3520 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3521 struct ListNodeInfo **listnode,
3522 struct FileInfo *file_list_entry)
3524 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3526 deleteArtworkListEntry(artwork_info, listnode);
3531 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3534 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3536 struct FileInfo *file_list = artwork_info->file_list;
3537 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3538 int num_file_list_entries = artwork_info->num_file_list_entries;
3539 int num_dynamic_file_list_entries =
3540 artwork_info->num_dynamic_file_list_entries;
3543 print_timestamp_init("ReloadCustomArtworkList");
3545 for (i = 0; i < num_file_list_entries; i++)
3546 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3549 for (i = 0; i < num_dynamic_file_list_entries; i++)
3550 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3551 &dynamic_file_list[i]);
3553 print_timestamp_done("ReloadCustomArtworkList");
3556 dumpList(artwork_info->content_list);
3560 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3561 struct ListNodeInfo ***list,
3562 int *num_list_entries)
3569 for (i = 0; i < *num_list_entries; i++)
3570 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3574 *num_list_entries = 0;
3577 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3579 if (artwork_info == NULL)
3582 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3583 &artwork_info->num_file_list_entries);
3585 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3586 &artwork_info->num_dynamic_file_list_entries);
3590 // ----------------------------------------------------------------------------
3591 // functions only needed for non-Unix (non-command-line) systems
3592 // (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")
3593 // (now also added for Windows, to create files in user data directory)
3594 // ----------------------------------------------------------------------------
3596 char *getLogFilename(char *basename)
3598 return getPath2(getUserGameDataDir(), basename);
3601 void OpenLogFiles(void)
3605 InitUserDataDirectory();
3607 for (i = 0; i < NUM_LOGS; i++)
3609 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3612 program.log_file[i] = program.log_file_default[i]; // reset to default
3614 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3615 program.log_filename[i], strerror(errno));
3618 // output should be unbuffered so it is not truncated in a crash
3619 setbuf(program.log_file[i], NULL);
3623 void CloseLogFiles(void)
3627 for (i = 0; i < NUM_LOGS; i++)
3628 if (program.log_file[i] != program.log_file_default[i])
3629 fclose(program.log_file[i]);
3632 void DumpLogFile(int nr)
3634 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3636 if (log_file == NULL)
3639 while (!feof(log_file))
3640 fputc(fgetc(log_file), stdout);
3645 void NotifyUserAboutErrorFile(void)
3647 #if defined(PLATFORM_WIN32)
3648 char *title_text = getStringCat2(program.program_title, " Error Message");
3649 char *error_text = getStringCat2("The program was aborted due to an error; "
3650 "for details, see the following error file:"
3652 program.log_filename[LOG_ERR_ID]);
3654 MessageBox(NULL, error_text, title_text, MB_OK);
3659 // ----------------------------------------------------------------------------
3660 // the following is only for debugging purpose and normally not used
3661 // ----------------------------------------------------------------------------
3665 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3666 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3668 #define DEBUG_NUM_TIMESTAMPS 10
3669 #define DEBUG_TIME_IN_MICROSECONDS 0
3671 #if DEBUG_TIME_IN_MICROSECONDS
3672 static double Counter_Microseconds(void)
3674 static struct timeval base_time = { 0, 0 };
3675 struct timeval current_time;
3678 gettimeofday(¤t_time, NULL);
3680 // reset base time in case of wrap-around
3681 if (current_time.tv_sec < base_time.tv_sec)
3682 base_time = current_time;
3685 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3686 ((double)(current_time.tv_usec - base_time.tv_usec));
3688 return counter; // return microseconds since last init
3692 static char *debug_print_timestamp_get_padding(int padding_size)
3694 static char *padding = NULL;
3695 int max_padding_size = 100;
3697 if (padding == NULL)
3699 padding = checked_calloc(max_padding_size + 1);
3700 memset(padding, ' ', max_padding_size);
3703 return &padding[MAX(0, max_padding_size - padding_size)];
3706 void debug_print_timestamp(int counter_nr, char *message)
3708 int indent_size = 8;
3709 int padding_size = 40;
3710 float timestamp_interval;
3713 Error(ERR_EXIT, "debugging: invalid negative counter");
3714 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3715 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3717 #if DEBUG_TIME_IN_MICROSECONDS
3718 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3721 counter[counter_nr][0] = Counter_Microseconds();
3723 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3726 counter[counter_nr][0] = Counter();
3729 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3730 counter[counter_nr][1] = counter[counter_nr][0];
3733 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3734 debug_print_timestamp_get_padding(counter_nr * indent_size),
3736 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3737 timestamp_interval / 1000,
3742 static void debug_print_parent_only(char *format, ...)
3744 if (!IS_PARENT_PROCESS())
3751 va_start(ap, format);
3752 vprintf(format, ap);
3762 static void print_timestamp_ext(char *message, char *mode)
3764 #if DEBUG_PRINT_INIT_TIMESTAMPS
3765 static char *debug_message = NULL;
3766 static char *last_message = NULL;
3767 static int counter_nr = 0;
3768 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3770 checked_free(debug_message);
3771 debug_message = getStringCat3(mode, " ", message);
3773 if (strEqual(mode, "INIT"))
3775 debug_print_timestamp(counter_nr, NULL);
3777 if (counter_nr + 1 < max_depth)
3778 debug_print_timestamp(counter_nr, debug_message);
3782 debug_print_timestamp(counter_nr, NULL);
3784 else if (strEqual(mode, "DONE"))
3788 if (counter_nr + 1 < max_depth ||
3789 (counter_nr == 0 && max_depth == 1))
3791 last_message = message;
3793 if (counter_nr == 0 && max_depth == 1)
3795 checked_free(debug_message);
3796 debug_message = getStringCat3("TIME", " ", message);
3799 debug_print_timestamp(counter_nr, debug_message);
3802 else if (!strEqual(mode, "TIME") ||
3803 !strEqual(message, last_message))
3805 if (counter_nr < max_depth)
3806 debug_print_timestamp(counter_nr, debug_message);
3811 void print_timestamp_init(char *message)
3813 print_timestamp_ext(message, "INIT");
3816 void print_timestamp_time(char *message)
3818 print_timestamp_ext(message, "TIME");
3821 void print_timestamp_done(char *message)
3823 print_timestamp_ext(message, "DONE");