1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
14 #include <sys/types.h>
24 #if defined(PLATFORM_UNIX)
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 // ----------------------------------------------------------------------------
255 // generic logging and error handling functions
256 // ----------------------------------------------------------------------------
268 static char *log_tokens[] =
278 static void printf_log_prefix(int log_level, char *mode)
280 if (log_level < 0 || log_level > LOG_FATAL)
283 char *log_token = log_tokens[log_level];
285 if (log_level == LOG_DEBUG)
286 printf_log_nonewline("[%s] [%s] ", log_token, mode);
288 printf_log_nonewline("[%s] ", log_token);
291 static void vLog(int log_level, char *mode, char *format, va_list ap)
293 if (log_level < 0 || log_level > LOG_FATAL)
296 if (log_level == LOG_DEBUG)
298 // only show debug messages when in debug mode
302 // if optional debug mode specified, limit debug output accordingly
303 if (options.debug_mode != NULL &&
304 strstr(mode, options.debug_mode) == NULL)
307 else if (log_level == LOG_WARN)
309 // only show warning messages when in verbose mode
310 if (!options.verbose)
314 #if defined(PLATFORM_ANDROID)
315 android_log_prio = (log_level == LOG_DEBUG ? ANDROID_LOG_DEBUG :
316 log_level == LOG_INFO ? ANDROID_LOG_INFO :
317 log_level == LOG_WARN ? ANDROID_LOG_WARN :
318 log_level == LOG_ERROR ? ANDROID_LOG_ERROR :
319 log_level == LOG_FATAL ? ANDROID_LOG_FATAL :
320 ANDROID_LOG_UNKNOWN);
323 static boolean last_line_was_separator = FALSE;
324 char *log_token = log_tokens[log_level];
326 if (strEqual(format, "===") ||
327 strEqual(format, "---"))
329 static char *mode_last = NULL;
330 char line_char[2] = { format[0], '\0' };
331 int line_length = 80 - strlen(log_token) - 3;
333 if (log_level == LOG_DEBUG)
334 line_length -= strlen(mode) + 3;
336 if (last_line_was_separator && strEqual(mode, mode_last))
339 printf_log_prefix(log_level, mode);
340 printf_log_line(line_char, line_length);
342 if (!strEqual(mode, mode_last))
343 setString(&mode_last, mode);
345 last_line_was_separator = TRUE;
350 last_line_was_separator = FALSE;
352 printf_log_prefix(log_level, mode);
354 vprintf_log(format, ap);
357 static void Log(int log_level, char *mode, char *format, ...)
361 va_start(ap, format);
362 vLog(log_level, mode, format, ap);
366 void DebugContinued(char *mode, char *format, ...)
368 static char message[MAX_LINE_LEN] = { 0 };
370 // initialize message (optional)
371 if (strEqual(format, ""))
378 char *message_ptr = message + strlen(message);
379 int size_left = MAX_LINE_LEN - strlen(message);
383 va_start(ap, format);
384 vsnprintf(message_ptr, size_left, format, ap);
388 if (strSuffix(format, "\n"))
390 message[strlen(message) - 1] = '\0';
392 Debug(mode, message);
398 void Debug(char *mode, char *format, ...)
402 va_start(ap, format);
403 vLog(LOG_DEBUG, mode, format, ap);
407 void Info(char *format, ...)
411 va_start(ap, format);
412 vLog(LOG_INFO, NULL, format, ap);
416 void Warn(char *format, ...)
420 va_start(ap, format);
421 vLog(LOG_WARN, NULL, format, ap);
425 void Error(char *format, ...)
429 va_start(ap, format);
430 vLog(LOG_ERROR, NULL, format, ap);
434 void Fail(char *format, ...)
438 va_start(ap, format);
439 vLog(LOG_FATAL, NULL, format, ap);
442 if (!network.is_server_thread)
444 va_start(ap, format);
445 program.exit_message_function(format, ap);
449 Log(LOG_FATAL, NULL, "aborting");
451 // network server thread: normal exit
452 if (network.is_server_thread)
455 // main process: clean up stuff
456 program.exit_function(1);
459 void FailWithHelp(char *format, ...)
463 va_start(ap, format);
464 vLog(LOG_FATAL, NULL, format, ap);
467 Log(LOG_FATAL, NULL, "try option '--help' for more information");
468 Log(LOG_FATAL, NULL, "aborting");
470 // main process: clean up stuff
471 program.exit_function(1);
475 // ----------------------------------------------------------------------------
477 // ----------------------------------------------------------------------------
479 /* int2str() returns a number converted to a string;
480 the used memory is static, but will be overwritten by later calls,
481 so if you want to save the result, copy it to a private string buffer;
482 there can be 10 local calls of int2str() without buffering the result --
483 the 11th call will then destroy the result from the first call and so on. */
485 char *int2str(int number, int size)
487 static char shift_array[10][40];
488 static int shift_counter = 0;
489 char *s = shift_array[shift_counter];
491 shift_counter = (shift_counter + 1) % 10;
498 sprintf(s, " %09d", number);
499 return &s[strlen(s) - size];
503 sprintf(s, "%d", number);
509 // something similar to "int2str()" above, but allocates its own memory
510 // and has a different interface; we cannot use "itoa()", because this
511 // seems to be already defined when cross-compiling to the win32 target
513 char *i_to_a(unsigned int i)
515 static char *a = NULL;
519 if (i > 2147483647) // yes, this is a kludge
522 a = checked_malloc(10 + 1);
530 // calculate base-2 logarithm of argument (rounded down to integer;
531 // this function returns the number of the highest bit set in argument)
533 int log_2(unsigned int x)
539 x -= (1 << e); // for rounding down (rounding up: remove this line)
546 boolean getTokenValueFromString(char *string, char **token, char **value)
548 return getTokenValueFromSetupLine(string, token, value);
552 // ----------------------------------------------------------------------------
554 // ----------------------------------------------------------------------------
556 // maximal allowed length of a command line option
557 #define MAX_OPTION_LEN 256
559 static unsigned int getCurrentMS(void)
561 return SDL_GetTicks();
564 static unsigned int mainCounter(int mode)
566 static unsigned int base_ms = 0;
567 unsigned int current_ms;
569 // get current system milliseconds
570 current_ms = getCurrentMS();
572 // reset base timestamp in case of counter reset or wrap-around
573 if (mode == INIT_COUNTER || current_ms < base_ms)
574 base_ms = current_ms;
576 // return milliseconds since last counter reset
577 return current_ms - base_ms;
580 void InitCounter() // set counter back to zero
582 mainCounter(INIT_COUNTER);
585 unsigned int Counter() // get milliseconds since last call of InitCounter()
587 return mainCounter(READ_COUNTER);
590 static void sleep_milliseconds(unsigned int milliseconds_delay)
592 SDL_Delay(milliseconds_delay);
595 void Delay(unsigned int delay) // Sleep specified number of milliseconds
597 sleep_milliseconds(delay);
600 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
601 unsigned int actual_counter)
603 if (actual_counter >= *counter_var &&
604 actual_counter < *counter_var + delay)
607 *counter_var = actual_counter;
612 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
614 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
617 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
619 return DelayReachedExt(counter_var, delay, Counter());
622 void ResetDelayCounterExt(unsigned int *counter_var,
623 unsigned int actual_counter)
625 DelayReachedExt(counter_var, 0, actual_counter);
628 void ResetFrameCounter(unsigned int *frame_counter_var)
630 FrameReached(frame_counter_var, 0);
633 void ResetDelayCounter(unsigned int *counter_var)
635 DelayReached(counter_var, 0);
638 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
640 unsigned int actual_counter;
645 actual_counter = Counter();
647 if (actual_counter >= *counter_var &&
648 actual_counter < *counter_var + delay)
649 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
654 if (*counter_var != 0 &&
656 actual_counter >= *counter_var + delay)
658 int lag = actual_counter - (*counter_var + delay);
659 int delay2 = (delay + 1) / 2;
662 skip_frames = (lag + delay2) / delay;
665 *counter_var = actual_counter;
670 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
671 int *loop_var, int last_loop_value)
673 int skip_frames = WaitUntilDelayReached(counter_var, delay);
678 Debug("internal:SkipUntilDelayReached",
679 "%d: %d ms -> SKIP %d FRAME(S) [%d ms]",
681 skip_frames, skip_frames * delay);
683 Debug("internal:SkipUntilDelayReached",
689 if (skip_frames == 0)
692 // when skipping frames, make sure to never skip the last frame, as
693 // this may be needed for animations to reach a defined end state;
694 // furthermore, we assume that this function is called at the end
695 // of a "for" loop, which continues by incrementing the loop variable
696 // by one before checking the loop condition again; therefore we have
697 // to check against the last loop value minus one here
701 if (*loop_var < last_loop_value) // never skip the last frame
703 *loop_var += skip_frames;
705 if (*loop_var > last_loop_value) // never skip the last frame
706 *loop_var = last_loop_value;
711 // ----------------------------------------------------------------------------
712 // random generator functions
713 // ----------------------------------------------------------------------------
715 unsigned int init_random_number(int nr, int seed)
717 if (seed == NEW_RANDOMIZE)
719 // default random seed
720 seed = (int)time(NULL); // seconds since the epoch
722 #if !defined(PLATFORM_WIN32)
723 // add some more randomness
724 struct timeval current_time;
726 gettimeofday(¤t_time, NULL);
728 seed += (int)current_time.tv_usec; // microseconds since the epoch
731 // add some more randomness
732 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
734 // add some more randomness
735 seed += GetSimpleRandom(1000000);
738 srandom_linux_libc(nr, (unsigned int) seed);
740 return (unsigned int) seed;
743 unsigned int get_random_number(int nr, int max)
745 return (max > 0 ? random_linux_libc(nr) % max : 0);
749 // ----------------------------------------------------------------------------
750 // system info functions
751 // ----------------------------------------------------------------------------
753 #if !defined(PLATFORM_ANDROID)
754 static char *get_corrected_real_name(char *real_name)
756 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
757 char *from_ptr = real_name;
758 char *to_ptr = real_name_new;
760 // copy the name string, but not more than MAX_USERNAME_LEN characters
761 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
763 // the name field read from "passwd" file may also contain additional
764 // user information, separated by commas, which will be removed here
765 if (*from_ptr == ',')
768 // the user's real name may contain 'german sharp s' characters,
769 // which have no equivalent in upper case letters (used by our fonts)
770 if (*from_ptr == CHAR_BYTE_SHARP_S)
777 *to_ptr++ = *from_ptr++;
782 return real_name_new;
786 #if defined(PLATFORM_UNIX)
787 static struct passwd *getPasswdEntry(void)
789 #if defined(PLATFORM_EMSCRIPTEN)
790 // currently not fully supported; force fallback to default values
793 return getpwuid(getuid());
797 char *getUnixLoginName(void)
799 struct passwd *pwd = getPasswdEntry();
801 if (pwd != NULL && strlen(pwd->pw_name) != 0)
807 char *getUnixRealName(void)
809 struct passwd *pwd = getPasswdEntry();
811 if (pwd != NULL && strlen(pwd->pw_gecos) != 0)
812 return pwd->pw_gecos;
817 char *getUnixHomeDir(void)
819 struct passwd *pwd = getPasswdEntry();
821 if (pwd != NULL && strlen(pwd->pw_dir) != 0)
828 char *getLoginName(void)
830 static char *login_name = NULL;
832 #if defined(PLATFORM_WIN32)
833 if (login_name == NULL)
835 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
837 login_name = checked_malloc(buffer_size);
839 if (GetUserName(login_name, &buffer_size) == 0)
840 strcpy(login_name, ANONYMOUS_NAME);
842 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
843 if (login_name == NULL)
845 char *name = getUnixLoginName();
848 login_name = getStringCopy(name);
850 login_name = ANONYMOUS_NAME;
853 login_name = ANONYMOUS_NAME;
859 char *getRealName(void)
861 static char *real_name = NULL;
863 #if defined(PLATFORM_WIN32)
864 if (real_name == NULL)
866 static char buffer[MAX_USERNAME_LEN + 1];
867 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
869 if (GetUserName(buffer, &buffer_size) != 0)
870 real_name = get_corrected_real_name(buffer);
872 real_name = ANONYMOUS_NAME;
874 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
875 if (real_name == NULL)
877 char *name = getUnixRealName();
880 real_name = get_corrected_real_name(name);
882 real_name = ANONYMOUS_NAME;
885 real_name = ANONYMOUS_NAME;
891 time_t getFileTimestampEpochSeconds(char *filename)
893 struct stat file_status;
895 if (stat(filename, &file_status) != 0) // cannot stat file
898 return file_status.st_mtime;
902 // ----------------------------------------------------------------------------
903 // path manipulation functions
904 // ----------------------------------------------------------------------------
906 static char *getLastPathSeparatorPtr(char *filename)
908 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
910 if (last_separator == NULL) // also try DOS/Windows variant
911 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
913 return last_separator;
916 char *getBaseNamePtr(char *filename)
918 char *last_separator = getLastPathSeparatorPtr(filename);
920 if (last_separator != NULL)
921 return last_separator + 1; // separator found: strip base path
923 return filename; // no separator found: filename has no path
926 char *getBaseName(char *filename)
928 return getStringCopy(getBaseNamePtr(filename));
931 char *getBaseNameNoSuffix(char *filename)
933 char *basename = getStringCopy(getBaseNamePtr(filename));
935 // remove trailing suffix (separated by dot or hyphen)
936 if (basename[0] != '.' && basename[0] != '-')
938 if (strchr(basename, '.') != NULL)
939 *strchr(basename, '.') = '\0';
941 if (strchr(basename, '-') != NULL)
942 *strchr(basename, '-') = '\0';
948 char *getBasePath(char *filename)
950 char *basepath = getStringCopy(filename);
951 char *last_separator = getLastPathSeparatorPtr(basepath);
953 // if no separator was found, use current directory
954 if (last_separator == NULL)
958 return getStringCopy(".");
961 // separator found: strip basename
962 *last_separator = '\0';
968 // ----------------------------------------------------------------------------
969 // various string functions
970 // ----------------------------------------------------------------------------
972 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
974 if (s1 == NULL || s2 == NULL || sep == NULL)
977 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
980 sprintf(complete_string, "%s%s%s", s1, sep, s2);
982 return complete_string;
985 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
987 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
990 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
991 strlen(s2) + strlen(sep) +
994 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
996 return complete_string;
999 char *getStringCat2(char *s1, char *s2)
1001 return getStringCat2WithSeparator(s1, s2, "");
1004 char *getStringCat3(char *s1, char *s2, char *s3)
1006 return getStringCat3WithSeparator(s1, s2, s3, "");
1009 char *getPath2(char *path1, char *path2)
1011 #if defined(PLATFORM_ANDROID)
1012 // workaround for reading from assets directory -- skip "." subdirs in path
1013 if (strEqual(path1, "."))
1014 return getStringCopy(path2);
1015 else if (strEqual(path2, "."))
1016 return getStringCopy(path1);
1019 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1022 char *getPath3(char *path1, char *path2, char *path3)
1024 #if defined(PLATFORM_ANDROID)
1025 // workaround for reading from assets directory -- skip "." subdirs in path
1026 if (strEqual(path1, "."))
1027 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
1028 else if (strEqual(path2, "."))
1029 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
1030 else if (strEqual(path3, "."))
1031 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1034 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
1037 static char *getPngOrPcxIfNotExists(char *filename)
1039 // switch from PNG to PCX file and vice versa, if file does not exist
1040 // (backwards compatibility with PCX files used in previous versions)
1042 if (!fileExists(filename) && strSuffix(filename, ".png"))
1043 strcpy(&filename[strlen(filename) - 3], "pcx");
1044 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
1045 strcpy(&filename[strlen(filename) - 3], "png");
1050 char *getImg2(char *path1, char *path2)
1052 return getPngOrPcxIfNotExists(getPath2(path1, path2));
1055 char *getImg3(char *path1, char *path2, char *path3)
1057 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
1060 char *getStringCopy(const char *s)
1067 s_copy = checked_malloc(strlen(s) + 1);
1073 char *getStringCopyN(const char *s, int n)
1076 int s_len = MAX(0, n);
1081 s_copy = checked_malloc(s_len + 1);
1082 strncpy(s_copy, s, s_len);
1083 s_copy[s_len] = '\0';
1088 char *getStringCopyNStatic(const char *s, int n)
1090 static char *s_copy = NULL;
1092 checked_free(s_copy);
1094 s_copy = getStringCopyN(s, n);
1099 char *getStringToLower(const char *s)
1101 char *s_copy = checked_malloc(strlen(s) + 1);
1102 char *s_ptr = s_copy;
1105 *s_ptr++ = tolower(*s++);
1111 void setString(char **old_value, char *new_value)
1113 checked_free(*old_value);
1115 *old_value = getStringCopy(new_value);
1118 boolean strEqual(char *s1, char *s2)
1120 return (s1 == NULL && s2 == NULL ? TRUE :
1121 s1 == NULL && s2 != NULL ? FALSE :
1122 s1 != NULL && s2 == NULL ? FALSE :
1123 strcmp(s1, s2) == 0);
1126 boolean strEqualN(char *s1, char *s2, int n)
1128 return (s1 == NULL && s2 == NULL ? TRUE :
1129 s1 == NULL && s2 != NULL ? FALSE :
1130 s1 != NULL && s2 == NULL ? FALSE :
1131 strncmp(s1, s2, n) == 0);
1134 boolean strPrefix(char *s, char *prefix)
1136 return (s == NULL && prefix == NULL ? TRUE :
1137 s == NULL && prefix != NULL ? FALSE :
1138 s != NULL && prefix == NULL ? FALSE :
1139 strncmp(s, prefix, strlen(prefix)) == 0);
1142 boolean strSuffix(char *s, char *suffix)
1144 return (s == NULL && suffix == NULL ? TRUE :
1145 s == NULL && suffix != NULL ? FALSE :
1146 s != NULL && suffix == NULL ? FALSE :
1147 strlen(s) < strlen(suffix) ? FALSE :
1148 strcmp(&s[strlen(s) - strlen(suffix)], suffix) == 0);
1151 boolean strPrefixLower(char *s, char *prefix)
1153 char *s_lower = getStringToLower(s);
1154 boolean match = strPrefix(s_lower, prefix);
1161 boolean strSuffixLower(char *s, char *suffix)
1163 char *s_lower = getStringToLower(s);
1164 boolean match = strSuffix(s_lower, suffix);
1172 // ----------------------------------------------------------------------------
1173 // command line option handling functions
1174 // ----------------------------------------------------------------------------
1176 void GetOptions(int argc, char *argv[],
1177 void (*print_usage_function)(void),
1178 void (*print_version_function)(void))
1180 char *ro_base_path = getProgramMainDataPath(argv[0], RO_BASE_PATH);
1181 char *rw_base_path = getProgramMainDataPath(argv[0], RW_BASE_PATH);
1182 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
1183 char **options_left = &argvplus[1];
1185 // replace original "argv" with null-terminated array of string pointers
1187 argvplus[argc] = argv[argc];
1189 // initialize global program options
1190 options.server_host = NULL;
1191 options.server_port = 0;
1193 options.ro_base_directory = ro_base_path;
1194 options.rw_base_directory = rw_base_path;
1195 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1196 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1197 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1198 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1199 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1200 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
1202 options.execute_command = NULL;
1203 options.special_flags = NULL;
1204 options.debug_mode = NULL;
1206 options.mytapes = FALSE;
1207 options.serveronly = FALSE;
1208 options.network = FALSE;
1209 options.verbose = FALSE;
1210 options.debug = FALSE;
1213 options.verbose = TRUE;
1215 #if !defined(PLATFORM_UNIX)
1216 if (*options_left == NULL) // no options given -- enable verbose mode
1217 options.verbose = TRUE;
1222 #if defined(PLATFORM_ANDROID)
1223 options.debug = TRUE;
1227 while (*options_left)
1229 char option_str[MAX_OPTION_LEN];
1230 char *option = options_left[0];
1231 char *next_option = options_left[1];
1232 char *option_arg = NULL;
1233 int option_len = strlen(option);
1235 if (option_len >= MAX_OPTION_LEN)
1236 FailWithHelp("unrecognized option '%s'", option);
1238 strcpy(option_str, option); // copy argument into buffer
1239 option = option_str;
1241 if (strEqual(option, "--")) // stop scanning arguments
1244 if (strPrefix(option, "--")) // treat '--' like '-'
1247 option_arg = strchr(option, '=');
1248 if (option_arg == NULL) // no '=' in option
1249 option_arg = next_option;
1252 *option_arg++ = '\0'; // cut argument from option
1253 if (*option_arg == '\0') // no argument after '='
1254 FailWithHelp("option '%s' has invalid argument", option_str);
1257 option_len = strlen(option);
1259 if (strEqual(option, "-"))
1261 FailWithHelp("unrecognized option '%s'", option);
1263 else if (strncmp(option, "-help", option_len) == 0)
1265 print_usage_function();
1269 else if (strncmp(option, "-basepath", option_len) == 0)
1271 if (option_arg == NULL)
1272 FailWithHelp("option '%s' requires an argument", option_str);
1274 // this should be extended to separate options for ro and rw data
1275 options.ro_base_directory = ro_base_path = getStringCopy(option_arg);
1276 options.rw_base_directory = rw_base_path = getStringCopy(option_arg);
1277 if (option_arg == next_option)
1280 // adjust paths for sub-directories in base directory accordingly
1281 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1282 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1283 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1284 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1285 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1286 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
1288 else if (strncmp(option, "-levels", option_len) == 0)
1290 if (option_arg == NULL)
1291 FailWithHelp("option '%s' requires an argument", option_str);
1293 options.level_directory = getStringCopy(option_arg);
1294 if (option_arg == next_option)
1297 else if (strncmp(option, "-graphics", option_len) == 0)
1299 if (option_arg == NULL)
1300 FailWithHelp("option '%s' requires an argument", option_str);
1302 options.graphics_directory = getStringCopy(option_arg);
1303 if (option_arg == next_option)
1306 else if (strncmp(option, "-sounds", option_len) == 0)
1308 if (option_arg == NULL)
1309 FailWithHelp("option '%s' requires an argument", option_str);
1311 options.sounds_directory = getStringCopy(option_arg);
1312 if (option_arg == next_option)
1315 else if (strncmp(option, "-music", option_len) == 0)
1317 if (option_arg == NULL)
1318 FailWithHelp("option '%s' requires an argument", option_str);
1320 options.music_directory = getStringCopy(option_arg);
1321 if (option_arg == next_option)
1324 else if (strncmp(option, "-mytapes", option_len) == 0)
1326 options.mytapes = TRUE;
1328 else if (strncmp(option, "-network", option_len) == 0)
1330 options.network = TRUE;
1332 else if (strncmp(option, "-serveronly", option_len) == 0)
1334 options.serveronly = TRUE;
1336 else if (strncmp(option, "-debug", option_len) == 0)
1338 options.debug = TRUE;
1340 // optionally, debug output can be limited to a specific debug mode
1341 if (option_arg != next_option)
1342 options.debug_mode = getStringCopy(option_arg);
1344 else if (strncmp(option, "-verbose", option_len) == 0)
1346 options.verbose = TRUE;
1348 else if (strncmp(option, "-version", option_len) == 0 ||
1349 strncmp(option, "-V", option_len) == 0)
1351 print_version_function();
1355 else if (strPrefix(option, "-D"))
1357 options.special_flags = getStringCopy(&option[2]);
1359 else if (strncmp(option, "-execute", option_len) == 0)
1361 if (option_arg == NULL)
1362 FailWithHelp("option '%s' requires an argument", option_str);
1364 options.execute_command = getStringCopy(option_arg);
1365 if (option_arg == next_option)
1368 // when doing batch processing, always enable verbose mode (warnings)
1369 options.verbose = TRUE;
1371 #if defined(PLATFORM_MACOSX)
1372 else if (strPrefix(option, "-psn"))
1374 // ignore process serial number when launched via GUI on Mac OS X
1377 else if (*option == '-')
1379 FailWithHelp("unrecognized option '%s'", option_str);
1381 else if (options.server_host == NULL)
1383 options.server_host = *options_left;
1385 else if (options.server_port == 0)
1387 options.server_port = atoi(*options_left);
1388 if (options.server_port < 1024)
1389 FailWithHelp("bad port number '%d'", options.server_port);
1392 FailWithHelp("too many arguments");
1399 // ----------------------------------------------------------------------------
1400 // checked memory allocation and freeing functions
1401 // ----------------------------------------------------------------------------
1403 void *checked_malloc(unsigned int size)
1410 Fail("cannot allocate %d bytes -- out of memory", size);
1415 void *checked_calloc(unsigned int size)
1419 ptr = calloc(1, size);
1422 Fail("cannot allocate %d bytes -- out of memory", size);
1427 void *checked_realloc(void *ptr, unsigned int size)
1429 ptr = realloc(ptr, size);
1432 Fail("cannot allocate %d bytes -- out of memory", size);
1437 void checked_free(void *ptr)
1439 if (ptr != NULL) // this check should be done by free() anyway
1443 void clear_mem(void *ptr, unsigned int size)
1445 #if defined(PLATFORM_WIN32)
1446 // for unknown reason, memset() sometimes crashes when compiled with MinGW
1447 char *cptr = (char *)ptr;
1452 memset(ptr, 0, size);
1457 // ----------------------------------------------------------------------------
1458 // various helper functions
1459 // ----------------------------------------------------------------------------
1461 void swap_numbers(int *i1, int *i2)
1469 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1481 /* the "put" variants of the following file access functions check for the file
1482 pointer being != NULL and return the number of bytes they have or would have
1483 written; this allows for chunk writing functions to first determine the size
1484 of the (not yet written) chunk, write the correct chunk size and finally
1485 write the chunk itself */
1487 int getFile8BitInteger(File *file)
1489 return getByteFromFile(file);
1492 int putFile8BitInteger(FILE *file, int value)
1500 int getFile16BitInteger(File *file, int byte_order)
1502 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1503 return ((getByteFromFile(file) << 8) |
1504 (getByteFromFile(file) << 0));
1505 else // BYTE_ORDER_LITTLE_ENDIAN
1506 return ((getByteFromFile(file) << 0) |
1507 (getByteFromFile(file) << 8));
1510 int putFile16BitInteger(FILE *file, int value, int byte_order)
1514 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1516 fputc((value >> 8) & 0xff, file);
1517 fputc((value >> 0) & 0xff, file);
1519 else // BYTE_ORDER_LITTLE_ENDIAN
1521 fputc((value >> 0) & 0xff, file);
1522 fputc((value >> 8) & 0xff, file);
1529 int getFile32BitInteger(File *file, int byte_order)
1531 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1532 return ((getByteFromFile(file) << 24) |
1533 (getByteFromFile(file) << 16) |
1534 (getByteFromFile(file) << 8) |
1535 (getByteFromFile(file) << 0));
1536 else // BYTE_ORDER_LITTLE_ENDIAN
1537 return ((getByteFromFile(file) << 0) |
1538 (getByteFromFile(file) << 8) |
1539 (getByteFromFile(file) << 16) |
1540 (getByteFromFile(file) << 24));
1543 int putFile32BitInteger(FILE *file, int value, int byte_order)
1547 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1549 fputc((value >> 24) & 0xff, file);
1550 fputc((value >> 16) & 0xff, file);
1551 fputc((value >> 8) & 0xff, file);
1552 fputc((value >> 0) & 0xff, file);
1554 else // BYTE_ORDER_LITTLE_ENDIAN
1556 fputc((value >> 0) & 0xff, file);
1557 fputc((value >> 8) & 0xff, file);
1558 fputc((value >> 16) & 0xff, file);
1559 fputc((value >> 24) & 0xff, file);
1566 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1569 const int chunk_name_length = 4;
1572 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1575 if (chunk_size != NULL)
1578 *chunk_size = getFile32BitInteger(file, byte_order);
1581 return (checkEndOfFile(file) ? FALSE : TRUE);
1584 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1591 fputs(chunk_name, file);
1593 num_bytes += strlen(chunk_name);
1595 if (chunk_size >= 0)
1599 putFile32BitInteger(file, chunk_size, byte_order);
1607 int getFileVersion(File *file)
1609 int version_super = getByteFromFile(file);
1610 int version_major = getByteFromFile(file);
1611 int version_minor = getByteFromFile(file);
1612 int version_patch = getByteFromFile(file);
1614 return VERSION_IDENT(version_super, version_major, version_minor,
1618 int putFileVersion(FILE *file, int version)
1622 int version_super = VERSION_SUPER(version);
1623 int version_major = VERSION_MAJOR(version);
1624 int version_minor = VERSION_MINOR(version);
1625 int version_patch = VERSION_PATCH(version);
1627 fputc(version_super, file);
1628 fputc(version_major, file);
1629 fputc(version_minor, file);
1630 fputc(version_patch, file);
1636 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1640 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1641 buffer[i] = getByteFromFile(file);
1644 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1648 for (i = 0; i < bytes; i++)
1649 fputc(buffer[i], file);
1652 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1654 while (bytes-- && !checkEndOfFile(file))
1655 getByteFromFile(file);
1658 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1665 // ----------------------------------------------------------------------------
1666 // functions to translate key identifiers between different format
1667 // ----------------------------------------------------------------------------
1669 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1670 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1671 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1672 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1674 static void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1683 // return and escape keys
1684 { KSYM_Return, "XK_Return", "return" },
1685 { KSYM_Escape, "XK_Escape", "escape" },
1687 // normal cursor keys
1688 { KSYM_Left, "XK_Left", "cursor left" },
1689 { KSYM_Right, "XK_Right", "cursor right" },
1690 { KSYM_Up, "XK_Up", "cursor up" },
1691 { KSYM_Down, "XK_Down", "cursor down" },
1693 // keypad cursor keys
1695 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1696 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1697 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1698 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1701 // other keypad keys
1702 #ifdef KSYM_KP_Enter
1703 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1704 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1705 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1706 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1707 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1708 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1712 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1713 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1714 { KSYM_Control_L, "XK_Control_L", "left control" },
1715 { KSYM_Control_R, "XK_Control_R", "right control" },
1716 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1717 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1718 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1719 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1720 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, // Alt-R
1721 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, // Ctrl-R
1723 // some special keys
1724 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1725 { KSYM_Delete, "XK_Delete", "delete" },
1726 { KSYM_Insert, "XK_Insert", "insert" },
1727 { KSYM_Tab, "XK_Tab", "tab" },
1728 { KSYM_Home, "XK_Home", "home" },
1729 { KSYM_End, "XK_End", "end" },
1730 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1731 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1733 { KSYM_Select, "XK_Select", "select" },
1734 { KSYM_Menu, "XK_Menu", "menu" }, // menu key
1735 { KSYM_Back, "XK_Back", "back" }, // back key
1736 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
1737 #if defined(PLATFORM_ANDROID)
1738 { KSYM_Rewind, "XK_Rewind", "rewind" },
1739 { KSYM_FastForward, "XK_FastForward", "fast forward" },
1742 // ASCII 0x20 to 0x40 keys (except numbers)
1743 { KSYM_space, "XK_space", "space" },
1744 { KSYM_exclam, "XK_exclam", "!" },
1745 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1746 { KSYM_numbersign, "XK_numbersign", "#" },
1747 { KSYM_dollar, "XK_dollar", "$" },
1748 { KSYM_percent, "XK_percent", "%" },
1749 { KSYM_ampersand, "XK_ampersand", "&" },
1750 { KSYM_apostrophe, "XK_apostrophe", "'" },
1751 { KSYM_parenleft, "XK_parenleft", "(" },
1752 { KSYM_parenright, "XK_parenright", ")" },
1753 { KSYM_asterisk, "XK_asterisk", "*" },
1754 { KSYM_plus, "XK_plus", "+" },
1755 { KSYM_comma, "XK_comma", "," },
1756 { KSYM_minus, "XK_minus", "-" },
1757 { KSYM_period, "XK_period", "." },
1758 { KSYM_slash, "XK_slash", "/" },
1759 { KSYM_colon, "XK_colon", ":" },
1760 { KSYM_semicolon, "XK_semicolon", ";" },
1761 { KSYM_less, "XK_less", "<" },
1762 { KSYM_equal, "XK_equal", "=" },
1763 { KSYM_greater, "XK_greater", ">" },
1764 { KSYM_question, "XK_question", "?" },
1765 { KSYM_at, "XK_at", "@" },
1768 { KSYM_bracketleft, "XK_bracketleft", "[" },
1769 { KSYM_backslash, "XK_backslash", "\\" },
1770 { KSYM_bracketright,"XK_bracketright", "]" },
1771 { KSYM_asciicircum, "XK_asciicircum", "^" },
1772 { KSYM_underscore, "XK_underscore", "_" },
1773 { KSYM_grave, "XK_grave", "grave" },
1774 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1775 { KSYM_braceleft, "XK_braceleft", "brace left" },
1776 { KSYM_bar, "XK_bar", "bar" },
1777 { KSYM_braceright, "XK_braceright", "brace right" },
1778 { KSYM_asciitilde, "XK_asciitilde", "~" },
1780 // special (non-ASCII) keys
1781 { KSYM_degree, "XK_degree", "degree" },
1782 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1783 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1784 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1785 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1786 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1787 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1788 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1790 // special (non-ASCII) keys (UTF-8, for reverse mapping only)
1791 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1792 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1793 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1794 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1795 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1796 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1797 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1798 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1800 // other keys (for reverse mapping only)
1801 { KSYM_space, "XK_space", " " },
1803 // keypad keys are not in numerical order in SDL2
1804 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1805 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1806 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1807 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1808 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1809 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1810 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1811 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1812 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1813 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1815 // end-of-array identifier
1821 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1823 static char name_buffer[30];
1826 if (key >= KSYM_A && key <= KSYM_Z)
1827 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1828 else if (key >= KSYM_a && key <= KSYM_z)
1829 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1830 else if (key >= KSYM_0 && key <= KSYM_9)
1831 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1832 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1833 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1834 else if (key == KSYM_UNDEFINED)
1835 strcpy(name_buffer, "(undefined)");
1842 if (key == translate_key[i].key)
1844 strcpy(name_buffer, translate_key[i].name);
1848 while (translate_key[++i].name);
1850 if (!translate_key[i].name)
1851 strcpy(name_buffer, "(unknown)");
1854 *name = name_buffer;
1856 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1858 static char name_buffer[30];
1861 if (key >= KSYM_A && key <= KSYM_Z)
1862 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1863 else if (key >= KSYM_a && key <= KSYM_z)
1864 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1865 else if (key >= KSYM_0 && key <= KSYM_9)
1866 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1867 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1868 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1869 else if (key == KSYM_UNDEFINED)
1870 strcpy(name_buffer, "[undefined]");
1877 if (key == translate_key[i].key)
1879 strcpy(name_buffer, translate_key[i].x11name);
1883 while (translate_key[++i].x11name);
1885 if (!translate_key[i].x11name)
1886 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1889 *x11name = name_buffer;
1891 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1893 Key key = KSYM_UNDEFINED;
1894 char *name_ptr = *name;
1896 if (strlen(*name) == 1)
1898 char c = name_ptr[0];
1900 if (c >= 'A' && c <= 'Z')
1901 key = KSYM_A + (Key)(c - 'A');
1902 else if (c >= 'a' && c <= 'z')
1903 key = KSYM_a + (Key)(c - 'a');
1904 else if (c >= '0' && c <= '9')
1905 key = KSYM_0 + (Key)(c - '0');
1908 if (key == KSYM_UNDEFINED)
1914 if (strEqual(translate_key[i].name, *name))
1916 key = translate_key[i].key;
1920 while (translate_key[++i].x11name);
1923 if (key == KSYM_UNDEFINED)
1924 Warn("getKeyFromKeyName(): not completely implemented");
1928 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1930 Key key = KSYM_UNDEFINED;
1931 char *name_ptr = *x11name;
1933 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1935 char c = name_ptr[3];
1937 if (c >= 'A' && c <= 'Z')
1938 key = KSYM_A + (Key)(c - 'A');
1939 else if (c >= 'a' && c <= 'z')
1940 key = KSYM_a + (Key)(c - 'a');
1941 else if (c >= '0' && c <= '9')
1942 key = KSYM_0 + (Key)(c - '0');
1944 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1946 char c1 = name_ptr[4];
1947 char c2 = name_ptr[5];
1950 if ((c1 >= '0' && c1 <= '9') &&
1951 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1952 d = atoi(&name_ptr[4]);
1954 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1955 key = KSYM_F1 + (Key)(d - 1);
1957 else if (strPrefix(name_ptr, "XK_"))
1963 if (strEqual(name_ptr, translate_key[i].x11name))
1965 key = translate_key[i].key;
1969 while (translate_key[++i].x11name);
1971 else if (strPrefix(name_ptr, "0x"))
1973 unsigned int value = 0;
1979 char c = *name_ptr++;
1982 if (c >= '0' && c <= '9')
1984 else if (c >= 'a' && c <= 'f')
1985 d = (int)(c - 'a' + 10);
1986 else if (c >= 'A' && c <= 'F')
1987 d = (int)(c - 'A' + 10);
1995 value = value * 16 + d;
2006 char *getKeyNameFromKey(Key key)
2010 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
2014 char *getX11KeyNameFromKey(Key key)
2018 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
2022 Key getKeyFromKeyName(char *name)
2026 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
2030 Key getKeyFromX11KeyName(char *x11name)
2034 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
2038 char getCharFromKey(Key key)
2044 } translate_key_char[] =
2046 // special (non-ASCII) keys (ISO-8859-1)
2047 { KSYM_degree, CHAR_BYTE_DEGREE },
2048 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
2049 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
2050 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
2051 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
2052 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
2053 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
2054 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
2056 // end-of-array identifier
2060 char *keyname = getKeyNameFromKey(key);
2063 if (strlen(keyname) == 1)
2065 else if (strEqual(keyname, "space"))
2073 if (key == translate_key_char[i].key)
2075 c = translate_key_char[i].key_char;
2080 while (translate_key_char[++i].key_char);
2086 char getValidConfigValueChar(char c)
2088 if (c == '#' || // used to mark comments
2089 c == '\\') // used to mark continued lines
2096 // ----------------------------------------------------------------------------
2097 // functions to translate string identifiers to integer or boolean value
2098 // ----------------------------------------------------------------------------
2100 int get_integer_from_string(char *s)
2102 static char *number_text[][3] =
2104 { "0", "zero", "null", },
2105 { "1", "one", "first" },
2106 { "2", "two", "second" },
2107 { "3", "three", "third" },
2108 { "4", "four", "fourth" },
2109 { "5", "five", "fifth" },
2110 { "6", "six", "sixth" },
2111 { "7", "seven", "seventh" },
2112 { "8", "eight", "eighth" },
2113 { "9", "nine", "ninth" },
2114 { "10", "ten", "tenth" },
2115 { "11", "eleven", "eleventh" },
2116 { "12", "twelve", "twelfth" },
2118 { NULL, NULL, NULL },
2122 char *s_lower = getStringToLower(s);
2125 for (i = 0; number_text[i][0] != NULL; i++)
2126 for (j = 0; j < 3; j++)
2127 if (strEqual(s_lower, number_text[i][j]))
2132 if (strEqual(s_lower, "false") ||
2133 strEqual(s_lower, "no") ||
2134 strEqual(s_lower, "off"))
2136 else if (strEqual(s_lower, "true") ||
2137 strEqual(s_lower, "yes") ||
2138 strEqual(s_lower, "on"))
2149 boolean get_boolean_from_string(char *s)
2151 char *s_lower = getStringToLower(s);
2152 boolean result = FALSE;
2154 if (strEqual(s_lower, "true") ||
2155 strEqual(s_lower, "yes") ||
2156 strEqual(s_lower, "on") ||
2157 get_integer_from_string(s) == 1)
2165 int get_switch3_from_string(char *s)
2167 char *s_lower = getStringToLower(s);
2170 if (strEqual(s_lower, "true") ||
2171 strEqual(s_lower, "yes") ||
2172 strEqual(s_lower, "on") ||
2173 get_integer_from_string(s) == 1)
2175 else if (strEqual(s_lower, "auto"))
2183 int get_player_nr_from_string(char *s)
2185 static char *player_text[] =
2195 char *s_lower = getStringToLower(s);
2199 for (i = 0; player_text[i] != NULL; i++)
2200 if (strEqual(s_lower, player_text[i]))
2209 // ----------------------------------------------------------------------------
2210 // functions for generic lists
2211 // ----------------------------------------------------------------------------
2213 ListNode *newListNode(void)
2215 return checked_calloc(sizeof(ListNode));
2218 void addNodeToList(ListNode **node_first, char *key, void *content)
2220 ListNode *node_new = newListNode();
2222 node_new->key = getStringCopy(key);
2223 node_new->content = content;
2224 node_new->next = *node_first;
2227 (*node_first)->prev = node_new;
2229 *node_first = node_new;
2232 void deleteNodeFromList(ListNode **node_first, char *key,
2233 void (*destructor_function)(void *))
2235 if (node_first == NULL || *node_first == NULL)
2238 if (strEqual((*node_first)->key, key))
2240 // after first recursion, (*node_first)->prev->next == *node_first,
2241 // so *node_first would be overwritten with (*node_first)->next
2242 // => use a copy of *node_first (and later of (*node_first)->next)
2243 ListNode *node = *node_first;
2244 ListNode *node_next = node->next;
2246 checked_free(node->key);
2248 if (destructor_function)
2249 destructor_function(node->content);
2252 node->prev->next = node->next;
2255 node->next->prev = node->prev;
2259 // after removing node, set list pointer to next valid list node
2260 // (this is important if the first node of the list was deleted)
2261 *node_first = node_next;
2265 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2269 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2271 if (node_first == NULL)
2274 if (strEqual(node_first->key, key))
2277 return getNodeFromKey(node_first->next, key);
2280 int getNumNodes(ListNode *node_first)
2282 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2286 static void dumpList(ListNode *node_first)
2288 ListNode *node = node_first;
2292 Debug("internal:dumpList", "['%s' (%d)]", node->key,
2293 ((struct ListNodeInfo *)node->content)->num_references);
2297 Debug("internal:dumpList", "[%d nodes]", getNumNodes(node_first));
2302 // ----------------------------------------------------------------------------
2303 // functions for file handling
2304 // ----------------------------------------------------------------------------
2306 #define MAX_BUFFER_SIZE 4096
2308 File *openFile(char *filename, char *mode)
2310 File *file = checked_calloc(sizeof(File));
2312 file->file = fopen(filename, mode);
2314 if (file->file != NULL)
2316 file->filename = getStringCopy(filename);
2321 #if defined(PLATFORM_ANDROID)
2322 file->asset_file = SDL_RWFromFile(filename, mode);
2324 if (file->asset_file != NULL)
2326 file->file_is_asset = TRUE;
2327 file->filename = getStringCopy(filename);
2338 int closeFile(File *file)
2345 #if defined(PLATFORM_ANDROID)
2346 if (file->asset_file)
2347 result = SDL_RWclose(file->asset_file);
2351 result = fclose(file->file);
2353 checked_free(file->filename);
2359 int checkEndOfFile(File *file)
2361 #if defined(PLATFORM_ANDROID)
2362 if (file->file_is_asset)
2363 return file->end_of_file;
2366 return feof(file->file);
2369 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2371 #if defined(PLATFORM_ANDROID)
2372 if (file->file_is_asset)
2374 if (file->end_of_file)
2377 size_t num_items_read =
2378 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2380 if (num_items_read < num_items)
2381 file->end_of_file = TRUE;
2383 return num_items_read;
2387 return fread(buffer, item_size, num_items, file->file);
2390 size_t writeFile(File *file, void *buffer, size_t item_size, size_t num_items)
2392 return fwrite(buffer, item_size, num_items, file->file);
2395 int seekFile(File *file, long offset, int whence)
2397 #if defined(PLATFORM_ANDROID)
2398 if (file->file_is_asset)
2400 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2401 whence == SEEK_CUR ? RW_SEEK_CUR :
2402 whence == SEEK_END ? RW_SEEK_END : 0);
2404 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2408 return fseek(file->file, offset, whence);
2411 int getByteFromFile(File *file)
2413 #if defined(PLATFORM_ANDROID)
2414 if (file->file_is_asset)
2416 if (file->end_of_file)
2420 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2422 if (num_bytes_read < 1)
2423 file->end_of_file = TRUE;
2425 return (file->end_of_file ? EOF : (int)c);
2429 return fgetc(file->file);
2432 char *getStringFromFile(File *file, char *line, int size)
2434 #if defined(PLATFORM_ANDROID)
2435 if (file->file_is_asset)
2437 if (file->end_of_file)
2440 char *line_ptr = line;
2441 int num_bytes_read = 0;
2443 while (num_bytes_read < size - 1 &&
2444 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2445 *line_ptr++ != '\n')
2450 if (strlen(line) == 0)
2452 file->end_of_file = TRUE;
2461 return fgets(line, size, file->file);
2464 int copyFile(char *filename_from, char *filename_to)
2466 File *file_from, *file_to;
2468 if ((file_from = openFile(filename_from, MODE_READ)) == NULL)
2473 if ((file_to = openFile(filename_to, MODE_WRITE)) == NULL)
2475 closeFile(file_from);
2480 while (!checkEndOfFile(file_from))
2482 byte buffer[MAX_BUFFER_SIZE];
2483 size_t bytes_read = readFile(file_from, buffer, 1, MAX_BUFFER_SIZE);
2485 writeFile(file_to, buffer, 1, bytes_read);
2488 closeFile(file_from);
2495 // ----------------------------------------------------------------------------
2496 // functions for directory handling
2497 // ----------------------------------------------------------------------------
2499 Directory *openDirectory(char *dir_name)
2501 Directory *dir = checked_calloc(sizeof(Directory));
2503 dir->dir = opendir(dir_name);
2505 if (dir->dir != NULL)
2507 dir->filename = getStringCopy(dir_name);
2512 #if defined(PLATFORM_ANDROID)
2513 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2515 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2517 checked_free(asset_toc_filename);
2519 if (dir->asset_toc_file != NULL)
2521 dir->directory_is_asset = TRUE;
2522 dir->filename = getStringCopy(dir_name);
2533 int closeDirectory(Directory *dir)
2540 #if defined(PLATFORM_ANDROID)
2541 if (dir->asset_toc_file)
2542 result = SDL_RWclose(dir->asset_toc_file);
2546 result = closedir(dir->dir);
2549 freeDirectoryEntry(dir->dir_entry);
2551 checked_free(dir->filename);
2557 DirectoryEntry *readDirectory(Directory *dir)
2560 freeDirectoryEntry(dir->dir_entry);
2562 dir->dir_entry = NULL;
2564 #if defined(PLATFORM_ANDROID)
2565 if (dir->directory_is_asset)
2567 char line[MAX_LINE_LEN];
2568 char *line_ptr = line;
2569 int num_bytes_read = 0;
2571 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2572 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2581 if (strlen(line) == 0)
2584 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2586 dir->dir_entry->is_directory = FALSE;
2587 if (line[strlen(line) - 1] == '/')
2589 dir->dir_entry->is_directory = TRUE;
2591 line[strlen(line) - 1] = '\0';
2594 dir->dir_entry->basename = getStringCopy(line);
2595 dir->dir_entry->filename = getPath2(dir->filename, line);
2597 return dir->dir_entry;
2601 struct dirent *dir_entry = readdir(dir->dir);
2603 if (dir_entry == NULL)
2606 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2608 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2609 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2611 struct stat file_status;
2613 dir->dir_entry->is_directory =
2614 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2615 S_ISDIR(file_status.st_mode));
2617 return dir->dir_entry;
2620 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2622 if (dir_entry == NULL)
2625 checked_free(dir_entry->basename);
2626 checked_free(dir_entry->filename);
2627 checked_free(dir_entry);
2631 // ----------------------------------------------------------------------------
2632 // functions for checking files and filenames
2633 // ----------------------------------------------------------------------------
2635 boolean directoryExists(char *dir_name)
2637 if (dir_name == NULL)
2640 struct stat file_status;
2641 boolean success = (stat(dir_name, &file_status) == 0 &&
2642 S_ISDIR(file_status.st_mode));
2644 #if defined(PLATFORM_ANDROID)
2647 // this might be an asset directory; check by trying to open toc file
2648 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2649 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2651 checked_free(asset_toc_filename);
2653 success = (file != NULL);
2663 boolean fileExists(char *filename)
2665 if (filename == NULL)
2668 boolean success = (access(filename, F_OK) == 0);
2670 #if defined(PLATFORM_ANDROID)
2673 // this might be an asset file; check by trying to open it
2674 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2676 success = (file != NULL);
2687 static boolean fileHasPrefix(char *basename, char *prefix)
2689 static char *basename_lower = NULL;
2690 int basename_length, prefix_length;
2692 checked_free(basename_lower);
2694 if (basename == NULL || prefix == NULL)
2697 basename_lower = getStringToLower(basename);
2698 basename_length = strlen(basename_lower);
2699 prefix_length = strlen(prefix);
2701 if (basename_length > prefix_length + 1 &&
2702 basename_lower[prefix_length] == '.' &&
2703 strncmp(basename_lower, prefix, prefix_length) == 0)
2710 static boolean fileHasSuffix(char *basename, char *suffix)
2712 static char *basename_lower = NULL;
2713 int basename_length, suffix_length;
2715 checked_free(basename_lower);
2717 if (basename == NULL || suffix == NULL)
2720 basename_lower = getStringToLower(basename);
2721 basename_length = strlen(basename_lower);
2722 suffix_length = strlen(suffix);
2724 if (basename_length > suffix_length + 1 &&
2725 basename_lower[basename_length - suffix_length - 1] == '.' &&
2726 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2732 static boolean FileCouldBeArtwork(char *filename)
2734 char *basename = getBaseNamePtr(filename);
2736 return (!strEqual(basename, ".") &&
2737 !strEqual(basename, "..") &&
2738 !fileHasSuffix(basename, "txt") &&
2739 !fileHasSuffix(basename, "conf") &&
2740 !directoryExists(filename));
2743 boolean FileIsGraphic(char *filename)
2745 return FileCouldBeArtwork(filename);
2748 boolean FileIsSound(char *filename)
2750 return FileCouldBeArtwork(filename);
2753 boolean FileIsMusic(char *filename)
2755 return FileCouldBeArtwork(filename);
2758 boolean FileIsArtworkType(char *filename, int type)
2760 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2761 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2762 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2768 // ----------------------------------------------------------------------------
2769 // functions for loading artwork configuration information
2770 // ----------------------------------------------------------------------------
2772 char *get_mapped_token(char *token)
2774 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
2775 static char *map_token_prefix[][2] =
2777 { "char_procent", "char_percent" },
2778 { "bd_magic_wall_filling", "bd_magic_wall.filling" },
2779 { "bd_magic_wall_emptying", "bd_magic_wall.emptying" },
2780 { "bd_butterfly_left", "bd_butterfly.left" },
2781 { "bd_butterfly_right", "bd_butterfly.right" },
2782 { "bd_butterfly_up", "bd_butterfly.up" },
2783 { "bd_butterfly_down", "bd_butterfly.down" },
2784 { "bd_firefly_left", "bd_firefly.left" },
2785 { "bd_firefly_right", "bd_firefly.right" },
2786 { "bd_firefly_up", "bd_firefly.up" },
2787 { "bd_firefly_down", "bd_firefly.down" },
2793 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2795 int len_token_prefix = strlen(map_token_prefix[i][0]);
2797 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2798 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2801 // change tokens containing ".gfx" by moving the "gfx" part to the very left
2802 char *gfx_substring = ".gfx";
2803 char *gfx_prefix = "gfx.";
2804 if (strstr(token, gfx_substring) != NULL)
2806 char *token_prefix = getStringCopy(token);
2807 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
2808 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
2811 // cut off token string at ".gfx" substring position
2812 *token_gfx_pos = '\0';
2814 // put together prefix "gfx." and token prefix and suffix without ".gfx"
2815 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
2819 return mapped_token;
2825 static char *get_special_base_token(struct ArtworkListInfo *artwork_info,
2828 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
2829 static struct ConfigTypeInfo prefix_list[] =
2831 { "global.anim_1" },
2832 { "global.anim_2" },
2833 { "global.anim_3" },
2834 { "global.anim_4" },
2835 { "global.anim_5" },
2836 { "global.anim_6" },
2837 { "global.anim_7" },
2838 { "global.anim_8" },
2839 { "global.anim_9" },
2840 { "global.anim_10" },
2841 { "global.anim_11" },
2842 { "global.anim_12" },
2843 { "global.anim_13" },
2844 { "global.anim_14" },
2845 { "global.anim_15" },
2846 { "global.anim_16" },
2847 { "global.anim_17" },
2848 { "global.anim_18" },
2849 { "global.anim_19" },
2850 { "global.anim_20" },
2851 { "global.anim_21" },
2852 { "global.anim_22" },
2853 { "global.anim_23" },
2854 { "global.anim_24" },
2855 { "global.anim_25" },
2856 { "global.anim_26" },
2857 { "global.anim_27" },
2858 { "global.anim_28" },
2859 { "global.anim_29" },
2860 { "global.anim_30" },
2861 { "global.anim_31" },
2862 { "global.anim_32" },
2866 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2867 boolean prefix_found = FALSE;
2871 // search for prefix to check if base token has to be created
2872 for (i = 0; prefix_list[i].token != NULL; i++)
2873 if (strPrefix(token, prefix_list[i].token))
2874 prefix_found = TRUE;
2879 // search for suffix (parameter) to determine base token length
2880 for (i = 0; suffix_list[i].token != NULL; i++)
2881 if (strSuffix(token, suffix_list[i].token))
2882 len_suffix = strlen(suffix_list[i].token);
2884 return getStringCopyN(token, strlen(token) - len_suffix);
2887 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2888 struct ListNodeInfo ***, int *);
2890 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2891 struct ConfigTypeInfo *suffix_list,
2892 char **ignore_tokens,
2893 int num_file_list_entries)
2895 SetupFileHash *ignore_tokens_hash;
2896 struct FileInfo *file_list;
2897 int num_file_list_entries_found = 0;
2898 int num_suffix_list_entries = 0;
2902 // create hash from list of tokens to be ignored (for quick access)
2903 ignore_tokens_hash = newSetupFileHash();
2904 for (i = 0; ignore_tokens[i] != NULL; i++)
2905 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
2907 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2909 for (i = 0; suffix_list[i].token != NULL; i++)
2910 num_suffix_list_entries++;
2912 // always start with reliable default values
2913 for (i = 0; i < num_file_list_entries; i++)
2915 file_list[i].token = NULL;
2917 file_list[i].default_filename = NULL;
2918 file_list[i].filename = NULL;
2920 if (num_suffix_list_entries > 0)
2922 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2924 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2925 file_list[i].parameter = checked_calloc(parameter_array_size);
2927 for (j = 0; j < num_suffix_list_entries; j++)
2929 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2930 setString(&file_list[i].parameter[j], suffix_list[j].value);
2933 file_list[i].redefined = FALSE;
2934 file_list[i].fallback_to_default = FALSE;
2935 file_list[i].default_is_cloned = FALSE;
2941 for (i = 0; config_list[i].token != NULL; i++)
2943 int len_config_token = strlen(config_list[i].token);
2944 boolean is_file_entry = TRUE;
2946 for (j = 0; suffix_list[j].token != NULL; j++)
2948 int len_suffix = strlen(suffix_list[j].token);
2950 if (len_suffix < len_config_token &&
2951 strEqual(&config_list[i].token[len_config_token - len_suffix],
2952 suffix_list[j].token))
2954 setString(&file_list[list_pos].default_parameter[j],
2955 config_list[i].value);
2957 is_file_entry = FALSE;
2963 // the following tokens are no file definitions, but other config tokens
2964 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
2965 is_file_entry = FALSE;
2972 if (list_pos >= num_file_list_entries)
2975 file_list[list_pos].token = config_list[i].token;
2976 file_list[list_pos].default_filename = config_list[i].value;
2979 if (strSuffix(config_list[i].token, ".clone_from"))
2980 file_list[list_pos].default_is_cloned = TRUE;
2983 num_file_list_entries_found = list_pos + 1;
2984 if (num_file_list_entries_found != num_file_list_entries)
2987 Error("inconsistant config list information:");
2988 Error("- should be: %d (according to 'src/conf_xxx.h')",
2989 num_file_list_entries);
2990 Error("- found to be: %d (according to 'src/conf_xxx.c')",
2991 num_file_list_entries_found);
2996 freeSetupFileHash(ignore_tokens_hash);
3001 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3003 int len_token = strlen(token);
3004 int len_suffix = strlen(suffix);
3006 if (start_pos < 0) // compare suffix from end of string
3007 start_pos += len_token;
3009 if (start_pos < 0 || start_pos + len_suffix > len_token)
3012 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3015 if (token[start_pos + len_suffix] == '\0')
3018 if (token[start_pos + len_suffix] == '.')
3024 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3026 static void read_token_parameters(SetupFileHash *setup_file_hash,
3027 struct ConfigTypeInfo *suffix_list,
3028 struct FileInfo *file_list_entry)
3030 // check for config token that is the base token without any suffixes
3031 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3032 char *known_token_value = KNOWN_TOKEN_VALUE;
3035 if (filename != NULL)
3037 setString(&file_list_entry->filename, filename);
3039 // when file definition found, set all parameters to default values
3040 for (i = 0; suffix_list[i].token != NULL; i++)
3041 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3043 file_list_entry->redefined = TRUE;
3045 // mark config file token as well known from default config
3046 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3049 // check for config tokens that can be build by base token and suffixes
3050 for (i = 0; suffix_list[i].token != NULL; i++)
3052 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3053 char *value = getHashEntry(setup_file_hash, token);
3057 setString(&file_list_entry->parameter[i], value);
3059 // mark config file token as well known from default config
3060 setHashEntry(setup_file_hash, token, known_token_value);
3067 static void add_dynamic_file_list_entry(struct FileInfo **list,
3068 int *num_list_entries,
3069 SetupFileHash *extra_file_hash,
3070 struct ConfigTypeInfo *suffix_list,
3071 int num_suffix_list_entries,
3074 struct FileInfo *new_list_entry;
3075 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3077 (*num_list_entries)++;
3078 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3079 new_list_entry = &(*list)[*num_list_entries - 1];
3081 new_list_entry->token = getStringCopy(token);
3082 new_list_entry->default_filename = NULL;
3083 new_list_entry->filename = NULL;
3084 new_list_entry->parameter = checked_calloc(parameter_array_size);
3086 new_list_entry->redefined = FALSE;
3087 new_list_entry->fallback_to_default = FALSE;
3088 new_list_entry->default_is_cloned = FALSE;
3090 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3093 static void add_property_mapping(struct PropertyMapping **list,
3094 int *num_list_entries,
3095 int base_index, int ext1_index,
3096 int ext2_index, int ext3_index,
3099 struct PropertyMapping *new_list_entry;
3101 (*num_list_entries)++;
3102 *list = checked_realloc(*list,
3103 *num_list_entries * sizeof(struct PropertyMapping));
3104 new_list_entry = &(*list)[*num_list_entries - 1];
3106 new_list_entry->base_index = base_index;
3107 new_list_entry->ext1_index = ext1_index;
3108 new_list_entry->ext2_index = ext2_index;
3109 new_list_entry->ext3_index = ext3_index;
3111 new_list_entry->artwork_index = artwork_index;
3114 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3117 struct FileInfo *file_list = artwork_info->file_list;
3118 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3119 char **base_prefixes = artwork_info->base_prefixes;
3120 char **ext1_suffixes = artwork_info->ext1_suffixes;
3121 char **ext2_suffixes = artwork_info->ext2_suffixes;
3122 char **ext3_suffixes = artwork_info->ext3_suffixes;
3123 char **ignore_tokens = artwork_info->ignore_tokens;
3124 int num_file_list_entries = artwork_info->num_file_list_entries;
3125 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3126 int num_base_prefixes = artwork_info->num_base_prefixes;
3127 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3128 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3129 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3130 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3131 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3132 SetupFileHash *extra_file_hash, *empty_file_hash;
3133 char *known_token_value = KNOWN_TOKEN_VALUE;
3134 char *base_token_value = UNDEFINED_FILENAME;
3137 if (filename == NULL)
3140 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3143 // separate valid (defined) from empty (undefined) config token values
3144 valid_file_hash = newSetupFileHash();
3145 empty_file_hash = newSetupFileHash();
3146 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3148 char *value = HASH_ITERATION_VALUE(itr);
3150 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3151 HASH_ITERATION_TOKEN(itr), value);
3153 END_HASH_ITERATION(setup_file_hash, itr)
3155 // at this point, we do not need the setup file hash anymore -- free it
3156 freeSetupFileHash(setup_file_hash);
3158 // prevent changing hash while iterating over it by using a temporary copy
3159 valid_file_hash_tmp = newSetupFileHash();
3160 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3162 setHashEntry(valid_file_hash_tmp,
3163 HASH_ITERATION_TOKEN(itr),
3164 HASH_ITERATION_VALUE(itr));
3166 END_HASH_ITERATION(valid_file_hash, itr)
3168 // (iterate over same temporary hash, as modifications are independent)
3170 // map deprecated to current tokens (using prefix match and replace)
3171 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3173 char *token = HASH_ITERATION_TOKEN(itr);
3174 char *mapped_token = get_mapped_token(token);
3176 if (mapped_token != NULL)
3178 char *value = HASH_ITERATION_VALUE(itr);
3181 setHashEntry(valid_file_hash, mapped_token, value);
3183 // ignore old token (by setting it to "known" keyword)
3184 setHashEntry(valid_file_hash, token, known_token_value);
3189 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3191 // add special base tokens (using prefix match and replace)
3192 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3194 char *token = HASH_ITERATION_TOKEN(itr);
3195 char *base_token = get_special_base_token(artwork_info, token);
3197 if (base_token != NULL)
3199 // add base token only if it does not already exist
3200 if (getHashEntry(valid_file_hash, base_token) == NULL)
3201 setHashEntry(valid_file_hash, base_token, base_token_value);
3206 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3208 // free temporary hash used for iteration
3209 freeSetupFileHash(valid_file_hash_tmp);
3211 // read parameters for all known config file tokens
3212 for (i = 0; i < num_file_list_entries; i++)
3213 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3215 // set all tokens that can be ignored here to "known" keyword
3216 for (i = 0; i < num_ignore_tokens; i++)
3217 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3219 // copy all unknown config file tokens to extra config hash
3220 extra_file_hash = newSetupFileHash();
3221 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3223 char *value = HASH_ITERATION_VALUE(itr);
3225 if (!strEqual(value, known_token_value))
3226 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3228 END_HASH_ITERATION(valid_file_hash, itr)
3230 // at this point, we do not need the valid file hash anymore -- free it
3231 freeSetupFileHash(valid_file_hash);
3233 // now try to determine valid, dynamically defined config tokens
3235 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3237 struct FileInfo **dynamic_file_list =
3238 &artwork_info->dynamic_file_list;
3239 int *num_dynamic_file_list_entries =
3240 &artwork_info->num_dynamic_file_list_entries;
3241 struct PropertyMapping **property_mapping =
3242 &artwork_info->property_mapping;
3243 int *num_property_mapping_entries =
3244 &artwork_info->num_property_mapping_entries;
3245 int current_summarized_file_list_entry =
3246 artwork_info->num_file_list_entries +
3247 artwork_info->num_dynamic_file_list_entries;
3248 char *token = HASH_ITERATION_TOKEN(itr);
3249 int len_token = strlen(token);
3251 boolean base_prefix_found = FALSE;
3252 boolean parameter_suffix_found = FALSE;
3254 // skip all parameter definitions (handled by read_token_parameters())
3255 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3257 int len_suffix = strlen(suffix_list[i].token);
3259 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3260 parameter_suffix_found = TRUE;
3263 if (parameter_suffix_found)
3266 // ---------- step 0: search for matching base prefix ----------
3269 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3271 char *base_prefix = base_prefixes[i];
3272 int len_base_prefix = strlen(base_prefix);
3273 boolean ext1_suffix_found = FALSE;
3274 boolean ext2_suffix_found = FALSE;
3275 boolean ext3_suffix_found = FALSE;
3276 boolean exact_match = FALSE;
3277 int base_index = -1;
3278 int ext1_index = -1;
3279 int ext2_index = -1;
3280 int ext3_index = -1;
3282 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3284 if (!base_prefix_found)
3289 if (start_pos + len_base_prefix == len_token) // exact match
3293 add_dynamic_file_list_entry(dynamic_file_list,
3294 num_dynamic_file_list_entries,
3297 num_suffix_list_entries,
3299 add_property_mapping(property_mapping,
3300 num_property_mapping_entries,
3301 base_index, -1, -1, -1,
3302 current_summarized_file_list_entry);
3306 // ---------- step 1: search for matching first suffix ----------
3308 start_pos += len_base_prefix;
3309 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3311 char *ext1_suffix = ext1_suffixes[j];
3312 int len_ext1_suffix = strlen(ext1_suffix);
3314 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3316 if (!ext1_suffix_found)
3321 if (start_pos + len_ext1_suffix == len_token) // exact match
3325 add_dynamic_file_list_entry(dynamic_file_list,
3326 num_dynamic_file_list_entries,
3329 num_suffix_list_entries,
3331 add_property_mapping(property_mapping,
3332 num_property_mapping_entries,
3333 base_index, ext1_index, -1, -1,
3334 current_summarized_file_list_entry);
3338 start_pos += len_ext1_suffix;
3344 // ---------- step 2: search for matching second suffix ----------
3346 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3348 char *ext2_suffix = ext2_suffixes[k];
3349 int len_ext2_suffix = strlen(ext2_suffix);
3351 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3353 if (!ext2_suffix_found)
3358 if (start_pos + len_ext2_suffix == len_token) // exact match
3362 add_dynamic_file_list_entry(dynamic_file_list,
3363 num_dynamic_file_list_entries,
3366 num_suffix_list_entries,
3368 add_property_mapping(property_mapping,
3369 num_property_mapping_entries,
3370 base_index, ext1_index, ext2_index, -1,
3371 current_summarized_file_list_entry);
3375 start_pos += len_ext2_suffix;
3381 // ---------- step 3: search for matching third suffix ----------
3383 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3385 char *ext3_suffix = ext3_suffixes[l];
3386 int len_ext3_suffix = strlen(ext3_suffix);
3388 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3390 if (!ext3_suffix_found)
3395 if (start_pos + len_ext3_suffix == len_token) // exact match
3399 add_dynamic_file_list_entry(dynamic_file_list,
3400 num_dynamic_file_list_entries,
3403 num_suffix_list_entries,
3405 add_property_mapping(property_mapping,
3406 num_property_mapping_entries,
3407 base_index, ext1_index, ext2_index, ext3_index,
3408 current_summarized_file_list_entry);
3414 END_HASH_ITERATION(extra_file_hash, itr)
3416 if (artwork_info->num_dynamic_file_list_entries > 0)
3418 artwork_info->dynamic_artwork_list =
3419 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3420 artwork_info->sizeof_artwork_list_entry);
3423 if (options.verbose && IS_PARENT_PROCESS())
3425 SetupFileList *setup_file_list, *list;
3426 boolean dynamic_tokens_found = FALSE;
3427 boolean unknown_tokens_found = FALSE;
3428 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3430 // list may be NULL for empty artwork config files
3431 setup_file_list = loadSetupFileList(filename);
3433 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3435 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3436 dynamic_tokens_found = TRUE;
3438 unknown_tokens_found = TRUE;
3440 END_HASH_ITERATION(extra_file_hash, itr)
3442 if (options.debug && dynamic_tokens_found)
3444 Debug("config", "---");
3445 Debug("config", "dynamic token(s) found in config file:");
3446 Debug("config", "- config file: '%s'", filename);
3448 for (list = setup_file_list; list != NULL; list = list->next)
3450 char *value = getHashEntry(extra_file_hash, list->token);
3452 if (value != NULL && strEqual(value, known_token_value))
3453 Debug("config", "- dynamic token: '%s'", list->token);
3456 Debug("config", "---");
3459 if (unknown_tokens_found)
3462 Warn("unknown token(s) found in config file:");
3463 Warn("- config file: '%s'", filename);
3465 for (list = setup_file_list; list != NULL; list = list->next)
3467 char *value = getHashEntry(extra_file_hash, list->token);
3469 if (value != NULL && !strEqual(value, known_token_value))
3470 Warn("- dynamic token: '%s'", list->token);
3476 if (undefined_values_found)
3479 Warn("undefined values found in config file:");
3480 Warn("- config file: '%s'", filename);
3482 for (list = setup_file_list; list != NULL; list = list->next)
3484 char *value = getHashEntry(empty_file_hash, list->token);
3487 Warn("- undefined value for token: '%s'", list->token);
3493 freeSetupFileList(setup_file_list);
3496 freeSetupFileHash(extra_file_hash);
3497 freeSetupFileHash(empty_file_hash);
3500 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3502 struct FileInfo *file_list = artwork_info->file_list;
3503 int num_file_list_entries = artwork_info->num_file_list_entries;
3504 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3505 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3508 DrawInitText("Loading artwork config", 120, FC_GREEN);
3509 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3511 // always start with reliable default values
3512 for (i = 0; i < num_file_list_entries; i++)
3514 setString(&file_list[i].filename, file_list[i].default_filename);
3516 for (j = 0; j < num_suffix_list_entries; j++)
3517 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3519 file_list[i].redefined = FALSE;
3520 file_list[i].fallback_to_default = FALSE;
3523 // free previous dynamic artwork file array
3524 if (artwork_info->dynamic_file_list != NULL)
3526 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3528 free(artwork_info->dynamic_file_list[i].token);
3529 free(artwork_info->dynamic_file_list[i].filename);
3530 free(artwork_info->dynamic_file_list[i].parameter);
3533 free(artwork_info->dynamic_file_list);
3534 artwork_info->dynamic_file_list = NULL;
3536 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3537 &artwork_info->num_dynamic_file_list_entries);
3540 // free previous property mapping
3541 if (artwork_info->property_mapping != NULL)
3543 free(artwork_info->property_mapping);
3545 artwork_info->property_mapping = NULL;
3546 artwork_info->num_property_mapping_entries = 0;
3549 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3551 // first look for special artwork configured in level series config
3552 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3554 if (fileExists(filename_base))
3555 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3558 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3560 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3561 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3564 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3565 struct ListNodeInfo **listnode)
3569 char *filename = (*listnode)->source_filename;
3571 if (--(*listnode)->num_references <= 0)
3572 deleteNodeFromList(&artwork_info->content_list, filename,
3573 artwork_info->free_artwork);
3579 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3580 struct ListNodeInfo **listnode,
3581 struct FileInfo *file_list_entry)
3591 char *basename = file_list_entry->filename;
3592 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3594 if (filename == NULL)
3596 Warn("cannot find artwork file '%s'", basename);
3598 basename = file_list_entry->default_filename;
3600 // fail for cloned default artwork that has no default filename defined
3601 if (file_list_entry->default_is_cloned &&
3602 strEqual(basename, UNDEFINED_FILENAME))
3604 void (*error_func)(char *, ...) = Warn;
3606 // we can get away without sounds and music, but not without graphics
3607 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3610 error_func("token '%s' was cloned and has no default filename",
3611 file_list_entry->token);
3616 // dynamic artwork has no default filename / skip empty default artwork
3617 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3620 file_list_entry->fallback_to_default = TRUE;
3622 Warn("trying default artwork file '%s'", basename);
3624 filename = getCustomArtworkFilename(basename, artwork_info->type);
3626 if (filename == NULL)
3628 void (*error_func)(char *, ...) = Warn;
3630 // we can get away without sounds and music, but not without graphics
3631 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3634 error_func("cannot find default artwork file '%s'", basename);
3640 // check if the old and the new artwork file are the same
3641 if (*listnode && strEqual((*listnode)->source_filename, filename))
3643 // The old and new artwork are the same (have the same filename and path).
3644 // This usually means that this artwork does not exist in this artwork set
3645 // and a fallback to the existing artwork is done.
3650 // delete existing artwork file entry
3651 deleteArtworkListEntry(artwork_info, listnode);
3653 // check if the new artwork file already exists in the list of artwork
3654 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3656 *listnode = (struct ListNodeInfo *)node->content;
3657 (*listnode)->num_references++;
3662 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3663 DrawInitText(basename, 150, FC_YELLOW);
3665 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3667 // add new artwork file entry to the list of artwork files
3668 (*listnode)->num_references = 1;
3669 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3674 void (*error_func)(char *, ...) = Warn;
3676 // we can get away without sounds and music, but not without graphics
3677 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3680 error_func("cannot load artwork file '%s'", basename);
3686 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3687 struct ListNodeInfo **listnode,
3688 struct FileInfo *file_list_entry)
3690 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3692 deleteArtworkListEntry(artwork_info, listnode);
3697 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3700 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3702 struct FileInfo *file_list = artwork_info->file_list;
3703 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3704 int num_file_list_entries = artwork_info->num_file_list_entries;
3705 int num_dynamic_file_list_entries =
3706 artwork_info->num_dynamic_file_list_entries;
3709 print_timestamp_init("ReloadCustomArtworkList");
3711 for (i = 0; i < num_file_list_entries; i++)
3712 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3715 for (i = 0; i < num_dynamic_file_list_entries; i++)
3716 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3717 &dynamic_file_list[i]);
3719 print_timestamp_done("ReloadCustomArtworkList");
3722 dumpList(artwork_info->content_list);
3726 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3727 struct ListNodeInfo ***list,
3728 int *num_list_entries)
3735 for (i = 0; i < *num_list_entries; i++)
3736 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3740 *num_list_entries = 0;
3743 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3745 if (artwork_info == NULL)
3748 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3749 &artwork_info->num_file_list_entries);
3751 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3752 &artwork_info->num_dynamic_file_list_entries);
3756 // ----------------------------------------------------------------------------
3757 // functions only needed for non-Unix (non-command-line) systems
3758 // (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")
3759 // (now also added for Windows, to create files in user data directory)
3760 // ----------------------------------------------------------------------------
3762 char *getLogFilename(char *basename)
3764 return getPath2(getMainUserGameDataDir(), basename);
3767 void OpenLogFiles(void)
3771 InitMainUserDataDirectory();
3773 for (i = 0; i < NUM_LOGS; i++)
3775 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3778 program.log_file[i] = program.log_file_default[i]; // reset to default
3780 Warn("cannot open file '%s' for writing: %s",
3781 program.log_filename[i], strerror(errno));
3784 // output should be unbuffered so it is not truncated in a crash
3785 setbuf(program.log_file[i], NULL);
3789 void CloseLogFiles(void)
3793 for (i = 0; i < NUM_LOGS; i++)
3794 if (program.log_file[i] != program.log_file_default[i])
3795 fclose(program.log_file[i]);
3798 void DumpLogFile(int nr)
3800 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3802 if (log_file == NULL)
3805 while (!feof(log_file))
3806 fputc(fgetc(log_file), stdout);
3811 void NotifyUserAboutErrorFile(void)
3813 #if defined(PLATFORM_WIN32)
3814 char *title_text = getStringCat2(program.program_title, " Error Message");
3815 char *error_text = getStringCat2("The program was aborted due to an error; "
3816 "for details, see the following error file:"
3818 program.log_filename[LOG_ERR_ID]);
3820 MessageBox(NULL, error_text, title_text, MB_OK);
3825 // ----------------------------------------------------------------------------
3826 // the following is only for debugging purpose and normally not used
3827 // ----------------------------------------------------------------------------
3831 #define DEBUG_PRINT_INIT_TIMESTAMPS TRUE
3832 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3834 #define DEBUG_NUM_TIMESTAMPS 10
3835 #define DEBUG_TIME_IN_MICROSECONDS 0
3837 #if DEBUG_TIME_IN_MICROSECONDS
3838 static double Counter_Microseconds(void)
3840 static struct timeval base_time = { 0, 0 };
3841 struct timeval current_time;
3844 gettimeofday(¤t_time, NULL);
3846 // reset base time in case of wrap-around
3847 if (current_time.tv_sec < base_time.tv_sec)
3848 base_time = current_time;
3851 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3852 ((double)(current_time.tv_usec - base_time.tv_usec));
3854 return counter; // return microseconds since last init
3858 static char *debug_print_timestamp_get_padding(int padding_size)
3860 static char *padding = NULL;
3861 int max_padding_size = 100;
3863 if (padding == NULL)
3865 padding = checked_calloc(max_padding_size + 1);
3866 memset(padding, ' ', max_padding_size);
3869 return &padding[MAX(0, max_padding_size - padding_size)];
3872 void debug_print_timestamp(int counter_nr, char *message)
3874 int indent_size = 8;
3875 int padding_size = 40;
3876 float timestamp_interval;
3879 Fail("debugging: invalid negative counter");
3880 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3881 Fail("debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3883 #if DEBUG_TIME_IN_MICROSECONDS
3884 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3887 counter[counter_nr][0] = Counter_Microseconds();
3889 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3892 counter[counter_nr][0] = Counter();
3895 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3896 counter[counter_nr][1] = counter[counter_nr][0];
3899 Debug("time:init", "%s%s%s %.3f %s",
3900 debug_print_timestamp_get_padding(counter_nr * indent_size),
3902 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3903 timestamp_interval / 1000,
3908 static void debug_print_parent_only(char *format, ...)
3910 if (!IS_PARENT_PROCESS())
3917 va_start(ap, format);
3918 vprintf(format, ap);
3928 static void print_timestamp_ext(char *message, char *mode)
3930 #if DEBUG_PRINT_INIT_TIMESTAMPS
3931 static char *debug_message = NULL;
3932 static char *last_message = NULL;
3933 static int counter_nr = 0;
3934 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3936 checked_free(debug_message);
3937 debug_message = getStringCat3(mode, " ", message);
3939 if (strEqual(mode, "INIT"))
3941 debug_print_timestamp(counter_nr, NULL);
3943 if (counter_nr + 1 < max_depth)
3944 debug_print_timestamp(counter_nr, debug_message);
3948 debug_print_timestamp(counter_nr, NULL);
3950 else if (strEqual(mode, "DONE"))
3954 if (counter_nr + 1 < max_depth ||
3955 (counter_nr == 0 && max_depth == 1))
3957 last_message = message;
3959 if (counter_nr == 0 && max_depth == 1)
3961 checked_free(debug_message);
3962 debug_message = getStringCat3("TIME", " ", message);
3965 debug_print_timestamp(counter_nr, debug_message);
3968 else if (!strEqual(mode, "TIME") ||
3969 !strEqual(message, last_message))
3971 if (counter_nr < max_depth)
3972 debug_print_timestamp(counter_nr, debug_message);
3977 void print_timestamp_init(char *message)
3979 print_timestamp_ext(message, "INIT");
3982 void print_timestamp_time(char *message)
3984 print_timestamp_ext(message, "TIME");
3987 void print_timestamp_done(char *message)
3989 print_timestamp_ext(message, "DONE");