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 #define UUID_BYTES 16
557 #define UUID_CHARS (UUID_BYTES * 2)
558 #define UUID_LENGTH (UUID_CHARS + 4)
560 static unsigned int uuid_random_function(int max)
562 return GetBetterRandom(max);
565 char *getUUIDExt(unsigned int (*random_function)(int max))
567 static char uuid[UUID_LENGTH + 1];
568 int data[UUID_BYTES];
572 for (i = 0; i < UUID_BYTES; i++)
573 data[i] = random_function(256);
575 data[6] = 0x40 | (data[6] & 0x0f);
576 data[8] = 0x80 | (data[8] & 0x3f);
578 for (i = 0; i < UUID_BYTES; i++)
580 sprintf(&uuid[count], "%02x", data[i]);
583 if (i == 3 || i == 5 || i == 7 || i == 9)
584 strcat(&uuid[count++], "-");
592 return getUUIDExt(uuid_random_function);
596 // ----------------------------------------------------------------------------
598 // ----------------------------------------------------------------------------
600 // maximal allowed length of a command line option
601 #define MAX_OPTION_LEN 256
603 static unsigned int getCurrentMS(void)
605 return SDL_GetTicks();
608 static unsigned int mainCounter(int mode)
610 static unsigned int base_ms = 0;
611 unsigned int current_ms;
613 // get current system milliseconds
614 current_ms = getCurrentMS();
616 // reset base timestamp in case of counter reset or wrap-around
617 if (mode == INIT_COUNTER || current_ms < base_ms)
618 base_ms = current_ms;
620 // return milliseconds since last counter reset
621 return current_ms - base_ms;
624 void InitCounter() // set counter back to zero
626 mainCounter(INIT_COUNTER);
629 unsigned int Counter() // get milliseconds since last call of InitCounter()
631 return mainCounter(READ_COUNTER);
634 static void sleep_milliseconds(unsigned int milliseconds_delay)
636 SDL_Delay(milliseconds_delay);
639 void Delay(unsigned int delay) // Sleep specified number of milliseconds
641 sleep_milliseconds(delay);
644 boolean DelayReachedExt2(unsigned int *counter_var, unsigned int delay,
645 unsigned int actual_counter)
647 if (actual_counter >= *counter_var &&
648 actual_counter < *counter_var + delay)
651 *counter_var = actual_counter;
656 boolean DelayReachedExt(DelayCounter *counter, unsigned int actual_counter)
658 return DelayReachedExt2(&counter->count, counter->value, actual_counter);
661 boolean FrameReached(DelayCounter *counter)
663 return DelayReachedExt(counter, FrameCounter);
666 boolean DelayReached(DelayCounter *counter)
668 return DelayReachedExt(counter, Counter());
671 void ResetDelayCounterExt(DelayCounter *counter, unsigned int actual_counter)
673 DelayReachedExt2(&counter->count, 0, actual_counter);
676 void ResetFrameCounter(DelayCounter *counter)
678 ResetDelayCounterExt(counter, FrameCounter);
681 void ResetDelayCounter(DelayCounter *counter)
683 ResetDelayCounterExt(counter, Counter());
686 int WaitUntilDelayReached(DelayCounter *counter)
688 unsigned int *counter_var = &counter->count;
689 unsigned int delay = counter->value;
690 unsigned int actual_counter;
695 actual_counter = Counter();
697 if (actual_counter >= *counter_var &&
698 actual_counter < *counter_var + delay)
699 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
704 if (*counter_var != 0 &&
706 actual_counter >= *counter_var + delay)
708 int lag = actual_counter - (*counter_var + delay);
709 int delay2 = (delay + 1) / 2;
712 skip_frames = (lag + delay2) / delay;
715 *counter_var = actual_counter;
720 void SkipUntilDelayReached(DelayCounter *counter,
721 int *loop_var, int last_loop_value)
723 int skip_frames = WaitUntilDelayReached(counter);
728 Debug("internal:SkipUntilDelayReached",
729 "%d: %d ms -> SKIP %d FRAME(S) [%d ms]",
730 *loop_var, counter->value,
731 skip_frames, skip_frames * counter->value);
733 Debug("internal:SkipUntilDelayReached",
735 *loop_var, counter->value);
739 if (skip_frames == 0)
742 // when skipping frames, make sure to never skip the last frame, as
743 // this may be needed for animations to reach a defined end state;
744 // furthermore, we assume that this function is called at the end
745 // of a "for" loop, which continues by incrementing the loop variable
746 // by one before checking the loop condition again; therefore we have
747 // to check against the last loop value minus one here
751 if (*loop_var < last_loop_value) // never skip the last frame
753 *loop_var += skip_frames;
755 if (*loop_var > last_loop_value) // never skip the last frame
756 *loop_var = last_loop_value;
761 // ----------------------------------------------------------------------------
762 // random generator functions
763 // ----------------------------------------------------------------------------
765 static unsigned int init_random_number_ext(int nr, int seed)
767 if (seed == NEW_RANDOMIZE)
769 // default random seed
770 seed = (int)time(NULL); // seconds since the epoch
772 #if !defined(PLATFORM_WINDOWS)
773 // add some more randomness
774 struct timeval current_time;
776 gettimeofday(¤t_time, NULL);
778 seed += (int)current_time.tv_usec; // microseconds since the epoch
781 // add some more randomness
782 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
784 // add some more randomness
785 seed += GetSimpleRandom(1000000);
788 srandom_linux_libc(nr, (unsigned int) seed);
790 return (unsigned int) seed;
793 static unsigned int prng_seed_gettimeofday(void)
795 struct timeval current_time;
797 gettimeofday(¤t_time, NULL);
799 prng_seed_bytes(¤t_time, sizeof(current_time));
804 unsigned int init_random_number(int nr, int seed)
806 return (nr == RANDOM_BETTER ? prng_seed_gettimeofday() :
807 init_random_number_ext(nr, seed));
810 static unsigned int get_random_number_ext(int nr)
812 return (nr == RANDOM_BETTER ? prng_get_uint() :
813 random_linux_libc(nr));
816 unsigned int get_random_number(int nr, int max)
818 return (max > 0 ? get_random_number_ext(nr) % max : 0);
822 // ----------------------------------------------------------------------------
823 // system info functions
824 // ----------------------------------------------------------------------------
826 #if !defined(PLATFORM_ANDROID)
827 static char *get_corrected_real_name(char *real_name)
829 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
830 char *from_ptr = real_name;
831 char *to_ptr = real_name_new;
833 // copy the name string, but not more than MAX_USERNAME_LEN characters
834 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
836 // the name field read from "passwd" file may also contain additional
837 // user information, separated by commas, which will be removed here
838 if (*from_ptr == ',')
841 // the user's real name may contain 'german sharp s' characters,
842 // which have no equivalent in upper case letters (used by our fonts)
843 if (*from_ptr == CHAR_BYTE_SHARP_S)
850 *to_ptr++ = *from_ptr++;
855 return real_name_new;
859 #if defined(PLATFORM_UNIX)
860 static struct passwd *getPasswdEntry(void)
862 #if defined(PLATFORM_EMSCRIPTEN)
863 // currently not fully supported; force fallback to default values
866 return getpwuid(getuid());
870 char *getUnixLoginName(void)
872 struct passwd *pwd = getPasswdEntry();
874 if (pwd != NULL && strlen(pwd->pw_name) != 0)
880 char *getUnixRealName(void)
882 struct passwd *pwd = getPasswdEntry();
884 if (pwd != NULL && strlen(pwd->pw_gecos) != 0)
885 return pwd->pw_gecos;
890 char *getUnixHomeDir(void)
892 struct passwd *pwd = getPasswdEntry();
894 if (pwd != NULL && strlen(pwd->pw_dir) != 0)
901 char *getLoginName(void)
903 static char *login_name = NULL;
905 #if defined(PLATFORM_WINDOWS)
906 if (login_name == NULL)
908 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
910 login_name = checked_malloc(buffer_size);
912 if (GetUserName(login_name, &buffer_size) == 0)
913 strcpy(login_name, ANONYMOUS_NAME);
915 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
916 if (login_name == NULL)
918 char *name = getUnixLoginName();
921 login_name = getStringCopy(name);
923 login_name = ANONYMOUS_NAME;
926 login_name = ANONYMOUS_NAME;
932 char *getRealName(void)
934 static char *real_name = NULL;
936 #if defined(PLATFORM_WINDOWS)
937 if (real_name == NULL)
939 static char buffer[MAX_USERNAME_LEN + 1];
940 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
942 if (GetUserName(buffer, &buffer_size) != 0)
943 real_name = get_corrected_real_name(buffer);
945 real_name = ANONYMOUS_NAME;
947 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
948 if (real_name == NULL)
950 char *name = getUnixRealName();
953 real_name = get_corrected_real_name(name);
955 real_name = ANONYMOUS_NAME;
958 real_name = ANONYMOUS_NAME;
964 char *getFixedUserName(char *name)
966 // needed because player name must be a fixed length string
967 char *name_new = checked_malloc(MAX_PLAYER_NAME_LEN + 1);
969 strncpy(name_new, name, MAX_PLAYER_NAME_LEN);
970 name_new[MAX_PLAYER_NAME_LEN] = '\0';
972 if (strlen(name) > MAX_PLAYER_NAME_LEN) // name has been cut
973 if (strchr(name_new, ' '))
974 *strchr(name_new, ' ') = '\0';
979 char *getDefaultUserName(int nr)
981 static char *user_name[MAX_PLAYER_NAMES] = { NULL };
983 nr = MIN(MAX(0, nr), MAX_PLAYER_NAMES - 1);
985 if (user_name[nr] == NULL)
987 user_name[nr] = (nr == 0 ? getLoginName() : EMPTY_PLAYER_NAME);
988 user_name[nr] = getFixedUserName(user_name[nr]);
991 return user_name[nr];
994 char *getTimestampFromEpoch(time_t epoch_seconds)
996 struct tm *now = localtime(&epoch_seconds);
997 static char timestamp[20];
999 sprintf(timestamp, "%04d%02d%02d-%02d%02d%02d",
1000 now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
1001 now->tm_hour, now->tm_min, now->tm_sec);
1006 char *getCurrentTimestamp(void)
1008 return getTimestampFromEpoch(time(NULL));
1011 time_t getFileTimestampEpochSeconds(char *filename)
1013 struct stat file_status;
1015 if (stat(filename, &file_status) != 0) // cannot stat file
1018 return file_status.st_mtime;
1022 // ----------------------------------------------------------------------------
1023 // path manipulation functions
1024 // ----------------------------------------------------------------------------
1026 static char *getLastPathSeparatorPtr(char *filename)
1028 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
1030 if (last_separator == NULL) // also try DOS/Windows variant
1031 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
1033 return last_separator;
1036 char *getBaseNamePtr(char *filename)
1038 char *last_separator = getLastPathSeparatorPtr(filename);
1040 if (last_separator != NULL)
1041 return last_separator + 1; // separator found: strip base path
1043 return filename; // no separator found: filename has no path
1046 char *getBaseName(char *filename)
1048 return getStringCopy(getBaseNamePtr(filename));
1051 char *getBaseNameNoSuffix(char *filename)
1053 char *basename = getStringCopy(getBaseNamePtr(filename));
1055 // remove trailing suffix (separated by dot or hyphen)
1056 if (basename[0] != '.' && basename[0] != '-')
1058 if (strchr(basename, '.') != NULL)
1059 *strchr(basename, '.') = '\0';
1061 if (strchr(basename, '-') != NULL)
1062 *strchr(basename, '-') = '\0';
1068 char *getBasePath(char *filename)
1070 char *basepath = getStringCopy(filename);
1071 char *last_separator = getLastPathSeparatorPtr(basepath);
1073 // if no separator was found, use current directory
1074 if (last_separator == NULL)
1078 return getStringCopy(".");
1081 // separator found: strip basename
1082 *last_separator = '\0';
1088 // ----------------------------------------------------------------------------
1089 // various string functions
1090 // ----------------------------------------------------------------------------
1092 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
1094 if (s1 == NULL || s2 == NULL || sep == NULL)
1097 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
1100 sprintf(complete_string, "%s%s%s", s1, sep, s2);
1102 return complete_string;
1105 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
1107 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
1110 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
1111 strlen(s2) + strlen(sep) +
1114 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
1116 return complete_string;
1119 char *getStringCat2(char *s1, char *s2)
1121 return getStringCat2WithSeparator(s1, s2, "");
1124 char *getStringCat3(char *s1, char *s2, char *s3)
1126 return getStringCat3WithSeparator(s1, s2, s3, "");
1129 char *getPath2(char *path1, char *path2)
1131 #if defined(PLATFORM_ANDROID)
1132 // workaround for reading from assets directory -- skip "." subdirs in path
1133 if (strEqual(path1, "."))
1134 return getStringCopy(path2);
1135 else if (strEqual(path2, "."))
1136 return getStringCopy(path1);
1139 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1142 char *getPath3(char *path1, char *path2, char *path3)
1144 #if defined(PLATFORM_ANDROID)
1145 // workaround for reading from assets directory -- skip "." subdirs in path
1146 if (strEqual(path1, "."))
1147 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
1148 else if (strEqual(path2, "."))
1149 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
1150 else if (strEqual(path3, "."))
1151 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1154 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
1157 static char *getPngOrPcxIfNotExists(char *filename)
1159 // switch from PNG to PCX file and vice versa, if file does not exist
1160 // (backwards compatibility with PCX files used in previous versions)
1162 if (!fileExists(filename) && strSuffix(filename, ".png"))
1163 strcpy(&filename[strlen(filename) - 3], "pcx");
1164 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
1165 strcpy(&filename[strlen(filename) - 3], "png");
1170 char *getImg2(char *path1, char *path2)
1172 return getPngOrPcxIfNotExists(getPath2(path1, path2));
1175 char *getImg3(char *path1, char *path2, char *path3)
1177 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
1180 char *getStringCopy(const char *s)
1187 s_copy = checked_malloc(strlen(s) + 1);
1193 char *getStringCopyN(const char *s, int n)
1196 int s_len = MAX(0, n);
1201 s_copy = checked_malloc(s_len + 1);
1202 strncpy(s_copy, s, s_len);
1203 s_copy[s_len] = '\0';
1208 char *getStringCopyNStatic(const char *s, int n)
1210 static char *s_copy = NULL;
1212 checked_free(s_copy);
1214 s_copy = getStringCopyN(s, n);
1219 char *getStringToLower(const char *s)
1221 char *s_copy = checked_malloc(strlen(s) + 1);
1222 char *s_ptr = s_copy;
1225 *s_ptr++ = tolower(*s++);
1231 void setString(char **old_value, char *new_value)
1233 checked_free(*old_value);
1235 *old_value = getStringCopy(new_value);
1238 boolean strEqual(char *s1, char *s2)
1240 return (s1 == NULL && s2 == NULL ? TRUE :
1241 s1 == NULL && s2 != NULL ? FALSE :
1242 s1 != NULL && s2 == NULL ? FALSE :
1243 strcmp(s1, s2) == 0);
1246 boolean strEqualN(char *s1, char *s2, int n)
1248 return (s1 == NULL && s2 == NULL ? TRUE :
1249 s1 == NULL && s2 != NULL ? FALSE :
1250 s1 != NULL && s2 == NULL ? FALSE :
1251 strncmp(s1, s2, n) == 0);
1254 boolean strEqualCase(char *s1, char *s2)
1256 return (s1 == NULL && s2 == NULL ? TRUE :
1257 s1 == NULL && s2 != NULL ? FALSE :
1258 s1 != NULL && s2 == NULL ? FALSE :
1259 strcasecmp(s1, s2) == 0);
1262 boolean strEqualCaseN(char *s1, char *s2, int n)
1264 return (s1 == NULL && s2 == NULL ? TRUE :
1265 s1 == NULL && s2 != NULL ? FALSE :
1266 s1 != NULL && s2 == NULL ? FALSE :
1267 strncasecmp(s1, s2, n) == 0);
1270 boolean strPrefix(char *s, char *prefix)
1272 return (s == NULL && prefix == NULL ? TRUE :
1273 s == NULL && prefix != NULL ? FALSE :
1274 s != NULL && prefix == NULL ? FALSE :
1275 strncmp(s, prefix, strlen(prefix)) == 0);
1278 boolean strSuffix(char *s, char *suffix)
1280 return (s == NULL && suffix == NULL ? TRUE :
1281 s == NULL && suffix != NULL ? FALSE :
1282 s != NULL && suffix == NULL ? FALSE :
1283 strlen(s) < strlen(suffix) ? FALSE :
1284 strcmp(&s[strlen(s) - strlen(suffix)], suffix) == 0);
1287 boolean strPrefixLower(char *s, char *prefix)
1289 char *s_lower = getStringToLower(s);
1290 boolean match = strPrefix(s_lower, prefix);
1297 boolean strSuffixLower(char *s, char *suffix)
1299 char *s_lower = getStringToLower(s);
1300 boolean match = strSuffix(s_lower, suffix);
1307 boolean isURL(char *s)
1309 while (*s && *s >= 'a' && *s <= 'z')
1312 return strPrefix(s, "://");
1316 // ----------------------------------------------------------------------------
1317 // command line option handling functions
1318 // ----------------------------------------------------------------------------
1320 void GetOptions(int argc, char *argv[],
1321 void (*print_usage_function)(void),
1322 void (*print_version_function)(void))
1324 char *base_path = getProgramMainDataPath(argv[0], BASE_PATH);
1325 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
1326 char **options_left = &argvplus[1];
1328 // replace original "argv" with null-terminated array of string pointers
1330 argvplus[argc] = argv[argc];
1332 // initialize global program options
1333 options.server_host = NULL;
1334 options.server_port = 0;
1336 options.base_directory = base_path;
1338 options.level_directory = getPath2(base_path, LEVELS_DIRECTORY);
1339 options.graphics_directory = getPath2(base_path, GRAPHICS_DIRECTORY);
1340 options.sounds_directory = getPath2(base_path, SOUNDS_DIRECTORY);
1341 options.music_directory = getPath2(base_path, MUSIC_DIRECTORY);
1342 options.docs_directory = getPath2(base_path, DOCS_DIRECTORY);
1343 options.conf_directory = getPath2(base_path, CONF_DIRECTORY);
1345 options.execute_command = NULL;
1346 options.tape_log_filename = NULL;
1347 options.special_flags = NULL;
1348 options.debug_mode = NULL;
1349 options.player_name = NULL;
1350 options.identifier = NULL;
1351 options.level_nr = NULL;
1353 options.display_nr = 0;
1355 options.mytapes = FALSE;
1356 options.serveronly = FALSE;
1357 options.network = FALSE;
1358 options.verbose = FALSE;
1359 options.debug = FALSE;
1362 options.verbose = TRUE;
1364 #if !defined(PLATFORM_UNIX)
1365 if (*options_left == NULL) // no options given -- enable verbose mode
1366 options.verbose = TRUE;
1371 #if defined(PLATFORM_ANDROID)
1372 options.debug = TRUE;
1376 while (*options_left)
1378 char option_str[MAX_OPTION_LEN];
1379 char *option = options_left[0];
1380 char *next_option = options_left[1];
1381 char *option_arg = NULL;
1382 int option_len = strlen(option);
1384 if (option_len >= MAX_OPTION_LEN)
1385 FailWithHelp("unrecognized option '%s'", option);
1387 strcpy(option_str, option); // copy argument into buffer
1388 option = option_str;
1390 if (strEqual(option, "--")) // stop scanning arguments
1393 if (strPrefix(option, "--")) // treat '--' like '-'
1396 option_arg = strchr(option, '=');
1397 if (option_arg == NULL) // no '=' in option
1398 option_arg = next_option;
1401 *option_arg++ = '\0'; // cut argument from option
1402 if (*option_arg == '\0') // no argument after '='
1403 FailWithHelp("option '%s' has invalid argument", option_str);
1406 option_len = strlen(option);
1408 if (strEqual(option, "-"))
1410 FailWithHelp("unrecognized option '%s'", option);
1412 else if (strncmp(option, "-help", option_len) == 0)
1414 print_usage_function();
1418 else if (strncmp(option, "-basepath", option_len) == 0)
1420 if (option_arg == NULL)
1421 FailWithHelp("option '%s' requires an argument", option_str);
1423 options.base_directory = base_path = getStringCopy(option_arg);
1424 if (option_arg == next_option)
1427 // adjust paths for sub-directories in base directory accordingly
1428 options.level_directory = getPath2(base_path, LEVELS_DIRECTORY);
1429 options.graphics_directory = getPath2(base_path, GRAPHICS_DIRECTORY);
1430 options.sounds_directory = getPath2(base_path, SOUNDS_DIRECTORY);
1431 options.music_directory = getPath2(base_path, MUSIC_DIRECTORY);
1432 options.docs_directory = getPath2(base_path, DOCS_DIRECTORY);
1433 options.conf_directory = getPath2(base_path, CONF_DIRECTORY);
1435 else if (strncmp(option, "-levels", option_len) == 0)
1437 if (option_arg == NULL)
1438 FailWithHelp("option '%s' requires an argument", option_str);
1440 options.level_directory = getStringCopy(option_arg);
1441 if (option_arg == next_option)
1444 else if (strncmp(option, "-graphics", option_len) == 0)
1446 if (option_arg == NULL)
1447 FailWithHelp("option '%s' requires an argument", option_str);
1449 options.graphics_directory = getStringCopy(option_arg);
1450 if (option_arg == next_option)
1453 else if (strncmp(option, "-sounds", option_len) == 0)
1455 if (option_arg == NULL)
1456 FailWithHelp("option '%s' requires an argument", option_str);
1458 options.sounds_directory = getStringCopy(option_arg);
1459 if (option_arg == next_option)
1462 else if (strncmp(option, "-music", option_len) == 0)
1464 if (option_arg == NULL)
1465 FailWithHelp("option '%s' requires an argument", option_str);
1467 options.music_directory = getStringCopy(option_arg);
1468 if (option_arg == next_option)
1471 else if (strncmp(option, "-mytapes", option_len) == 0)
1473 options.mytapes = TRUE;
1475 else if (strncmp(option, "-network", option_len) == 0)
1477 options.network = TRUE;
1479 else if (strncmp(option, "-serveronly", option_len) == 0)
1481 options.serveronly = TRUE;
1483 else if (strncmp(option, "-debug", option_len) == 0)
1485 options.debug = TRUE;
1487 // optionally, debug output can be limited to a specific debug mode
1488 if (option_arg != next_option)
1489 options.debug_mode = getStringCopy(option_arg);
1491 else if (strncmp(option, "-player-name", option_len) == 0)
1493 if (option_arg == NULL)
1494 FailWithHelp("option '%s' requires an argument", option_str);
1496 options.player_name = getStringCopy(option_arg);
1497 if (option_arg == next_option)
1500 else if (strncmp(option, "-identifier", option_len) == 0)
1502 if (option_arg == NULL)
1503 FailWithHelp("option '%s' requires an argument", option_str);
1505 options.identifier = getStringCopy(option_arg);
1506 if (option_arg == next_option)
1509 else if (strncmp(option, "-level-nr", option_len) == 0)
1511 if (option_arg == NULL)
1512 FailWithHelp("option '%s' requires an argument", option_str);
1514 options.level_nr = getStringCopy(option_arg);
1515 if (option_arg == next_option)
1518 else if (strncmp(option, "-verbose", option_len) == 0)
1520 options.verbose = TRUE;
1522 else if (strncmp(option, "-version", option_len) == 0 ||
1523 strncmp(option, "-V", option_len) == 0)
1525 print_version_function();
1529 else if (strPrefix(option, "-D"))
1531 options.special_flags = getStringCopy(&option[2]);
1533 else if (strncmp(option, "-execute", option_len) == 0)
1535 if (option_arg == NULL)
1536 FailWithHelp("option '%s' requires an argument", option_str);
1538 options.execute_command = getStringCopy(option_arg);
1539 if (option_arg == next_option)
1542 // when doing batch processing, always enable verbose mode (warnings)
1543 options.verbose = TRUE;
1545 else if (strncmp(option, "-tape_logfile", option_len) == 0)
1547 if (option_arg == NULL)
1548 FailWithHelp("option '%s' requires an argument", option_str);
1550 options.tape_log_filename = getStringCopy(option_arg);
1551 if (option_arg == next_option)
1554 else if (strncmp(option, "-display", option_len) == 0)
1556 if (option_arg == NULL)
1557 FailWithHelp("option '%s' requires an argument", option_str);
1559 if (option_arg == next_option)
1562 int display_nr = atoi(option_arg);
1565 // dirty hack: SDL_GetNumVideoDisplays() seems broken on some systems
1566 options.display_nr = display_nr;
1568 options.display_nr =
1569 MAX(0, MIN(display_nr, SDL_GetNumVideoDisplays() - 1));
1571 if (display_nr != options.display_nr)
1572 Warn("invalid display %d -- using display %d",
1573 display_nr, options.display_nr);
1576 #if defined(PLATFORM_MAC)
1577 else if (strPrefix(option, "-psn"))
1579 // ignore process serial number when launched via GUI on Mac OS X
1582 else if (*option == '-')
1584 FailWithHelp("unrecognized option '%s'", option_str);
1586 else if (options.server_host == NULL)
1588 options.server_host = *options_left;
1590 else if (options.server_port == 0)
1592 options.server_port = atoi(*options_left);
1593 if (options.server_port < 1024)
1594 FailWithHelp("bad port number '%d'", options.server_port);
1597 FailWithHelp("too many arguments");
1604 // ----------------------------------------------------------------------------
1605 // checked memory allocation and freeing functions
1606 // ----------------------------------------------------------------------------
1608 void *checked_malloc(unsigned int size)
1615 Fail("cannot allocate %d bytes -- out of memory", size);
1620 void *checked_calloc(unsigned int size)
1624 ptr = calloc(1, size);
1627 Fail("cannot allocate %d bytes -- out of memory", size);
1632 void *checked_realloc(void *ptr, unsigned int size)
1634 ptr = realloc(ptr, size);
1637 Fail("cannot allocate %d bytes -- out of memory", size);
1642 void checked_free(void *ptr)
1644 if (ptr != NULL) // this check should be done by free() anyway
1648 void clear_mem(void *ptr, unsigned int size)
1650 #if defined(PLATFORM_WINDOWS)
1651 // for unknown reason, memset() sometimes crashes when compiled with MinGW
1652 char *cptr = (char *)ptr;
1657 memset(ptr, 0, size);
1662 // ----------------------------------------------------------------------------
1663 // various helper functions
1664 // ----------------------------------------------------------------------------
1666 void swap_numbers(int *i1, int *i2)
1674 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1686 /* the "put" variants of the following file access functions check for the file
1687 pointer being != NULL and return the number of bytes they have or would have
1688 written; this allows for chunk writing functions to first determine the size
1689 of the (not yet written) chunk, write the correct chunk size and finally
1690 write the chunk itself */
1692 int getFile8BitInteger(File *file)
1694 return getByteFromFile(file);
1697 int putFile8BitInteger(FILE *file, int value)
1705 int getFile16BitInteger(File *file, int byte_order)
1707 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1708 return ((getByteFromFile(file) << 8) |
1709 (getByteFromFile(file) << 0));
1710 else // BYTE_ORDER_LITTLE_ENDIAN
1711 return ((getByteFromFile(file) << 0) |
1712 (getByteFromFile(file) << 8));
1715 int putFile16BitInteger(FILE *file, int value, int byte_order)
1719 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1721 fputc((value >> 8) & 0xff, file);
1722 fputc((value >> 0) & 0xff, file);
1724 else // BYTE_ORDER_LITTLE_ENDIAN
1726 fputc((value >> 0) & 0xff, file);
1727 fputc((value >> 8) & 0xff, file);
1734 int getFile32BitInteger(File *file, int byte_order)
1736 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1737 return ((getByteFromFile(file) << 24) |
1738 (getByteFromFile(file) << 16) |
1739 (getByteFromFile(file) << 8) |
1740 (getByteFromFile(file) << 0));
1741 else // BYTE_ORDER_LITTLE_ENDIAN
1742 return ((getByteFromFile(file) << 0) |
1743 (getByteFromFile(file) << 8) |
1744 (getByteFromFile(file) << 16) |
1745 (getByteFromFile(file) << 24));
1748 int putFile32BitInteger(FILE *file, int value, int byte_order)
1752 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1754 fputc((value >> 24) & 0xff, file);
1755 fputc((value >> 16) & 0xff, file);
1756 fputc((value >> 8) & 0xff, file);
1757 fputc((value >> 0) & 0xff, file);
1759 else // BYTE_ORDER_LITTLE_ENDIAN
1761 fputc((value >> 0) & 0xff, file);
1762 fputc((value >> 8) & 0xff, file);
1763 fputc((value >> 16) & 0xff, file);
1764 fputc((value >> 24) & 0xff, file);
1771 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1774 const int chunk_name_length = 4;
1777 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1780 if (chunk_size != NULL)
1783 *chunk_size = getFile32BitInteger(file, byte_order);
1786 return (checkEndOfFile(file) ? FALSE : TRUE);
1789 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1796 fputs(chunk_name, file);
1798 num_bytes += strlen(chunk_name);
1800 if (chunk_size >= 0)
1804 putFile32BitInteger(file, chunk_size, byte_order);
1812 int getFileVersion(File *file)
1814 int version_super = getByteFromFile(file);
1815 int version_major = getByteFromFile(file);
1816 int version_minor = getByteFromFile(file);
1817 int version_patch = getByteFromFile(file);
1819 return VERSION_IDENT(version_super, version_major, version_minor,
1823 int putFileVersion(FILE *file, int version)
1827 int version_super = VERSION_SUPER(version);
1828 int version_major = VERSION_MAJOR(version);
1829 int version_minor = VERSION_MINOR(version);
1830 int version_patch = VERSION_PATCH(version);
1832 fputc(version_super, file);
1833 fputc(version_major, file);
1834 fputc(version_minor, file);
1835 fputc(version_patch, file);
1841 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1845 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1846 buffer[i] = getByteFromFile(file);
1849 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1853 for (i = 0; i < bytes; i++)
1854 fputc(buffer[i], file);
1857 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1859 while (bytes-- && !checkEndOfFile(file))
1860 getByteFromFile(file);
1863 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1870 // ----------------------------------------------------------------------------
1871 // functions to convert between ISO-8859-1 and UTF-8
1872 // ----------------------------------------------------------------------------
1874 char *getUTF8FromLatin1(char *latin1)
1876 int max_utf8_size = 2 * strlen(latin1) + 1;
1877 char *utf8 = checked_calloc(max_utf8_size);
1878 unsigned char *src = (unsigned char *)latin1;
1879 unsigned char *dst = (unsigned char *)utf8;
1883 if (*src < 128) // pure 7-bit ASCII
1887 else if (*src >= 160) // non-ASCII characters
1889 *dst++ = 194 + (*src >= 192);
1890 *dst++ = 128 + (*src & 63);
1892 else // undefined in ISO-8859-1
1900 // only use the smallest possible string buffer size
1901 utf8 = checked_realloc(utf8, strlen(utf8) + 1);
1906 char *getLatin1FromUTF8(char *utf8)
1908 int max_latin1_size = strlen(utf8) + 1;
1909 char *latin1 = checked_calloc(max_latin1_size);
1910 unsigned char *src = (unsigned char *)utf8;
1911 unsigned char *dst = (unsigned char *)latin1;
1915 if (*src < 128) // pure 7-bit ASCII
1919 else if (src[0] == 194 &&
1920 src[1] >= 128 && src[1] < 192) // non-ASCII characters
1925 else if (src[0] == 195 &&
1926 src[1] >= 128 && src[1] < 192) // non-ASCII characters
1928 *dst++ = src[1] + 64;
1932 // all other UTF-8 characters are undefined in ISO-8859-1
1934 else if (src[0] >= 192 && src[0] < 224 &&
1935 src[1] >= 128 && src[1] < 192)
1940 else if (src[0] >= 224 && src[0] < 240 &&
1941 src[1] >= 128 && src[1] < 192 &&
1942 src[2] >= 128 && src[2] < 192)
1947 else if (src[0] >= 240 && src[0] < 248 &&
1948 src[1] >= 128 && src[1] < 192 &&
1949 src[2] >= 128 && src[2] < 192 &&
1950 src[3] >= 128 && src[3] < 192)
1955 else if (src[0] >= 248 && src[0] < 252 &&
1956 src[1] >= 128 && src[1] < 192 &&
1957 src[2] >= 128 && src[2] < 192 &&
1958 src[3] >= 128 && src[3] < 192 &&
1959 src[4] >= 128 && src[4] < 192)
1964 else if (src[0] >= 252 && src[0] < 254 &&
1965 src[1] >= 128 && src[1] < 192 &&
1966 src[2] >= 128 && src[2] < 192 &&
1967 src[3] >= 128 && src[3] < 192 &&
1968 src[4] >= 128 && src[4] < 192 &&
1969 src[5] >= 128 && src[5] < 192)
1981 // only use the smallest possible string buffer size
1982 latin1 = checked_realloc(latin1, strlen(latin1) + 1);
1987 int getTextEncoding(char *text)
1989 unsigned char *src = (unsigned char *)text;
1990 int encoding = TEXT_ENCODING_ASCII; // default: assume encoding is ASCII
1995 encoding = TEXT_ENCODING_UTF_8; // non-ASCII character: assume UTF-8
2001 else if (src[0] >= 192 && src[0] < 224 &&
2002 src[1] >= 128 && src[1] < 192)
2006 else if (src[0] >= 224 && src[0] < 240 &&
2007 src[1] >= 128 && src[1] < 192 &&
2008 src[2] >= 128 && src[2] < 192)
2012 else if (src[0] >= 240 && src[0] < 248 &&
2013 src[1] >= 128 && src[1] < 192 &&
2014 src[2] >= 128 && src[2] < 192 &&
2015 src[3] >= 128 && src[3] < 192)
2019 else if (src[0] >= 248 && src[0] < 252 &&
2020 src[1] >= 128 && src[1] < 192 &&
2021 src[2] >= 128 && src[2] < 192 &&
2022 src[3] >= 128 && src[3] < 192 &&
2023 src[4] >= 128 && src[4] < 192)
2027 else if (src[0] >= 252 && src[0] < 254 &&
2028 src[1] >= 128 && src[1] < 192 &&
2029 src[2] >= 128 && src[2] < 192 &&
2030 src[3] >= 128 && src[3] < 192 &&
2031 src[4] >= 128 && src[4] < 192 &&
2032 src[5] >= 128 && src[5] < 192)
2038 return TEXT_ENCODING_UNKNOWN; // non-UTF-8 character: unknown encoding
2046 // ----------------------------------------------------------------------------
2047 // functions for JSON handling
2048 // ----------------------------------------------------------------------------
2050 char *getEscapedJSON(char *s)
2052 int max_json_size = 2 * strlen(s) + 1;
2053 char *json = checked_calloc(max_json_size);
2054 unsigned char *src = (unsigned char *)s;
2055 unsigned char *dst = (unsigned char *)json;
2056 char *escaped[256] =
2069 if (escaped[*src] != NULL)
2071 char *esc = escaped[*src++];
2082 // only use the smallest possible string buffer size
2083 json = checked_realloc(json, strlen(json) + 1);
2089 // ----------------------------------------------------------------------------
2090 // functions to translate key identifiers between different format
2091 // ----------------------------------------------------------------------------
2093 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
2094 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
2095 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
2096 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
2098 static void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
2107 // return and escape keys
2108 { KSYM_Return, "XK_Return", "return" },
2109 { KSYM_Escape, "XK_Escape", "escape" },
2111 // normal cursor keys
2112 { KSYM_Left, "XK_Left", "cursor left" },
2113 { KSYM_Right, "XK_Right", "cursor right" },
2114 { KSYM_Up, "XK_Up", "cursor up" },
2115 { KSYM_Down, "XK_Down", "cursor down" },
2117 // keypad cursor keys
2119 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
2120 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
2121 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
2122 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
2125 // other keypad keys
2126 #ifdef KSYM_KP_Enter
2127 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
2128 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
2129 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
2130 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
2131 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
2132 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
2136 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
2137 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
2138 { KSYM_Control_L, "XK_Control_L", "left control" },
2139 { KSYM_Control_R, "XK_Control_R", "right control" },
2140 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
2141 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
2142 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
2143 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
2144 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, // Alt-R
2145 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, // Ctrl-R
2147 // some special keys
2148 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
2149 { KSYM_Delete, "XK_Delete", "delete" },
2150 { KSYM_Insert, "XK_Insert", "insert" },
2151 { KSYM_Tab, "XK_Tab", "tab" },
2152 { KSYM_Home, "XK_Home", "home" },
2153 { KSYM_End, "XK_End", "end" },
2154 { KSYM_Page_Up, "XK_Page_Up", "page up" },
2155 { KSYM_Page_Down, "XK_Page_Down", "page down" },
2157 { KSYM_Select, "XK_Select", "select" },
2158 { KSYM_Menu, "XK_Menu", "menu" }, // menu key
2159 { KSYM_Back, "XK_Back", "back" }, // back key
2160 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
2161 #if defined(PLATFORM_ANDROID)
2162 { KSYM_Rewind, "XK_Rewind", "rewind" },
2163 { KSYM_FastForward, "XK_FastForward", "fast forward" },
2166 // ASCII 0x20 to 0x40 keys (except numbers)
2167 { KSYM_space, "XK_space", "space" },
2168 { KSYM_exclam, "XK_exclam", "!" },
2169 { KSYM_quotedbl, "XK_quotedbl", "\"" },
2170 { KSYM_numbersign, "XK_numbersign", "#" },
2171 { KSYM_dollar, "XK_dollar", "$" },
2172 { KSYM_percent, "XK_percent", "%" },
2173 { KSYM_ampersand, "XK_ampersand", "&" },
2174 { KSYM_apostrophe, "XK_apostrophe", "'" },
2175 { KSYM_parenleft, "XK_parenleft", "(" },
2176 { KSYM_parenright, "XK_parenright", ")" },
2177 { KSYM_asterisk, "XK_asterisk", "*" },
2178 { KSYM_plus, "XK_plus", "+" },
2179 { KSYM_comma, "XK_comma", "," },
2180 { KSYM_minus, "XK_minus", "-" },
2181 { KSYM_period, "XK_period", "." },
2182 { KSYM_slash, "XK_slash", "/" },
2183 { KSYM_colon, "XK_colon", ":" },
2184 { KSYM_semicolon, "XK_semicolon", ";" },
2185 { KSYM_less, "XK_less", "<" },
2186 { KSYM_equal, "XK_equal", "=" },
2187 { KSYM_greater, "XK_greater", ">" },
2188 { KSYM_question, "XK_question", "?" },
2189 { KSYM_at, "XK_at", "@" },
2192 { KSYM_bracketleft, "XK_bracketleft", "[" },
2193 { KSYM_backslash, "XK_backslash", "\\" },
2194 { KSYM_bracketright,"XK_bracketright", "]" },
2195 { KSYM_asciicircum, "XK_asciicircum", "^" },
2196 { KSYM_underscore, "XK_underscore", "_" },
2197 { KSYM_grave, "XK_grave", "grave" },
2198 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
2199 { KSYM_braceleft, "XK_braceleft", "brace left" },
2200 { KSYM_bar, "XK_bar", "bar" },
2201 { KSYM_braceright, "XK_braceright", "brace right" },
2202 { KSYM_asciitilde, "XK_asciitilde", "~" },
2204 // special (non-ASCII) keys
2205 { KSYM_degree, "XK_degree", "degree" },
2206 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
2207 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
2208 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
2209 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
2210 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
2211 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
2212 { KSYM_ssharp, "XK_ssharp", "sharp s" },
2214 // special (non-ASCII) keys (UTF-8, for reverse mapping only)
2215 { KSYM_degree, "XK_degree", "\xc2\xb0" },
2216 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
2217 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
2218 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
2219 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
2220 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
2221 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
2222 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
2224 // other keys (for reverse mapping only)
2225 { KSYM_space, "XK_space", " " },
2227 // keypad keys are not in numerical order in SDL2
2228 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
2229 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
2230 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
2231 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
2232 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
2233 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
2234 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
2235 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
2236 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
2237 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
2239 // end-of-array identifier
2245 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
2247 static char name_buffer[30];
2250 if (key >= KSYM_A && key <= KSYM_Z)
2251 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
2252 else if (key >= KSYM_a && key <= KSYM_z)
2253 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
2254 else if (key >= KSYM_0 && key <= KSYM_9)
2255 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
2256 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
2257 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
2258 else if (key == KSYM_UNDEFINED)
2259 strcpy(name_buffer, "(undefined)");
2266 if (key == translate_key[i].key)
2268 strcpy(name_buffer, translate_key[i].name);
2272 while (translate_key[++i].name);
2274 if (!translate_key[i].name)
2275 strcpy(name_buffer, "(unknown)");
2278 *name = name_buffer;
2280 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
2282 static char name_buffer[30];
2285 if (key >= KSYM_A && key <= KSYM_Z)
2286 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
2287 else if (key >= KSYM_a && key <= KSYM_z)
2288 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
2289 else if (key >= KSYM_0 && key <= KSYM_9)
2290 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
2291 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
2292 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
2293 else if (key == KSYM_UNDEFINED)
2294 strcpy(name_buffer, "[undefined]");
2301 if (key == translate_key[i].key)
2303 strcpy(name_buffer, translate_key[i].x11name);
2307 while (translate_key[++i].x11name);
2309 if (!translate_key[i].x11name)
2310 sprintf(name_buffer, "0x%04x", (unsigned int)key);
2313 *x11name = name_buffer;
2315 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
2317 Key key = KSYM_UNDEFINED;
2318 char *name_ptr = *name;
2320 if (strlen(*name) == 1)
2322 char c = name_ptr[0];
2324 if (c >= 'A' && c <= 'Z')
2325 key = KSYM_A + (Key)(c - 'A');
2326 else if (c >= 'a' && c <= 'z')
2327 key = KSYM_a + (Key)(c - 'a');
2328 else if (c >= '0' && c <= '9')
2329 key = KSYM_0 + (Key)(c - '0');
2332 if (key == KSYM_UNDEFINED)
2338 if (strEqual(translate_key[i].name, *name))
2340 key = translate_key[i].key;
2344 while (translate_key[++i].x11name);
2347 if (key == KSYM_UNDEFINED)
2348 Warn("getKeyFromKeyName(): not completely implemented");
2352 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
2354 Key key = KSYM_UNDEFINED;
2355 char *name_ptr = *x11name;
2357 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
2359 char c = name_ptr[3];
2361 if (c >= 'A' && c <= 'Z')
2362 key = KSYM_A + (Key)(c - 'A');
2363 else if (c >= 'a' && c <= 'z')
2364 key = KSYM_a + (Key)(c - 'a');
2365 else if (c >= '0' && c <= '9')
2366 key = KSYM_0 + (Key)(c - '0');
2368 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
2370 char c1 = name_ptr[4];
2371 char c2 = name_ptr[5];
2374 if ((c1 >= '0' && c1 <= '9') &&
2375 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
2376 d = atoi(&name_ptr[4]);
2378 if (d >= 1 && d <= KSYM_NUM_FKEYS)
2379 key = KSYM_F1 + (Key)(d - 1);
2381 else if (strPrefix(name_ptr, "XK_"))
2387 if (strEqual(name_ptr, translate_key[i].x11name))
2389 key = translate_key[i].key;
2393 while (translate_key[++i].x11name);
2395 else if (strPrefix(name_ptr, "0x"))
2397 unsigned int value = 0;
2403 char c = *name_ptr++;
2406 if (c >= '0' && c <= '9')
2408 else if (c >= 'a' && c <= 'f')
2409 d = (int)(c - 'a' + 10);
2410 else if (c >= 'A' && c <= 'F')
2411 d = (int)(c - 'A' + 10);
2419 value = value * 16 + d;
2430 char *getKeyNameFromKey(Key key)
2434 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
2438 char *getX11KeyNameFromKey(Key key)
2442 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
2446 Key getKeyFromKeyName(char *name)
2450 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
2454 Key getKeyFromX11KeyName(char *x11name)
2458 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
2462 char getCharFromKey(Key key)
2468 } translate_key_char[] =
2470 // special (non-ASCII) keys (ISO-8859-1)
2471 { KSYM_degree, CHAR_BYTE_DEGREE },
2472 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
2473 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
2474 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
2475 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
2476 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
2477 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
2478 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
2480 // end-of-array identifier
2484 char *keyname = getKeyNameFromKey(key);
2487 if (strlen(keyname) == 1)
2489 else if (strEqual(keyname, "space"))
2497 if (key == translate_key_char[i].key)
2499 c = translate_key_char[i].key_char;
2504 while (translate_key_char[++i].key_char);
2510 char getValidConfigValueChar(char c)
2512 if (c == '#' || // used to mark comments
2513 c == '\\') // used to mark continued lines
2520 // ----------------------------------------------------------------------------
2521 // functions to translate string identifiers to integer or boolean value
2522 // ----------------------------------------------------------------------------
2524 int get_integer_from_string(char *s)
2526 // check for the most common case first
2527 if (s[0] >= '0' && s[0] <= '9')
2530 char *s_lower = getStringToLower(s);
2533 if (strEqual(s_lower, "false") ||
2534 strEqual(s_lower, "no") ||
2535 strEqual(s_lower, "off"))
2537 else if (strEqual(s_lower, "true") ||
2538 strEqual(s_lower, "yes") ||
2539 strEqual(s_lower, "on"))
2549 boolean get_boolean_from_string(char *s)
2551 char *s_lower = getStringToLower(s);
2552 boolean result = FALSE;
2554 if (strEqual(s_lower, "true") ||
2555 strEqual(s_lower, "yes") ||
2556 strEqual(s_lower, "on") ||
2557 get_integer_from_string(s) == 1)
2565 int get_switch3_from_string(char *s)
2567 char *s_lower = getStringToLower(s);
2570 if (strEqual(s_lower, "true") ||
2571 strEqual(s_lower, "yes") ||
2572 strEqual(s_lower, "on") ||
2573 get_integer_from_string(s) == 1)
2575 else if (strEqual(s_lower, "auto"))
2583 int get_player_nr_from_string(char *s)
2585 static char *player_text[] =
2595 char *s_lower = getStringToLower(s);
2599 for (i = 0; player_text[i] != NULL; i++)
2600 if (strEqual(s_lower, player_text[i]))
2609 // ----------------------------------------------------------------------------
2610 // functions for generic lists
2611 // ----------------------------------------------------------------------------
2613 ListNode *newListNode(void)
2615 return checked_calloc(sizeof(ListNode));
2618 void addNodeToList(ListNode **node_first, char *key, void *content)
2620 ListNode *node_new = newListNode();
2622 node_new->key = getStringCopy(key);
2623 node_new->content = content;
2624 node_new->next = *node_first;
2627 (*node_first)->prev = node_new;
2629 *node_first = node_new;
2632 void deleteNodeFromList(ListNode **node_first, char *key,
2633 void (*destructor_function)(void *))
2635 if (node_first == NULL || *node_first == NULL)
2638 if (strEqual((*node_first)->key, key))
2640 // after first recursion, (*node_first)->prev->next == *node_first,
2641 // so *node_first would be overwritten with (*node_first)->next
2642 // => use a copy of *node_first (and later of (*node_first)->next)
2643 ListNode *node = *node_first;
2644 ListNode *node_next = node->next;
2646 checked_free(node->key);
2648 if (destructor_function)
2649 destructor_function(node->content);
2652 node->prev->next = node->next;
2655 node->next->prev = node->prev;
2659 // after removing node, set list pointer to next valid list node
2660 // (this is important if the first node of the list was deleted)
2661 *node_first = node_next;
2665 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2669 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2671 if (node_first == NULL)
2674 if (strEqual(node_first->key, key))
2677 return getNodeFromKey(node_first->next, key);
2680 int getNumNodes(ListNode *node_first)
2682 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2686 static void dumpList(ListNode *node_first)
2688 ListNode *node = node_first;
2692 Debug("internal:dumpList", "['%s' (%d)]", node->key,
2693 ((struct ListNodeInfo *)node->content)->num_references);
2697 Debug("internal:dumpList", "[%d nodes]", getNumNodes(node_first));
2702 // ----------------------------------------------------------------------------
2703 // functions for file handling
2704 // ----------------------------------------------------------------------------
2706 #define MAX_BUFFER_SIZE 4096
2708 File *openFile(char *filename, char *mode)
2710 File *file = checked_calloc(sizeof(File));
2712 file->file = fopen(filename, mode);
2714 if (file->file != NULL)
2716 file->filename = getStringCopy(filename);
2721 #if defined(PLATFORM_ANDROID)
2722 file->asset_file = SDL_RWFromFile(filename, mode);
2724 if (file->asset_file != NULL)
2726 file->file_is_asset = TRUE;
2727 file->filename = getStringCopy(filename);
2738 int closeFile(File *file)
2745 #if defined(PLATFORM_ANDROID)
2746 if (file->asset_file)
2747 result = SDL_RWclose(file->asset_file);
2751 result = fclose(file->file);
2753 checked_free(file->filename);
2759 int checkEndOfFile(File *file)
2761 #if defined(PLATFORM_ANDROID)
2762 if (file->file_is_asset)
2763 return file->end_of_file;
2766 return feof(file->file);
2769 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2771 #if defined(PLATFORM_ANDROID)
2772 if (file->file_is_asset)
2774 if (file->end_of_file)
2777 size_t num_items_read =
2778 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2780 if (num_items_read < num_items)
2781 file->end_of_file = TRUE;
2783 return num_items_read;
2787 return fread(buffer, item_size, num_items, file->file);
2790 size_t writeFile(File *file, void *buffer, size_t item_size, size_t num_items)
2792 return fwrite(buffer, item_size, num_items, file->file);
2795 int seekFile(File *file, long offset, int whence)
2797 #if defined(PLATFORM_ANDROID)
2798 if (file->file_is_asset)
2800 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2801 whence == SEEK_CUR ? RW_SEEK_CUR :
2802 whence == SEEK_END ? RW_SEEK_END : 0);
2804 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2808 return fseek(file->file, offset, whence);
2811 int getByteFromFile(File *file)
2813 #if defined(PLATFORM_ANDROID)
2814 if (file->file_is_asset)
2816 if (file->end_of_file)
2820 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2822 if (num_bytes_read < 1)
2823 file->end_of_file = TRUE;
2825 return (file->end_of_file ? EOF : (int)c);
2829 return fgetc(file->file);
2832 char *getStringFromFile(File *file, char *line, int size)
2834 #if defined(PLATFORM_ANDROID)
2835 if (file->file_is_asset)
2837 if (file->end_of_file)
2840 char *line_ptr = line;
2841 int num_bytes_read = 0;
2843 while (num_bytes_read < size - 1 &&
2844 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2845 *line_ptr++ != '\n')
2850 if (strlen(line) == 0)
2852 file->end_of_file = TRUE;
2861 return fgets(line, size, file->file);
2864 int copyFile(char *filename_from, char *filename_to)
2866 File *file_from, *file_to;
2868 if ((file_from = openFile(filename_from, MODE_READ)) == NULL)
2873 if ((file_to = openFile(filename_to, MODE_WRITE)) == NULL)
2875 closeFile(file_from);
2880 while (!checkEndOfFile(file_from))
2882 byte buffer[MAX_BUFFER_SIZE];
2883 size_t bytes_read = readFile(file_from, buffer, 1, MAX_BUFFER_SIZE);
2885 writeFile(file_to, buffer, 1, bytes_read);
2888 closeFile(file_from);
2894 boolean touchFile(char *filename)
2898 if (!(file = fopen(filename, MODE_WRITE)))
2900 Warn("cannot touch file '%s'", filename);
2911 // ----------------------------------------------------------------------------
2912 // functions for directory handling
2913 // ----------------------------------------------------------------------------
2915 Directory *openDirectory(char *dir_name)
2917 Directory *dir = checked_calloc(sizeof(Directory));
2919 dir->dir = opendir(dir_name);
2921 if (dir->dir != NULL)
2923 dir->filename = getStringCopy(dir_name);
2928 #if defined(PLATFORM_ANDROID)
2929 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2931 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2933 checked_free(asset_toc_filename);
2935 if (dir->asset_toc_file != NULL)
2937 dir->directory_is_asset = TRUE;
2938 dir->filename = getStringCopy(dir_name);
2949 int closeDirectory(Directory *dir)
2956 #if defined(PLATFORM_ANDROID)
2957 if (dir->asset_toc_file)
2958 result = SDL_RWclose(dir->asset_toc_file);
2962 result = closedir(dir->dir);
2965 freeDirectoryEntry(dir->dir_entry);
2967 checked_free(dir->filename);
2973 DirectoryEntry *readDirectory(Directory *dir)
2976 freeDirectoryEntry(dir->dir_entry);
2978 dir->dir_entry = NULL;
2980 #if defined(PLATFORM_ANDROID)
2981 if (dir->directory_is_asset)
2983 char line[MAX_LINE_LEN];
2984 char *line_ptr = line;
2985 int num_bytes_read = 0;
2987 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2988 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2997 if (strlen(line) == 0)
3000 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
3002 dir->dir_entry->is_directory = FALSE;
3003 if (line[strlen(line) - 1] == '/')
3005 dir->dir_entry->is_directory = TRUE;
3007 line[strlen(line) - 1] = '\0';
3010 dir->dir_entry->basename = getStringCopy(line);
3011 dir->dir_entry->filename = getPath2(dir->filename, line);
3013 return dir->dir_entry;
3017 struct dirent *dir_entry = readdir(dir->dir);
3019 if (dir_entry == NULL)
3022 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
3024 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
3025 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
3027 struct stat file_status;
3029 dir->dir_entry->is_directory =
3030 (stat(dir->dir_entry->filename, &file_status) == 0 &&
3031 S_ISDIR(file_status.st_mode));
3033 return dir->dir_entry;
3036 void freeDirectoryEntry(DirectoryEntry *dir_entry)
3038 if (dir_entry == NULL)
3041 checked_free(dir_entry->basename);
3042 checked_free(dir_entry->filename);
3043 checked_free(dir_entry);
3047 // ----------------------------------------------------------------------------
3048 // functions for checking files and filenames
3049 // ----------------------------------------------------------------------------
3051 boolean directoryExists(char *dir_name)
3053 if (dir_name == NULL)
3056 struct stat file_status;
3057 boolean success = (stat(dir_name, &file_status) == 0 &&
3058 S_ISDIR(file_status.st_mode));
3060 #if defined(PLATFORM_ANDROID)
3063 // this might be an asset directory; check by trying to open toc file
3064 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
3065 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
3067 checked_free(asset_toc_filename);
3069 success = (file != NULL);
3079 boolean fileExists(char *filename)
3081 if (filename == NULL)
3084 boolean success = (access(filename, F_OK) == 0);
3086 #if defined(PLATFORM_ANDROID)
3089 // this might be an asset file; check by trying to open it
3090 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
3092 success = (file != NULL);
3103 static boolean fileHasPrefix(char *basename, char *prefix)
3105 static char *basename_lower = NULL;
3106 int basename_length, prefix_length;
3108 checked_free(basename_lower);
3110 if (basename == NULL || prefix == NULL)
3113 basename_lower = getStringToLower(basename);
3114 basename_length = strlen(basename_lower);
3115 prefix_length = strlen(prefix);
3117 if (basename_length > prefix_length + 1 &&
3118 basename_lower[prefix_length] == '.' &&
3119 strncmp(basename_lower, prefix, prefix_length) == 0)
3126 static boolean fileHasSuffix(char *basename, char *suffix)
3128 static char *basename_lower = NULL;
3129 int basename_length, suffix_length;
3131 checked_free(basename_lower);
3133 if (basename == NULL || suffix == NULL)
3136 basename_lower = getStringToLower(basename);
3137 basename_length = strlen(basename_lower);
3138 suffix_length = strlen(suffix);
3140 if (basename_length > suffix_length + 1 &&
3141 basename_lower[basename_length - suffix_length - 1] == '.' &&
3142 strEqual(&basename_lower[basename_length - suffix_length], suffix))
3148 static boolean FileCouldBeArtwork(char *filename)
3150 char *basename = getBaseNamePtr(filename);
3152 return (!strEqual(basename, ".") &&
3153 !strEqual(basename, "..") &&
3154 !fileHasSuffix(basename, "txt") &&
3155 !fileHasSuffix(basename, "conf") &&
3156 !directoryExists(filename));
3159 boolean FileIsGraphic(char *filename)
3161 return FileCouldBeArtwork(filename);
3164 boolean FileIsSound(char *filename)
3166 return FileCouldBeArtwork(filename);
3169 boolean FileIsMusic(char *filename)
3171 return FileCouldBeArtwork(filename);
3174 boolean FileIsArtworkType(char *filename, int type)
3176 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
3177 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
3178 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
3184 // ----------------------------------------------------------------------------
3185 // functions for loading artwork configuration information
3186 // ----------------------------------------------------------------------------
3188 char *get_mapped_token(char *token)
3190 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
3191 static char *map_token_prefix[][2] =
3193 { "char_procent", "char_percent" },
3194 { "bd_magic_wall_filling", "bd_magic_wall.filling" },
3195 { "bd_magic_wall_emptying", "bd_magic_wall.emptying" },
3196 { "bd_butterfly_left", "bd_butterfly.left" },
3197 { "bd_butterfly_right", "bd_butterfly.right" },
3198 { "bd_butterfly_up", "bd_butterfly.up" },
3199 { "bd_butterfly_down", "bd_butterfly.down" },
3200 { "bd_firefly_left", "bd_firefly.left" },
3201 { "bd_firefly_right", "bd_firefly.right" },
3202 { "bd_firefly_up", "bd_firefly.up" },
3203 { "bd_firefly_down", "bd_firefly.down" },
3209 for (i = 0; map_token_prefix[i][0] != NULL; i++)
3211 int len_token_prefix = strlen(map_token_prefix[i][0]);
3213 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
3214 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
3217 // change tokens containing ".gfx" by moving the "gfx" part to the very left
3218 char *gfx_substring = ".gfx";
3219 char *gfx_prefix = "gfx.";
3220 if (strstr(token, gfx_substring) != NULL)
3222 char *token_prefix = getStringCopy(token);
3223 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
3224 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
3227 // cut off token string at ".gfx" substring position
3228 *token_gfx_pos = '\0';
3230 // put together prefix "gfx." and token prefix and suffix without ".gfx"
3231 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
3235 return mapped_token;
3241 static char *get_special_base_token(struct ArtworkListInfo *artwork_info,
3244 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
3245 static struct ConfigTypeInfo prefix_list[] =
3247 { "global.anim_1" },
3248 { "global.anim_2" },
3249 { "global.anim_3" },
3250 { "global.anim_4" },
3251 { "global.anim_5" },
3252 { "global.anim_6" },
3253 { "global.anim_7" },
3254 { "global.anim_8" },
3255 { "global.anim_9" },
3256 { "global.anim_10" },
3257 { "global.anim_11" },
3258 { "global.anim_12" },
3259 { "global.anim_13" },
3260 { "global.anim_14" },
3261 { "global.anim_15" },
3262 { "global.anim_16" },
3263 { "global.anim_17" },
3264 { "global.anim_18" },
3265 { "global.anim_19" },
3266 { "global.anim_20" },
3267 { "global.anim_21" },
3268 { "global.anim_22" },
3269 { "global.anim_23" },
3270 { "global.anim_24" },
3271 { "global.anim_25" },
3272 { "global.anim_26" },
3273 { "global.anim_27" },
3274 { "global.anim_28" },
3275 { "global.anim_29" },
3276 { "global.anim_30" },
3277 { "global.anim_31" },
3278 { "global.anim_32" },
3282 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3283 boolean prefix_found = FALSE;
3287 // search for prefix to check if base token has to be created
3288 for (i = 0; prefix_list[i].token != NULL; i++)
3289 if (strPrefix(token, prefix_list[i].token))
3290 prefix_found = TRUE;
3295 // search for suffix (parameter) to determine base token length
3296 for (i = 0; suffix_list[i].token != NULL; i++)
3297 if (strSuffix(token, suffix_list[i].token))
3298 len_suffix = strlen(suffix_list[i].token);
3300 return getStringCopyN(token, strlen(token) - len_suffix);
3303 static void FreeCustomArtworkList(struct ArtworkListInfo *,
3304 struct ListNodeInfo ***, int *);
3306 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
3307 struct ConfigTypeInfo *suffix_list,
3308 char **ignore_tokens,
3309 int num_file_list_entries)
3311 SetupFileHash *ignore_tokens_hash;
3312 struct FileInfo *file_list;
3313 int num_file_list_entries_found = 0;
3314 int num_suffix_list_entries = 0;
3318 // create hash from list of tokens to be ignored (for quick access)
3319 ignore_tokens_hash = newSetupFileHash();
3320 for (i = 0; ignore_tokens[i] != NULL; i++)
3321 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
3323 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
3325 for (i = 0; suffix_list[i].token != NULL; i++)
3326 num_suffix_list_entries++;
3328 // always start with reliable default values
3329 for (i = 0; i < num_file_list_entries; i++)
3331 file_list[i].token = NULL;
3333 file_list[i].default_filename = NULL;
3334 file_list[i].filename = NULL;
3336 if (num_suffix_list_entries > 0)
3338 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3340 file_list[i].default_parameter = checked_calloc(parameter_array_size);
3341 file_list[i].parameter = checked_calloc(parameter_array_size);
3343 for (j = 0; j < num_suffix_list_entries; j++)
3345 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
3346 setString(&file_list[i].parameter[j], suffix_list[j].value);
3349 file_list[i].redefined = FALSE;
3350 file_list[i].fallback_to_default = FALSE;
3351 file_list[i].default_is_cloned = FALSE;
3357 for (i = 0; config_list[i].token != NULL; i++)
3359 int len_config_token = strlen(config_list[i].token);
3360 boolean is_file_entry = TRUE;
3362 for (j = 0; suffix_list[j].token != NULL; j++)
3364 int len_suffix = strlen(suffix_list[j].token);
3366 if (len_suffix < len_config_token &&
3367 strEqual(&config_list[i].token[len_config_token - len_suffix],
3368 suffix_list[j].token))
3370 setString(&file_list[list_pos].default_parameter[j],
3371 config_list[i].value);
3373 is_file_entry = FALSE;
3379 // the following tokens are no file definitions, but other config tokens
3380 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
3381 is_file_entry = FALSE;
3388 if (list_pos >= num_file_list_entries)
3391 file_list[list_pos].token = config_list[i].token;
3392 file_list[list_pos].default_filename = config_list[i].value;
3395 if (strSuffix(config_list[i].token, ".clone_from"))
3396 file_list[list_pos].default_is_cloned = TRUE;
3399 num_file_list_entries_found = list_pos + 1;
3400 if (num_file_list_entries_found != num_file_list_entries)
3403 Error("inconsistant config list information:");
3404 Error("- should be: %d (according to 'src/conf_xxx.h')",
3405 num_file_list_entries);
3406 Error("- found to be: %d (according to 'src/conf_xxx.c')",
3407 num_file_list_entries_found);
3412 freeSetupFileHash(ignore_tokens_hash);
3417 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3419 int len_token = strlen(token);
3420 int len_suffix = strlen(suffix);
3422 if (start_pos < 0) // compare suffix from end of string
3423 start_pos += len_token;
3425 if (start_pos < 0 || start_pos + len_suffix > len_token)
3428 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3431 if (token[start_pos + len_suffix] == '\0')
3434 if (token[start_pos + len_suffix] == '.')
3440 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3442 static void read_token_parameters(SetupFileHash *setup_file_hash,
3443 struct ConfigTypeInfo *suffix_list,
3444 struct FileInfo *file_list_entry)
3446 // check for config token that is the base token without any suffixes
3447 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3448 char *known_token_value = KNOWN_TOKEN_VALUE;
3451 if (filename != NULL)
3453 setString(&file_list_entry->filename, filename);
3455 // when file definition found, set all parameters to default values
3456 for (i = 0; suffix_list[i].token != NULL; i++)
3457 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3459 file_list_entry->redefined = TRUE;
3461 // mark config file token as well known from default config
3462 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3465 // check for config tokens that can be build by base token and suffixes
3466 for (i = 0; suffix_list[i].token != NULL; i++)
3468 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3469 char *value = getHashEntry(setup_file_hash, token);
3473 setString(&file_list_entry->parameter[i], value);
3475 // mark config file token as well known from default config
3476 setHashEntry(setup_file_hash, token, known_token_value);
3483 static void add_dynamic_file_list_entry(struct FileInfo **list,
3484 int *num_list_entries,
3485 SetupFileHash *extra_file_hash,
3486 struct ConfigTypeInfo *suffix_list,
3487 int num_suffix_list_entries,
3490 struct FileInfo *new_list_entry;
3491 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3493 (*num_list_entries)++;
3494 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3495 new_list_entry = &(*list)[*num_list_entries - 1];
3497 new_list_entry->token = getStringCopy(token);
3498 new_list_entry->default_filename = NULL;
3499 new_list_entry->filename = NULL;
3500 new_list_entry->parameter = checked_calloc(parameter_array_size);
3502 new_list_entry->redefined = FALSE;
3503 new_list_entry->fallback_to_default = FALSE;
3504 new_list_entry->default_is_cloned = FALSE;
3506 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3509 static void add_property_mapping(struct PropertyMapping **list,
3510 int *num_list_entries,
3511 int base_index, int ext1_index,
3512 int ext2_index, int ext3_index,
3515 struct PropertyMapping *new_list_entry;
3517 (*num_list_entries)++;
3518 *list = checked_realloc(*list,
3519 *num_list_entries * sizeof(struct PropertyMapping));
3520 new_list_entry = &(*list)[*num_list_entries - 1];
3522 new_list_entry->base_index = base_index;
3523 new_list_entry->ext1_index = ext1_index;
3524 new_list_entry->ext2_index = ext2_index;
3525 new_list_entry->ext3_index = ext3_index;
3527 new_list_entry->artwork_index = artwork_index;
3530 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3533 struct FileInfo *file_list = artwork_info->file_list;
3534 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3535 char **base_prefixes = artwork_info->base_prefixes;
3536 char **ext1_suffixes = artwork_info->ext1_suffixes;
3537 char **ext2_suffixes = artwork_info->ext2_suffixes;
3538 char **ext3_suffixes = artwork_info->ext3_suffixes;
3539 char **ignore_tokens = artwork_info->ignore_tokens;
3540 int num_file_list_entries = artwork_info->num_file_list_entries;
3541 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3542 int num_base_prefixes = artwork_info->num_base_prefixes;
3543 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3544 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3545 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3546 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3547 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3548 SetupFileHash *extra_file_hash, *empty_file_hash;
3549 char *known_token_value = KNOWN_TOKEN_VALUE;
3550 char *base_token_value = UNDEFINED_FILENAME;
3553 if (filename == NULL)
3556 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3559 // separate valid (defined) from empty (undefined) config token values
3560 valid_file_hash = newSetupFileHash();
3561 empty_file_hash = newSetupFileHash();
3562 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3564 char *value = HASH_ITERATION_VALUE(itr);
3566 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3567 HASH_ITERATION_TOKEN(itr), value);
3569 END_HASH_ITERATION(setup_file_hash, itr)
3571 // at this point, we do not need the setup file hash anymore -- free it
3572 freeSetupFileHash(setup_file_hash);
3574 // prevent changing hash while iterating over it by using a temporary copy
3575 valid_file_hash_tmp = newSetupFileHash();
3576 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3578 setHashEntry(valid_file_hash_tmp,
3579 HASH_ITERATION_TOKEN(itr),
3580 HASH_ITERATION_VALUE(itr));
3582 END_HASH_ITERATION(valid_file_hash, itr)
3584 // (iterate over same temporary hash, as modifications are independent)
3586 // map deprecated to current tokens (using prefix match and replace)
3587 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3589 char *token = HASH_ITERATION_TOKEN(itr);
3590 char *mapped_token = get_mapped_token(token);
3592 if (mapped_token != NULL)
3594 char *value = HASH_ITERATION_VALUE(itr);
3597 setHashEntry(valid_file_hash, mapped_token, value);
3599 // ignore old token (by setting it to "known" keyword)
3600 setHashEntry(valid_file_hash, token, known_token_value);
3605 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3607 // add special base tokens (using prefix match and replace)
3608 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3610 char *token = HASH_ITERATION_TOKEN(itr);
3611 char *base_token = get_special_base_token(artwork_info, token);
3613 if (base_token != NULL)
3615 // add base token only if it does not already exist
3616 if (getHashEntry(valid_file_hash, base_token) == NULL)
3617 setHashEntry(valid_file_hash, base_token, base_token_value);
3622 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3624 // free temporary hash used for iteration
3625 freeSetupFileHash(valid_file_hash_tmp);
3627 // read parameters for all known config file tokens
3628 for (i = 0; i < num_file_list_entries; i++)
3629 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3631 // set all tokens that can be ignored here to "known" keyword
3632 for (i = 0; i < num_ignore_tokens; i++)
3633 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3635 // copy all unknown config file tokens to extra config hash
3636 extra_file_hash = newSetupFileHash();
3637 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3639 char *value = HASH_ITERATION_VALUE(itr);
3641 if (!strEqual(value, known_token_value))
3642 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3644 END_HASH_ITERATION(valid_file_hash, itr)
3646 // at this point, we do not need the valid file hash anymore -- free it
3647 freeSetupFileHash(valid_file_hash);
3649 // now try to determine valid, dynamically defined config tokens
3651 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3653 struct FileInfo **dynamic_file_list =
3654 &artwork_info->dynamic_file_list;
3655 int *num_dynamic_file_list_entries =
3656 &artwork_info->num_dynamic_file_list_entries;
3657 struct PropertyMapping **property_mapping =
3658 &artwork_info->property_mapping;
3659 int *num_property_mapping_entries =
3660 &artwork_info->num_property_mapping_entries;
3661 int current_summarized_file_list_entry =
3662 artwork_info->num_file_list_entries +
3663 artwork_info->num_dynamic_file_list_entries;
3664 char *token = HASH_ITERATION_TOKEN(itr);
3665 int len_token = strlen(token);
3667 boolean base_prefix_found = FALSE;
3668 boolean parameter_suffix_found = FALSE;
3670 // skip all parameter definitions (handled by read_token_parameters())
3671 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3673 int len_suffix = strlen(suffix_list[i].token);
3675 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3676 parameter_suffix_found = TRUE;
3679 if (parameter_suffix_found)
3682 // ---------- step 0: search for matching base prefix ----------
3685 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3687 char *base_prefix = base_prefixes[i];
3688 int len_base_prefix = strlen(base_prefix);
3689 boolean ext1_suffix_found = FALSE;
3690 boolean ext2_suffix_found = FALSE;
3691 boolean ext3_suffix_found = FALSE;
3692 boolean exact_match = FALSE;
3693 int base_index = -1;
3694 int ext1_index = -1;
3695 int ext2_index = -1;
3696 int ext3_index = -1;
3698 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3700 if (!base_prefix_found)
3705 if (start_pos + len_base_prefix == len_token) // exact match
3709 add_dynamic_file_list_entry(dynamic_file_list,
3710 num_dynamic_file_list_entries,
3713 num_suffix_list_entries,
3715 add_property_mapping(property_mapping,
3716 num_property_mapping_entries,
3717 base_index, -1, -1, -1,
3718 current_summarized_file_list_entry);
3722 // ---------- step 1: search for matching first suffix ----------
3724 start_pos += len_base_prefix;
3725 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3727 char *ext1_suffix = ext1_suffixes[j];
3728 int len_ext1_suffix = strlen(ext1_suffix);
3730 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3732 if (!ext1_suffix_found)
3737 if (start_pos + len_ext1_suffix == len_token) // exact match
3741 add_dynamic_file_list_entry(dynamic_file_list,
3742 num_dynamic_file_list_entries,
3745 num_suffix_list_entries,
3747 add_property_mapping(property_mapping,
3748 num_property_mapping_entries,
3749 base_index, ext1_index, -1, -1,
3750 current_summarized_file_list_entry);
3754 start_pos += len_ext1_suffix;
3760 // ---------- step 2: search for matching second suffix ----------
3762 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3764 char *ext2_suffix = ext2_suffixes[k];
3765 int len_ext2_suffix = strlen(ext2_suffix);
3767 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3769 if (!ext2_suffix_found)
3774 if (start_pos + len_ext2_suffix == len_token) // exact match
3778 add_dynamic_file_list_entry(dynamic_file_list,
3779 num_dynamic_file_list_entries,
3782 num_suffix_list_entries,
3784 add_property_mapping(property_mapping,
3785 num_property_mapping_entries,
3786 base_index, ext1_index, ext2_index, -1,
3787 current_summarized_file_list_entry);
3791 start_pos += len_ext2_suffix;
3797 // ---------- step 3: search for matching third suffix ----------
3799 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3801 char *ext3_suffix = ext3_suffixes[l];
3802 int len_ext3_suffix = strlen(ext3_suffix);
3804 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3806 if (!ext3_suffix_found)
3811 if (start_pos + len_ext3_suffix == len_token) // exact match
3815 add_dynamic_file_list_entry(dynamic_file_list,
3816 num_dynamic_file_list_entries,
3819 num_suffix_list_entries,
3821 add_property_mapping(property_mapping,
3822 num_property_mapping_entries,
3823 base_index, ext1_index, ext2_index, ext3_index,
3824 current_summarized_file_list_entry);
3830 END_HASH_ITERATION(extra_file_hash, itr)
3832 if (artwork_info->num_dynamic_file_list_entries > 0)
3834 artwork_info->dynamic_artwork_list =
3835 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3836 artwork_info->sizeof_artwork_list_entry);
3839 if (options.verbose && IS_PARENT_PROCESS())
3841 SetupFileList *setup_file_list, *list;
3842 boolean dynamic_tokens_found = FALSE;
3843 boolean unknown_tokens_found = FALSE;
3844 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3846 // list may be NULL for empty artwork config files
3847 setup_file_list = loadSetupFileList(filename);
3849 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3851 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3852 dynamic_tokens_found = TRUE;
3854 unknown_tokens_found = TRUE;
3856 END_HASH_ITERATION(extra_file_hash, itr)
3858 if (options.debug && dynamic_tokens_found)
3860 Debug("config", "---");
3861 Debug("config", "dynamic token(s) found in config file:");
3862 Debug("config", "- config file: '%s'", filename);
3864 for (list = setup_file_list; list != NULL; list = list->next)
3866 char *value = getHashEntry(extra_file_hash, list->token);
3868 if (value != NULL && strEqual(value, known_token_value))
3869 Debug("config", "- dynamic token: '%s'", list->token);
3872 Debug("config", "---");
3875 if (unknown_tokens_found)
3878 Warn("unknown token(s) found in config file:");
3879 Warn("- config file: '%s'", filename);
3881 for (list = setup_file_list; list != NULL; list = list->next)
3883 char *value = getHashEntry(extra_file_hash, list->token);
3885 if (value != NULL && !strEqual(value, known_token_value))
3886 Warn("- dynamic token: '%s'", list->token);
3892 if (undefined_values_found)
3895 Warn("undefined values found in config file:");
3896 Warn("- config file: '%s'", filename);
3898 for (list = setup_file_list; list != NULL; list = list->next)
3900 char *value = getHashEntry(empty_file_hash, list->token);
3903 Warn("- undefined value for token: '%s'", list->token);
3909 freeSetupFileList(setup_file_list);
3912 freeSetupFileHash(extra_file_hash);
3913 freeSetupFileHash(empty_file_hash);
3916 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3918 struct FileInfo *file_list = artwork_info->file_list;
3919 int num_file_list_entries = artwork_info->num_file_list_entries;
3920 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3921 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3924 DrawInitTextHead("Loading artwork config");
3925 DrawInitTextItem(ARTWORKINFO_FILENAME(artwork_info->type));
3927 // always start with reliable default values
3928 for (i = 0; i < num_file_list_entries; i++)
3930 setString(&file_list[i].filename, file_list[i].default_filename);
3932 for (j = 0; j < num_suffix_list_entries; j++)
3933 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3935 file_list[i].redefined = FALSE;
3936 file_list[i].fallback_to_default = FALSE;
3939 // free previous dynamic artwork file array
3940 if (artwork_info->dynamic_file_list != NULL)
3942 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3944 free(artwork_info->dynamic_file_list[i].token);
3945 free(artwork_info->dynamic_file_list[i].filename);
3946 free(artwork_info->dynamic_file_list[i].parameter);
3949 free(artwork_info->dynamic_file_list);
3950 artwork_info->dynamic_file_list = NULL;
3952 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3953 &artwork_info->num_dynamic_file_list_entries);
3956 // free previous property mapping
3957 if (artwork_info->property_mapping != NULL)
3959 free(artwork_info->property_mapping);
3961 artwork_info->property_mapping = NULL;
3962 artwork_info->num_property_mapping_entries = 0;
3965 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3967 // first look for special artwork configured in level series config
3968 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3970 if (fileExists(filename_base))
3971 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3974 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3976 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3977 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3980 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3981 struct ListNodeInfo **listnode)
3985 char *filename = (*listnode)->source_filename;
3987 if (--(*listnode)->num_references <= 0)
3988 deleteNodeFromList(&artwork_info->content_list, filename,
3989 artwork_info->free_artwork);
3995 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3996 struct ListNodeInfo **listnode,
3997 struct FileInfo *file_list_entry)
4007 char *basename = file_list_entry->filename;
4008 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
4010 // mark all images from non-default graphics directory as "redefined"
4011 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS &&
4012 !strPrefix(filename, options.graphics_directory))
4013 file_list_entry->redefined = TRUE;
4015 if (filename == NULL)
4017 Warn("cannot find artwork file '%s'", basename);
4019 basename = file_list_entry->default_filename;
4021 // fail for cloned default artwork that has no default filename defined
4022 if (file_list_entry->default_is_cloned &&
4023 strEqual(basename, UNDEFINED_FILENAME))
4025 void (*error_func)(char *, ...) = Warn;
4027 // we can get away without sounds and music, but not without graphics
4028 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
4031 error_func("token '%s' was cloned and has no default filename",
4032 file_list_entry->token);
4037 // dynamic artwork has no default filename / skip empty default artwork
4038 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
4041 file_list_entry->fallback_to_default = TRUE;
4043 Warn("trying default artwork file '%s'", basename);
4045 filename = getCustomArtworkFilename(basename, artwork_info->type);
4047 if (filename == NULL)
4049 void (*error_func)(char *, ...) = Warn;
4051 // we can get away without sounds and music, but not without graphics
4052 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
4055 error_func("cannot find default artwork file '%s'", basename);
4061 // check if the old and the new artwork file are the same
4062 if (*listnode && strEqual((*listnode)->source_filename, filename))
4064 // The old and new artwork are the same (have the same filename and path).
4065 // This usually means that this artwork does not exist in this artwork set
4066 // and a fallback to the existing artwork is done.
4071 // delete existing artwork file entry
4072 deleteArtworkListEntry(artwork_info, listnode);
4074 // check if the new artwork file already exists in the list of artwork
4075 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
4077 *listnode = (struct ListNodeInfo *)node->content;
4078 (*listnode)->num_references++;
4083 DrawInitTextHead(init_text[artwork_info->type]);
4084 DrawInitTextItem(basename);
4086 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
4088 // add new artwork file entry to the list of artwork files
4089 (*listnode)->num_references = 1;
4090 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
4095 void (*error_func)(char *, ...) = Warn;
4097 // we can get away without sounds and music, but not without graphics
4098 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
4101 error_func("cannot load artwork file '%s'", basename);
4107 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
4108 struct ListNodeInfo **listnode,
4109 struct FileInfo *file_list_entry)
4111 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
4113 deleteArtworkListEntry(artwork_info, listnode);
4118 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
4121 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
4123 struct FileInfo *file_list = artwork_info->file_list;
4124 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
4125 int num_file_list_entries = artwork_info->num_file_list_entries;
4126 int num_dynamic_file_list_entries =
4127 artwork_info->num_dynamic_file_list_entries;
4130 print_timestamp_init("ReloadCustomArtworkList");
4132 for (i = 0; i < num_file_list_entries; i++)
4133 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
4136 for (i = 0; i < num_dynamic_file_list_entries; i++)
4137 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
4138 &dynamic_file_list[i]);
4140 print_timestamp_done("ReloadCustomArtworkList");
4143 dumpList(artwork_info->content_list);
4147 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
4148 struct ListNodeInfo ***list,
4149 int *num_list_entries)
4156 for (i = 0; i < *num_list_entries; i++)
4157 deleteArtworkListEntry(artwork_info, &(*list)[i]);
4161 *num_list_entries = 0;
4164 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
4166 if (artwork_info == NULL)
4169 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
4170 &artwork_info->num_file_list_entries);
4172 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
4173 &artwork_info->num_dynamic_file_list_entries);
4177 // ----------------------------------------------------------------------------
4178 // functions only needed for non-Unix (non-command-line) systems
4179 // (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")
4180 // (now also added for Windows, to create files in user data directory)
4181 // ----------------------------------------------------------------------------
4183 char *getLogFilename(char *basename)
4185 return getPath2(getMainUserGameDataDir(), basename);
4188 void OpenLogFiles(void)
4192 InitMainUserDataDirectory();
4194 for (i = 0; i < NUM_LOGS; i++)
4196 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
4199 program.log_file[i] = program.log_file_default[i]; // reset to default
4201 Warn("cannot open file '%s' for writing: %s",
4202 program.log_filename[i], strerror(errno));
4205 // output should be unbuffered so it is not truncated in a crash
4206 setbuf(program.log_file[i], NULL);
4210 void CloseLogFiles(void)
4214 for (i = 0; i < NUM_LOGS; i++)
4215 if (program.log_file[i] != program.log_file_default[i])
4216 fclose(program.log_file[i]);
4219 void DumpLogFile(int nr)
4221 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
4223 if (log_file == NULL)
4226 while (!feof(log_file))
4227 fputc(fgetc(log_file), stdout);
4232 void NotifyUserAboutErrorFile(void)
4234 #if defined(PLATFORM_WINDOWS)
4235 char *title_text = getStringCat2(program.program_title, " Error Message");
4236 char *error_text = getStringCat2("The program was aborted due to an error; "
4237 "for details, see the following error file:"
4239 program.log_filename[LOG_ERR_ID]);
4241 MessageBox(NULL, error_text, title_text, MB_OK);
4246 // ----------------------------------------------------------------------------
4247 // the following is only for debugging purpose and normally not used
4248 // ----------------------------------------------------------------------------
4252 #define DEBUG_PRINT_INIT_TIMESTAMPS TRUE
4253 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
4255 #define DEBUG_NUM_TIMESTAMPS 10
4256 #define DEBUG_TIME_IN_MICROSECONDS 0
4258 #if DEBUG_TIME_IN_MICROSECONDS
4259 static double Counter_Microseconds(void)
4261 static struct timeval base_time = { 0, 0 };
4262 struct timeval current_time;
4265 gettimeofday(¤t_time, NULL);
4267 // reset base time in case of wrap-around
4268 if (current_time.tv_sec < base_time.tv_sec)
4269 base_time = current_time;
4272 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
4273 ((double)(current_time.tv_usec - base_time.tv_usec));
4275 return counter; // return microseconds since last init
4279 static char *debug_print_timestamp_get_padding(int padding_size)
4281 static char *padding = NULL;
4282 int max_padding_size = 100;
4284 if (padding == NULL)
4286 padding = checked_calloc(max_padding_size + 1);
4287 memset(padding, ' ', max_padding_size);
4290 return &padding[MAX(0, max_padding_size - padding_size)];
4293 void debug_print_timestamp(int counter_nr, char *message)
4295 int indent_size = 8;
4296 int padding_size = 40;
4297 float timestamp_interval;
4300 Fail("debugging: invalid negative counter");
4301 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
4302 Fail("debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
4304 #if DEBUG_TIME_IN_MICROSECONDS
4305 static double counter[DEBUG_NUM_TIMESTAMPS][2];
4308 counter[counter_nr][0] = Counter_Microseconds();
4310 static int counter[DEBUG_NUM_TIMESTAMPS][2];
4313 counter[counter_nr][0] = Counter();
4316 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
4317 counter[counter_nr][1] = counter[counter_nr][0];
4320 Debug("time:init", "%s%s%s %.3f %s",
4321 debug_print_timestamp_get_padding(counter_nr * indent_size),
4323 debug_print_timestamp_get_padding(padding_size - strlen(message)),
4324 timestamp_interval / 1000,
4329 static void debug_print_parent_only(char *format, ...)
4331 if (!IS_PARENT_PROCESS())
4338 va_start(ap, format);
4339 vprintf(format, ap);
4349 static void print_timestamp_ext(char *message, char *mode)
4351 #if DEBUG_PRINT_INIT_TIMESTAMPS
4352 static char *debug_message = NULL;
4353 static char *last_message = NULL;
4354 static int counter_nr = 0;
4355 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
4357 checked_free(debug_message);
4358 debug_message = getStringCat3(mode, " ", message);
4360 if (strEqual(mode, "INIT"))
4362 debug_print_timestamp(counter_nr, NULL);
4364 if (counter_nr + 1 < max_depth)
4365 debug_print_timestamp(counter_nr, debug_message);
4369 debug_print_timestamp(counter_nr, NULL);
4371 else if (strEqual(mode, "DONE"))
4375 if (counter_nr + 1 < max_depth ||
4376 (counter_nr == 0 && max_depth == 1))
4378 last_message = message;
4380 if (counter_nr == 0 && max_depth == 1)
4382 checked_free(debug_message);
4383 debug_message = getStringCat3("TIME", " ", message);
4386 debug_print_timestamp(counter_nr, debug_message);
4389 else if (!strEqual(mode, "TIME") ||
4390 !strEqual(message, last_message))
4392 if (counter_nr < max_depth)
4393 debug_print_timestamp(counter_nr, debug_message);
4398 void print_timestamp_init(char *message)
4400 print_timestamp_ext(message, "INIT");
4403 void print_timestamp_time(char *message)
4405 print_timestamp_ext(message, "TIME");
4408 void print_timestamp_done(char *message)
4410 print_timestamp_ext(message, "DONE");