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)
562 static char uuid[UUID_LENGTH + 1];
563 int data[UUID_BYTES];
567 for (i = 0; i < UUID_BYTES; i++)
568 data[i] = GetSimpleRandom(256);
570 data[6] = 0x40 | (data[6] & 0x0f);
571 data[8] = 0x80 | (data[8] & 0x3f);
573 for (i = 0; i < UUID_BYTES; i++)
575 sprintf(&uuid[count], "%02x", data[i]);
578 if (i == 3 || i == 5 || i == 7 || i == 9)
579 strcat(&uuid[count++], "-");
586 // ----------------------------------------------------------------------------
588 // ----------------------------------------------------------------------------
590 // maximal allowed length of a command line option
591 #define MAX_OPTION_LEN 256
593 static unsigned int getCurrentMS(void)
595 return SDL_GetTicks();
598 static unsigned int mainCounter(int mode)
600 static unsigned int base_ms = 0;
601 unsigned int current_ms;
603 // get current system milliseconds
604 current_ms = getCurrentMS();
606 // reset base timestamp in case of counter reset or wrap-around
607 if (mode == INIT_COUNTER || current_ms < base_ms)
608 base_ms = current_ms;
610 // return milliseconds since last counter reset
611 return current_ms - base_ms;
614 void InitCounter() // set counter back to zero
616 mainCounter(INIT_COUNTER);
619 unsigned int Counter() // get milliseconds since last call of InitCounter()
621 return mainCounter(READ_COUNTER);
624 static void sleep_milliseconds(unsigned int milliseconds_delay)
626 SDL_Delay(milliseconds_delay);
629 void Delay(unsigned int delay) // Sleep specified number of milliseconds
631 sleep_milliseconds(delay);
634 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
635 unsigned int actual_counter)
637 if (actual_counter >= *counter_var &&
638 actual_counter < *counter_var + delay)
641 *counter_var = actual_counter;
646 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
648 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
651 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
653 return DelayReachedExt(counter_var, delay, Counter());
656 void ResetDelayCounterExt(unsigned int *counter_var,
657 unsigned int actual_counter)
659 DelayReachedExt(counter_var, 0, actual_counter);
662 void ResetFrameCounter(unsigned int *frame_counter_var)
664 FrameReached(frame_counter_var, 0);
667 void ResetDelayCounter(unsigned int *counter_var)
669 DelayReached(counter_var, 0);
672 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
674 unsigned int actual_counter;
679 actual_counter = Counter();
681 if (actual_counter >= *counter_var &&
682 actual_counter < *counter_var + delay)
683 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
688 if (*counter_var != 0 &&
690 actual_counter >= *counter_var + delay)
692 int lag = actual_counter - (*counter_var + delay);
693 int delay2 = (delay + 1) / 2;
696 skip_frames = (lag + delay2) / delay;
699 *counter_var = actual_counter;
704 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
705 int *loop_var, int last_loop_value)
707 int skip_frames = WaitUntilDelayReached(counter_var, delay);
712 Debug("internal:SkipUntilDelayReached",
713 "%d: %d ms -> SKIP %d FRAME(S) [%d ms]",
715 skip_frames, skip_frames * delay);
717 Debug("internal:SkipUntilDelayReached",
723 if (skip_frames == 0)
726 // when skipping frames, make sure to never skip the last frame, as
727 // this may be needed for animations to reach a defined end state;
728 // furthermore, we assume that this function is called at the end
729 // of a "for" loop, which continues by incrementing the loop variable
730 // by one before checking the loop condition again; therefore we have
731 // to check against the last loop value minus one here
735 if (*loop_var < last_loop_value) // never skip the last frame
737 *loop_var += skip_frames;
739 if (*loop_var > last_loop_value) // never skip the last frame
740 *loop_var = last_loop_value;
745 // ----------------------------------------------------------------------------
746 // random generator functions
747 // ----------------------------------------------------------------------------
749 unsigned int init_random_number(int nr, int seed)
751 if (seed == NEW_RANDOMIZE)
753 // default random seed
754 seed = (int)time(NULL); // seconds since the epoch
756 #if !defined(PLATFORM_WIN32)
757 // add some more randomness
758 struct timeval current_time;
760 gettimeofday(¤t_time, NULL);
762 seed += (int)current_time.tv_usec; // microseconds since the epoch
765 // add some more randomness
766 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
768 // add some more randomness
769 seed += GetSimpleRandom(1000000);
772 srandom_linux_libc(nr, (unsigned int) seed);
774 return (unsigned int) seed;
777 unsigned int get_random_number(int nr, int max)
779 return (max > 0 ? random_linux_libc(nr) % max : 0);
783 // ----------------------------------------------------------------------------
784 // system info functions
785 // ----------------------------------------------------------------------------
787 #if !defined(PLATFORM_ANDROID)
788 static char *get_corrected_real_name(char *real_name)
790 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
791 char *from_ptr = real_name;
792 char *to_ptr = real_name_new;
794 // copy the name string, but not more than MAX_USERNAME_LEN characters
795 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
797 // the name field read from "passwd" file may also contain additional
798 // user information, separated by commas, which will be removed here
799 if (*from_ptr == ',')
802 // the user's real name may contain 'german sharp s' characters,
803 // which have no equivalent in upper case letters (used by our fonts)
804 if (*from_ptr == CHAR_BYTE_SHARP_S)
811 *to_ptr++ = *from_ptr++;
816 return real_name_new;
820 #if defined(PLATFORM_UNIX)
821 static struct passwd *getPasswdEntry(void)
823 #if defined(PLATFORM_EMSCRIPTEN)
824 // currently not fully supported; force fallback to default values
827 return getpwuid(getuid());
831 char *getUnixLoginName(void)
833 struct passwd *pwd = getPasswdEntry();
835 if (pwd != NULL && strlen(pwd->pw_name) != 0)
841 char *getUnixRealName(void)
843 struct passwd *pwd = getPasswdEntry();
845 if (pwd != NULL && strlen(pwd->pw_gecos) != 0)
846 return pwd->pw_gecos;
851 char *getUnixHomeDir(void)
853 struct passwd *pwd = getPasswdEntry();
855 if (pwd != NULL && strlen(pwd->pw_dir) != 0)
862 char *getLoginName(void)
864 static char *login_name = NULL;
866 #if defined(PLATFORM_WIN32)
867 if (login_name == NULL)
869 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
871 login_name = checked_malloc(buffer_size);
873 if (GetUserName(login_name, &buffer_size) == 0)
874 strcpy(login_name, ANONYMOUS_NAME);
876 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
877 if (login_name == NULL)
879 char *name = getUnixLoginName();
882 login_name = getStringCopy(name);
884 login_name = ANONYMOUS_NAME;
887 login_name = ANONYMOUS_NAME;
893 char *getRealName(void)
895 static char *real_name = NULL;
897 #if defined(PLATFORM_WIN32)
898 if (real_name == NULL)
900 static char buffer[MAX_USERNAME_LEN + 1];
901 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
903 if (GetUserName(buffer, &buffer_size) != 0)
904 real_name = get_corrected_real_name(buffer);
906 real_name = ANONYMOUS_NAME;
908 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
909 if (real_name == NULL)
911 char *name = getUnixRealName();
914 real_name = get_corrected_real_name(name);
916 real_name = ANONYMOUS_NAME;
919 real_name = ANONYMOUS_NAME;
925 char *getFixedUserName(char *name)
927 // needed because player name must be a fixed length string
928 char *name_new = checked_malloc(MAX_PLAYER_NAME_LEN + 1);
930 strncpy(name_new, name, MAX_PLAYER_NAME_LEN);
931 name_new[MAX_PLAYER_NAME_LEN] = '\0';
933 if (strlen(name) > MAX_PLAYER_NAME_LEN) // name has been cut
934 if (strchr(name_new, ' '))
935 *strchr(name_new, ' ') = '\0';
940 char *getDefaultUserName(int nr)
942 static char *user_name[MAX_PLAYER_NAMES] = { NULL };
944 nr = MIN(MAX(0, nr), MAX_PLAYER_NAMES - 1);
946 if (user_name[nr] == NULL)
948 user_name[nr] = (nr == 0 ? getLoginName() : EMPTY_PLAYER_NAME);
949 user_name[nr] = getFixedUserName(user_name[nr]);
952 return user_name[nr];
955 char *getTimestampFromEpoch(time_t epoch_seconds)
957 struct tm *now = localtime(&epoch_seconds);
958 static char timestamp[20];
960 sprintf(timestamp, "%04d%02d%02d-%02d%02d%02d",
961 now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
962 now->tm_hour, now->tm_min, now->tm_sec);
967 char *getCurrentTimestamp(void)
969 return getTimestampFromEpoch(time(NULL));
972 time_t getFileTimestampEpochSeconds(char *filename)
974 struct stat file_status;
976 if (stat(filename, &file_status) != 0) // cannot stat file
979 return file_status.st_mtime;
983 // ----------------------------------------------------------------------------
984 // path manipulation functions
985 // ----------------------------------------------------------------------------
987 static char *getLastPathSeparatorPtr(char *filename)
989 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
991 if (last_separator == NULL) // also try DOS/Windows variant
992 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
994 return last_separator;
997 char *getBaseNamePtr(char *filename)
999 char *last_separator = getLastPathSeparatorPtr(filename);
1001 if (last_separator != NULL)
1002 return last_separator + 1; // separator found: strip base path
1004 return filename; // no separator found: filename has no path
1007 char *getBaseName(char *filename)
1009 return getStringCopy(getBaseNamePtr(filename));
1012 char *getBaseNameNoSuffix(char *filename)
1014 char *basename = getStringCopy(getBaseNamePtr(filename));
1016 // remove trailing suffix (separated by dot or hyphen)
1017 if (basename[0] != '.' && basename[0] != '-')
1019 if (strchr(basename, '.') != NULL)
1020 *strchr(basename, '.') = '\0';
1022 if (strchr(basename, '-') != NULL)
1023 *strchr(basename, '-') = '\0';
1029 char *getBasePath(char *filename)
1031 char *basepath = getStringCopy(filename);
1032 char *last_separator = getLastPathSeparatorPtr(basepath);
1034 // if no separator was found, use current directory
1035 if (last_separator == NULL)
1039 return getStringCopy(".");
1042 // separator found: strip basename
1043 *last_separator = '\0';
1049 // ----------------------------------------------------------------------------
1050 // various string functions
1051 // ----------------------------------------------------------------------------
1053 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
1055 if (s1 == NULL || s2 == NULL || sep == NULL)
1058 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
1061 sprintf(complete_string, "%s%s%s", s1, sep, s2);
1063 return complete_string;
1066 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
1068 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
1071 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
1072 strlen(s2) + strlen(sep) +
1075 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
1077 return complete_string;
1080 char *getStringCat2(char *s1, char *s2)
1082 return getStringCat2WithSeparator(s1, s2, "");
1085 char *getStringCat3(char *s1, char *s2, char *s3)
1087 return getStringCat3WithSeparator(s1, s2, s3, "");
1090 char *getPath2(char *path1, char *path2)
1092 #if defined(PLATFORM_ANDROID)
1093 // workaround for reading from assets directory -- skip "." subdirs in path
1094 if (strEqual(path1, "."))
1095 return getStringCopy(path2);
1096 else if (strEqual(path2, "."))
1097 return getStringCopy(path1);
1100 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1103 char *getPath3(char *path1, char *path2, char *path3)
1105 #if defined(PLATFORM_ANDROID)
1106 // workaround for reading from assets directory -- skip "." subdirs in path
1107 if (strEqual(path1, "."))
1108 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
1109 else if (strEqual(path2, "."))
1110 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
1111 else if (strEqual(path3, "."))
1112 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1115 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
1118 static char *getPngOrPcxIfNotExists(char *filename)
1120 // switch from PNG to PCX file and vice versa, if file does not exist
1121 // (backwards compatibility with PCX files used in previous versions)
1123 if (!fileExists(filename) && strSuffix(filename, ".png"))
1124 strcpy(&filename[strlen(filename) - 3], "pcx");
1125 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
1126 strcpy(&filename[strlen(filename) - 3], "png");
1131 char *getImg2(char *path1, char *path2)
1133 return getPngOrPcxIfNotExists(getPath2(path1, path2));
1136 char *getImg3(char *path1, char *path2, char *path3)
1138 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
1141 char *getStringCopy(const char *s)
1148 s_copy = checked_malloc(strlen(s) + 1);
1154 char *getStringCopyN(const char *s, int n)
1157 int s_len = MAX(0, n);
1162 s_copy = checked_malloc(s_len + 1);
1163 strncpy(s_copy, s, s_len);
1164 s_copy[s_len] = '\0';
1169 char *getStringCopyNStatic(const char *s, int n)
1171 static char *s_copy = NULL;
1173 checked_free(s_copy);
1175 s_copy = getStringCopyN(s, n);
1180 char *getStringToLower(const char *s)
1182 char *s_copy = checked_malloc(strlen(s) + 1);
1183 char *s_ptr = s_copy;
1186 *s_ptr++ = tolower(*s++);
1192 void setString(char **old_value, char *new_value)
1194 checked_free(*old_value);
1196 *old_value = getStringCopy(new_value);
1199 boolean strEqual(char *s1, char *s2)
1201 return (s1 == NULL && s2 == NULL ? TRUE :
1202 s1 == NULL && s2 != NULL ? FALSE :
1203 s1 != NULL && s2 == NULL ? FALSE :
1204 strcmp(s1, s2) == 0);
1207 boolean strEqualN(char *s1, char *s2, int n)
1209 return (s1 == NULL && s2 == NULL ? TRUE :
1210 s1 == NULL && s2 != NULL ? FALSE :
1211 s1 != NULL && s2 == NULL ? FALSE :
1212 strncmp(s1, s2, n) == 0);
1215 boolean strEqualCase(char *s1, char *s2)
1217 return (s1 == NULL && s2 == NULL ? TRUE :
1218 s1 == NULL && s2 != NULL ? FALSE :
1219 s1 != NULL && s2 == NULL ? FALSE :
1220 strcasecmp(s1, s2) == 0);
1223 boolean strEqualCaseN(char *s1, char *s2, int n)
1225 return (s1 == NULL && s2 == NULL ? TRUE :
1226 s1 == NULL && s2 != NULL ? FALSE :
1227 s1 != NULL && s2 == NULL ? FALSE :
1228 strncasecmp(s1, s2, n) == 0);
1231 boolean strPrefix(char *s, char *prefix)
1233 return (s == NULL && prefix == NULL ? TRUE :
1234 s == NULL && prefix != NULL ? FALSE :
1235 s != NULL && prefix == NULL ? FALSE :
1236 strncmp(s, prefix, strlen(prefix)) == 0);
1239 boolean strSuffix(char *s, char *suffix)
1241 return (s == NULL && suffix == NULL ? TRUE :
1242 s == NULL && suffix != NULL ? FALSE :
1243 s != NULL && suffix == NULL ? FALSE :
1244 strlen(s) < strlen(suffix) ? FALSE :
1245 strcmp(&s[strlen(s) - strlen(suffix)], suffix) == 0);
1248 boolean strPrefixLower(char *s, char *prefix)
1250 char *s_lower = getStringToLower(s);
1251 boolean match = strPrefix(s_lower, prefix);
1258 boolean strSuffixLower(char *s, char *suffix)
1260 char *s_lower = getStringToLower(s);
1261 boolean match = strSuffix(s_lower, suffix);
1269 // ----------------------------------------------------------------------------
1270 // command line option handling functions
1271 // ----------------------------------------------------------------------------
1273 void GetOptions(int argc, char *argv[],
1274 void (*print_usage_function)(void),
1275 void (*print_version_function)(void))
1277 char *base_path = getProgramMainDataPath(argv[0], BASE_PATH);
1278 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
1279 char **options_left = &argvplus[1];
1281 // replace original "argv" with null-terminated array of string pointers
1283 argvplus[argc] = argv[argc];
1285 // initialize global program options
1286 options.server_host = NULL;
1287 options.server_port = 0;
1289 options.base_directory = base_path;
1291 options.level_directory = getPath2(base_path, LEVELS_DIRECTORY);
1292 options.graphics_directory = getPath2(base_path, GRAPHICS_DIRECTORY);
1293 options.sounds_directory = getPath2(base_path, SOUNDS_DIRECTORY);
1294 options.music_directory = getPath2(base_path, MUSIC_DIRECTORY);
1295 options.docs_directory = getPath2(base_path, DOCS_DIRECTORY);
1296 options.conf_directory = getPath2(base_path, CONF_DIRECTORY);
1298 options.execute_command = NULL;
1299 options.tape_log_filename = NULL;
1300 options.special_flags = NULL;
1301 options.debug_mode = NULL;
1302 options.player_name = NULL;
1304 options.mytapes = FALSE;
1305 options.serveronly = FALSE;
1306 options.network = FALSE;
1307 options.verbose = FALSE;
1308 options.debug = FALSE;
1311 options.verbose = TRUE;
1313 #if !defined(PLATFORM_UNIX)
1314 if (*options_left == NULL) // no options given -- enable verbose mode
1315 options.verbose = TRUE;
1320 #if defined(PLATFORM_ANDROID)
1321 options.debug = TRUE;
1325 while (*options_left)
1327 char option_str[MAX_OPTION_LEN];
1328 char *option = options_left[0];
1329 char *next_option = options_left[1];
1330 char *option_arg = NULL;
1331 int option_len = strlen(option);
1333 if (option_len >= MAX_OPTION_LEN)
1334 FailWithHelp("unrecognized option '%s'", option);
1336 strcpy(option_str, option); // copy argument into buffer
1337 option = option_str;
1339 if (strEqual(option, "--")) // stop scanning arguments
1342 if (strPrefix(option, "--")) // treat '--' like '-'
1345 option_arg = strchr(option, '=');
1346 if (option_arg == NULL) // no '=' in option
1347 option_arg = next_option;
1350 *option_arg++ = '\0'; // cut argument from option
1351 if (*option_arg == '\0') // no argument after '='
1352 FailWithHelp("option '%s' has invalid argument", option_str);
1355 option_len = strlen(option);
1357 if (strEqual(option, "-"))
1359 FailWithHelp("unrecognized option '%s'", option);
1361 else if (strncmp(option, "-help", option_len) == 0)
1363 print_usage_function();
1367 else if (strncmp(option, "-basepath", option_len) == 0)
1369 if (option_arg == NULL)
1370 FailWithHelp("option '%s' requires an argument", option_str);
1372 options.base_directory = base_path = getStringCopy(option_arg);
1373 if (option_arg == next_option)
1376 // adjust paths for sub-directories in base directory accordingly
1377 options.level_directory = getPath2(base_path, LEVELS_DIRECTORY);
1378 options.graphics_directory = getPath2(base_path, GRAPHICS_DIRECTORY);
1379 options.sounds_directory = getPath2(base_path, SOUNDS_DIRECTORY);
1380 options.music_directory = getPath2(base_path, MUSIC_DIRECTORY);
1381 options.docs_directory = getPath2(base_path, DOCS_DIRECTORY);
1382 options.conf_directory = getPath2(base_path, CONF_DIRECTORY);
1384 else if (strncmp(option, "-levels", option_len) == 0)
1386 if (option_arg == NULL)
1387 FailWithHelp("option '%s' requires an argument", option_str);
1389 options.level_directory = getStringCopy(option_arg);
1390 if (option_arg == next_option)
1393 else if (strncmp(option, "-graphics", option_len) == 0)
1395 if (option_arg == NULL)
1396 FailWithHelp("option '%s' requires an argument", option_str);
1398 options.graphics_directory = getStringCopy(option_arg);
1399 if (option_arg == next_option)
1402 else if (strncmp(option, "-sounds", option_len) == 0)
1404 if (option_arg == NULL)
1405 FailWithHelp("option '%s' requires an argument", option_str);
1407 options.sounds_directory = getStringCopy(option_arg);
1408 if (option_arg == next_option)
1411 else if (strncmp(option, "-music", option_len) == 0)
1413 if (option_arg == NULL)
1414 FailWithHelp("option '%s' requires an argument", option_str);
1416 options.music_directory = getStringCopy(option_arg);
1417 if (option_arg == next_option)
1420 else if (strncmp(option, "-mytapes", option_len) == 0)
1422 options.mytapes = TRUE;
1424 else if (strncmp(option, "-network", option_len) == 0)
1426 options.network = TRUE;
1428 else if (strncmp(option, "-serveronly", option_len) == 0)
1430 options.serveronly = TRUE;
1432 else if (strncmp(option, "-debug", option_len) == 0)
1434 options.debug = TRUE;
1436 // optionally, debug output can be limited to a specific debug mode
1437 if (option_arg != next_option)
1438 options.debug_mode = getStringCopy(option_arg);
1440 else if (strncmp(option, "-player-name", option_len) == 0)
1442 if (option_arg == NULL)
1443 FailWithHelp("option '%s' requires an argument", option_str);
1445 options.player_name = getStringCopy(option_arg);
1446 if (option_arg == next_option)
1449 else if (strncmp(option, "-verbose", option_len) == 0)
1451 options.verbose = TRUE;
1453 else if (strncmp(option, "-version", option_len) == 0 ||
1454 strncmp(option, "-V", option_len) == 0)
1456 print_version_function();
1460 else if (strPrefix(option, "-D"))
1462 options.special_flags = getStringCopy(&option[2]);
1464 else if (strncmp(option, "-execute", option_len) == 0)
1466 if (option_arg == NULL)
1467 FailWithHelp("option '%s' requires an argument", option_str);
1469 options.execute_command = getStringCopy(option_arg);
1470 if (option_arg == next_option)
1473 // when doing batch processing, always enable verbose mode (warnings)
1474 options.verbose = TRUE;
1476 else if (strncmp(option, "-tape_logfile", option_len) == 0)
1478 if (option_arg == NULL)
1479 FailWithHelp("option '%s' requires an argument", option_str);
1481 options.tape_log_filename = getStringCopy(option_arg);
1482 if (option_arg == next_option)
1485 #if defined(PLATFORM_MACOSX)
1486 else if (strPrefix(option, "-psn"))
1488 // ignore process serial number when launched via GUI on Mac OS X
1491 else if (*option == '-')
1493 FailWithHelp("unrecognized option '%s'", option_str);
1495 else if (options.server_host == NULL)
1497 options.server_host = *options_left;
1499 else if (options.server_port == 0)
1501 options.server_port = atoi(*options_left);
1502 if (options.server_port < 1024)
1503 FailWithHelp("bad port number '%d'", options.server_port);
1506 FailWithHelp("too many arguments");
1513 // ----------------------------------------------------------------------------
1514 // checked memory allocation and freeing functions
1515 // ----------------------------------------------------------------------------
1517 void *checked_malloc(unsigned int size)
1524 Fail("cannot allocate %d bytes -- out of memory", size);
1529 void *checked_calloc(unsigned int size)
1533 ptr = calloc(1, size);
1536 Fail("cannot allocate %d bytes -- out of memory", size);
1541 void *checked_realloc(void *ptr, unsigned int size)
1543 ptr = realloc(ptr, size);
1546 Fail("cannot allocate %d bytes -- out of memory", size);
1551 void checked_free(void *ptr)
1553 if (ptr != NULL) // this check should be done by free() anyway
1557 void clear_mem(void *ptr, unsigned int size)
1559 #if defined(PLATFORM_WIN32)
1560 // for unknown reason, memset() sometimes crashes when compiled with MinGW
1561 char *cptr = (char *)ptr;
1566 memset(ptr, 0, size);
1571 // ----------------------------------------------------------------------------
1572 // various helper functions
1573 // ----------------------------------------------------------------------------
1575 void swap_numbers(int *i1, int *i2)
1583 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1595 /* the "put" variants of the following file access functions check for the file
1596 pointer being != NULL and return the number of bytes they have or would have
1597 written; this allows for chunk writing functions to first determine the size
1598 of the (not yet written) chunk, write the correct chunk size and finally
1599 write the chunk itself */
1601 int getFile8BitInteger(File *file)
1603 return getByteFromFile(file);
1606 int putFile8BitInteger(FILE *file, int value)
1614 int getFile16BitInteger(File *file, int byte_order)
1616 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1617 return ((getByteFromFile(file) << 8) |
1618 (getByteFromFile(file) << 0));
1619 else // BYTE_ORDER_LITTLE_ENDIAN
1620 return ((getByteFromFile(file) << 0) |
1621 (getByteFromFile(file) << 8));
1624 int putFile16BitInteger(FILE *file, int value, int byte_order)
1628 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1630 fputc((value >> 8) & 0xff, file);
1631 fputc((value >> 0) & 0xff, file);
1633 else // BYTE_ORDER_LITTLE_ENDIAN
1635 fputc((value >> 0) & 0xff, file);
1636 fputc((value >> 8) & 0xff, file);
1643 int getFile32BitInteger(File *file, int byte_order)
1645 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1646 return ((getByteFromFile(file) << 24) |
1647 (getByteFromFile(file) << 16) |
1648 (getByteFromFile(file) << 8) |
1649 (getByteFromFile(file) << 0));
1650 else // BYTE_ORDER_LITTLE_ENDIAN
1651 return ((getByteFromFile(file) << 0) |
1652 (getByteFromFile(file) << 8) |
1653 (getByteFromFile(file) << 16) |
1654 (getByteFromFile(file) << 24));
1657 int putFile32BitInteger(FILE *file, int value, int byte_order)
1661 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1663 fputc((value >> 24) & 0xff, file);
1664 fputc((value >> 16) & 0xff, file);
1665 fputc((value >> 8) & 0xff, file);
1666 fputc((value >> 0) & 0xff, file);
1668 else // BYTE_ORDER_LITTLE_ENDIAN
1670 fputc((value >> 0) & 0xff, file);
1671 fputc((value >> 8) & 0xff, file);
1672 fputc((value >> 16) & 0xff, file);
1673 fputc((value >> 24) & 0xff, file);
1680 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1683 const int chunk_name_length = 4;
1686 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1689 if (chunk_size != NULL)
1692 *chunk_size = getFile32BitInteger(file, byte_order);
1695 return (checkEndOfFile(file) ? FALSE : TRUE);
1698 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1705 fputs(chunk_name, file);
1707 num_bytes += strlen(chunk_name);
1709 if (chunk_size >= 0)
1713 putFile32BitInteger(file, chunk_size, byte_order);
1721 int getFileVersion(File *file)
1723 int version_super = getByteFromFile(file);
1724 int version_major = getByteFromFile(file);
1725 int version_minor = getByteFromFile(file);
1726 int version_patch = getByteFromFile(file);
1728 return VERSION_IDENT(version_super, version_major, version_minor,
1732 int putFileVersion(FILE *file, int version)
1736 int version_super = VERSION_SUPER(version);
1737 int version_major = VERSION_MAJOR(version);
1738 int version_minor = VERSION_MINOR(version);
1739 int version_patch = VERSION_PATCH(version);
1741 fputc(version_super, file);
1742 fputc(version_major, file);
1743 fputc(version_minor, file);
1744 fputc(version_patch, file);
1750 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1754 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1755 buffer[i] = getByteFromFile(file);
1758 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1762 for (i = 0; i < bytes; i++)
1763 fputc(buffer[i], file);
1766 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1768 while (bytes-- && !checkEndOfFile(file))
1769 getByteFromFile(file);
1772 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1779 // ----------------------------------------------------------------------------
1780 // functions to convert between ISO-8859-1 and UTF-8
1781 // ----------------------------------------------------------------------------
1783 char *getUTF8FromLatin1(char *latin1)
1785 int max_utf8_size = 2 * strlen(latin1) + 1;
1786 char *utf8 = checked_calloc(max_utf8_size);
1787 unsigned char *src = (unsigned char *)latin1;
1788 unsigned char *dst = (unsigned char *)utf8;
1792 if (*src < 128) // pure 7-bit ASCII
1796 else if (*src >= 160) // non-ASCII characters
1798 *dst++ = 194 + (*src >= 192);
1799 *dst++ = 128 + (*src & 63);
1801 else // undefined in ISO-8859-1
1809 // only use the smallest possible string buffer size
1810 utf8 = checked_realloc(utf8, strlen(utf8) + 1);
1815 char *getLatin1FromUTF8(char *utf8)
1817 int max_latin1_size = strlen(utf8) + 1;
1818 char *latin1 = checked_calloc(max_latin1_size);
1819 unsigned char *src = (unsigned char *)utf8;
1820 unsigned char *dst = (unsigned char *)latin1;
1824 if (*src < 128) // pure 7-bit ASCII
1828 else if (src[0] == 194 &&
1829 src[1] >= 128 && src[1] < 192) // non-ASCII characters
1834 else if (src[0] == 195 &&
1835 src[1] >= 128 && src[1] < 192) // non-ASCII characters
1837 *dst++ = src[1] + 64;
1841 // all other UTF-8 characters are undefined in ISO-8859-1
1843 else if (src[0] >= 192 && src[0] < 224 &&
1844 src[1] >= 128 && src[1] < 192)
1849 else if (src[0] >= 224 && src[0] < 240 &&
1850 src[1] >= 128 && src[1] < 192 &&
1851 src[2] >= 128 && src[2] < 192)
1856 else if (src[0] >= 240 && src[0] < 248 &&
1857 src[1] >= 128 && src[1] < 192 &&
1858 src[2] >= 128 && src[2] < 192 &&
1859 src[3] >= 128 && src[3] < 192)
1864 else if (src[0] >= 248 && src[0] < 252 &&
1865 src[1] >= 128 && src[1] < 192 &&
1866 src[2] >= 128 && src[2] < 192 &&
1867 src[3] >= 128 && src[3] < 192 &&
1868 src[4] >= 128 && src[4] < 192)
1873 else if (src[0] >= 252 && src[0] < 254 &&
1874 src[1] >= 128 && src[1] < 192 &&
1875 src[2] >= 128 && src[2] < 192 &&
1876 src[3] >= 128 && src[3] < 192 &&
1877 src[4] >= 128 && src[4] < 192 &&
1878 src[5] >= 128 && src[5] < 192)
1890 // only use the smallest possible string buffer size
1891 latin1 = checked_realloc(latin1, strlen(latin1) + 1);
1897 // ----------------------------------------------------------------------------
1898 // functions for JSON handling
1899 // ----------------------------------------------------------------------------
1901 char *getEscapedJSON(char *s)
1903 int max_json_size = 2 * strlen(s) + 1;
1904 char *json = checked_calloc(max_json_size);
1905 unsigned char *src = (unsigned char *)s;
1906 unsigned char *dst = (unsigned char *)json;
1907 char *escaped[256] =
1920 if (escaped[*src] != NULL)
1922 char *esc = escaped[*src++];
1933 // only use the smallest possible string buffer size
1934 json = checked_realloc(json, strlen(json) + 1);
1940 // ----------------------------------------------------------------------------
1941 // functions to translate key identifiers between different format
1942 // ----------------------------------------------------------------------------
1944 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1945 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1946 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1947 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1949 static void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1958 // return and escape keys
1959 { KSYM_Return, "XK_Return", "return" },
1960 { KSYM_Escape, "XK_Escape", "escape" },
1962 // normal cursor keys
1963 { KSYM_Left, "XK_Left", "cursor left" },
1964 { KSYM_Right, "XK_Right", "cursor right" },
1965 { KSYM_Up, "XK_Up", "cursor up" },
1966 { KSYM_Down, "XK_Down", "cursor down" },
1968 // keypad cursor keys
1970 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1971 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1972 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1973 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1976 // other keypad keys
1977 #ifdef KSYM_KP_Enter
1978 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1979 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1980 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1981 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1982 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1983 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1987 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1988 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1989 { KSYM_Control_L, "XK_Control_L", "left control" },
1990 { KSYM_Control_R, "XK_Control_R", "right control" },
1991 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1992 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1993 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1994 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1995 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, // Alt-R
1996 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, // Ctrl-R
1998 // some special keys
1999 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
2000 { KSYM_Delete, "XK_Delete", "delete" },
2001 { KSYM_Insert, "XK_Insert", "insert" },
2002 { KSYM_Tab, "XK_Tab", "tab" },
2003 { KSYM_Home, "XK_Home", "home" },
2004 { KSYM_End, "XK_End", "end" },
2005 { KSYM_Page_Up, "XK_Page_Up", "page up" },
2006 { KSYM_Page_Down, "XK_Page_Down", "page down" },
2008 { KSYM_Select, "XK_Select", "select" },
2009 { KSYM_Menu, "XK_Menu", "menu" }, // menu key
2010 { KSYM_Back, "XK_Back", "back" }, // back key
2011 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
2012 #if defined(PLATFORM_ANDROID)
2013 { KSYM_Rewind, "XK_Rewind", "rewind" },
2014 { KSYM_FastForward, "XK_FastForward", "fast forward" },
2017 // ASCII 0x20 to 0x40 keys (except numbers)
2018 { KSYM_space, "XK_space", "space" },
2019 { KSYM_exclam, "XK_exclam", "!" },
2020 { KSYM_quotedbl, "XK_quotedbl", "\"" },
2021 { KSYM_numbersign, "XK_numbersign", "#" },
2022 { KSYM_dollar, "XK_dollar", "$" },
2023 { KSYM_percent, "XK_percent", "%" },
2024 { KSYM_ampersand, "XK_ampersand", "&" },
2025 { KSYM_apostrophe, "XK_apostrophe", "'" },
2026 { KSYM_parenleft, "XK_parenleft", "(" },
2027 { KSYM_parenright, "XK_parenright", ")" },
2028 { KSYM_asterisk, "XK_asterisk", "*" },
2029 { KSYM_plus, "XK_plus", "+" },
2030 { KSYM_comma, "XK_comma", "," },
2031 { KSYM_minus, "XK_minus", "-" },
2032 { KSYM_period, "XK_period", "." },
2033 { KSYM_slash, "XK_slash", "/" },
2034 { KSYM_colon, "XK_colon", ":" },
2035 { KSYM_semicolon, "XK_semicolon", ";" },
2036 { KSYM_less, "XK_less", "<" },
2037 { KSYM_equal, "XK_equal", "=" },
2038 { KSYM_greater, "XK_greater", ">" },
2039 { KSYM_question, "XK_question", "?" },
2040 { KSYM_at, "XK_at", "@" },
2043 { KSYM_bracketleft, "XK_bracketleft", "[" },
2044 { KSYM_backslash, "XK_backslash", "\\" },
2045 { KSYM_bracketright,"XK_bracketright", "]" },
2046 { KSYM_asciicircum, "XK_asciicircum", "^" },
2047 { KSYM_underscore, "XK_underscore", "_" },
2048 { KSYM_grave, "XK_grave", "grave" },
2049 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
2050 { KSYM_braceleft, "XK_braceleft", "brace left" },
2051 { KSYM_bar, "XK_bar", "bar" },
2052 { KSYM_braceright, "XK_braceright", "brace right" },
2053 { KSYM_asciitilde, "XK_asciitilde", "~" },
2055 // special (non-ASCII) keys
2056 { KSYM_degree, "XK_degree", "degree" },
2057 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
2058 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
2059 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
2060 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
2061 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
2062 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
2063 { KSYM_ssharp, "XK_ssharp", "sharp s" },
2065 // special (non-ASCII) keys (UTF-8, for reverse mapping only)
2066 { KSYM_degree, "XK_degree", "\xc2\xb0" },
2067 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
2068 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
2069 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
2070 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
2071 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
2072 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
2073 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
2075 // other keys (for reverse mapping only)
2076 { KSYM_space, "XK_space", " " },
2078 // keypad keys are not in numerical order in SDL2
2079 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
2080 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
2081 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
2082 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
2083 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
2084 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
2085 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
2086 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
2087 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
2088 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
2090 // end-of-array identifier
2096 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
2098 static char name_buffer[30];
2101 if (key >= KSYM_A && key <= KSYM_Z)
2102 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
2103 else if (key >= KSYM_a && key <= KSYM_z)
2104 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
2105 else if (key >= KSYM_0 && key <= KSYM_9)
2106 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
2107 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
2108 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
2109 else if (key == KSYM_UNDEFINED)
2110 strcpy(name_buffer, "(undefined)");
2117 if (key == translate_key[i].key)
2119 strcpy(name_buffer, translate_key[i].name);
2123 while (translate_key[++i].name);
2125 if (!translate_key[i].name)
2126 strcpy(name_buffer, "(unknown)");
2129 *name = name_buffer;
2131 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
2133 static char name_buffer[30];
2136 if (key >= KSYM_A && key <= KSYM_Z)
2137 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
2138 else if (key >= KSYM_a && key <= KSYM_z)
2139 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
2140 else if (key >= KSYM_0 && key <= KSYM_9)
2141 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
2142 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
2143 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
2144 else if (key == KSYM_UNDEFINED)
2145 strcpy(name_buffer, "[undefined]");
2152 if (key == translate_key[i].key)
2154 strcpy(name_buffer, translate_key[i].x11name);
2158 while (translate_key[++i].x11name);
2160 if (!translate_key[i].x11name)
2161 sprintf(name_buffer, "0x%04x", (unsigned int)key);
2164 *x11name = name_buffer;
2166 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
2168 Key key = KSYM_UNDEFINED;
2169 char *name_ptr = *name;
2171 if (strlen(*name) == 1)
2173 char c = name_ptr[0];
2175 if (c >= 'A' && c <= 'Z')
2176 key = KSYM_A + (Key)(c - 'A');
2177 else if (c >= 'a' && c <= 'z')
2178 key = KSYM_a + (Key)(c - 'a');
2179 else if (c >= '0' && c <= '9')
2180 key = KSYM_0 + (Key)(c - '0');
2183 if (key == KSYM_UNDEFINED)
2189 if (strEqual(translate_key[i].name, *name))
2191 key = translate_key[i].key;
2195 while (translate_key[++i].x11name);
2198 if (key == KSYM_UNDEFINED)
2199 Warn("getKeyFromKeyName(): not completely implemented");
2203 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
2205 Key key = KSYM_UNDEFINED;
2206 char *name_ptr = *x11name;
2208 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
2210 char c = name_ptr[3];
2212 if (c >= 'A' && c <= 'Z')
2213 key = KSYM_A + (Key)(c - 'A');
2214 else if (c >= 'a' && c <= 'z')
2215 key = KSYM_a + (Key)(c - 'a');
2216 else if (c >= '0' && c <= '9')
2217 key = KSYM_0 + (Key)(c - '0');
2219 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
2221 char c1 = name_ptr[4];
2222 char c2 = name_ptr[5];
2225 if ((c1 >= '0' && c1 <= '9') &&
2226 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
2227 d = atoi(&name_ptr[4]);
2229 if (d >= 1 && d <= KSYM_NUM_FKEYS)
2230 key = KSYM_F1 + (Key)(d - 1);
2232 else if (strPrefix(name_ptr, "XK_"))
2238 if (strEqual(name_ptr, translate_key[i].x11name))
2240 key = translate_key[i].key;
2244 while (translate_key[++i].x11name);
2246 else if (strPrefix(name_ptr, "0x"))
2248 unsigned int value = 0;
2254 char c = *name_ptr++;
2257 if (c >= '0' && c <= '9')
2259 else if (c >= 'a' && c <= 'f')
2260 d = (int)(c - 'a' + 10);
2261 else if (c >= 'A' && c <= 'F')
2262 d = (int)(c - 'A' + 10);
2270 value = value * 16 + d;
2281 char *getKeyNameFromKey(Key key)
2285 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
2289 char *getX11KeyNameFromKey(Key key)
2293 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
2297 Key getKeyFromKeyName(char *name)
2301 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
2305 Key getKeyFromX11KeyName(char *x11name)
2309 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
2313 char getCharFromKey(Key key)
2319 } translate_key_char[] =
2321 // special (non-ASCII) keys (ISO-8859-1)
2322 { KSYM_degree, CHAR_BYTE_DEGREE },
2323 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
2324 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
2325 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
2326 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
2327 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
2328 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
2329 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
2331 // end-of-array identifier
2335 char *keyname = getKeyNameFromKey(key);
2338 if (strlen(keyname) == 1)
2340 else if (strEqual(keyname, "space"))
2348 if (key == translate_key_char[i].key)
2350 c = translate_key_char[i].key_char;
2355 while (translate_key_char[++i].key_char);
2361 char getValidConfigValueChar(char c)
2363 if (c == '#' || // used to mark comments
2364 c == '\\') // used to mark continued lines
2371 // ----------------------------------------------------------------------------
2372 // functions to translate string identifiers to integer or boolean value
2373 // ----------------------------------------------------------------------------
2375 int get_integer_from_string(char *s)
2377 static char *number_text[][3] =
2379 { "0", "zero", "null", },
2380 { "1", "one", "first" },
2381 { "2", "two", "second" },
2382 { "3", "three", "third" },
2383 { "4", "four", "fourth" },
2384 { "5", "five", "fifth" },
2385 { "6", "six", "sixth" },
2386 { "7", "seven", "seventh" },
2387 { "8", "eight", "eighth" },
2388 { "9", "nine", "ninth" },
2389 { "10", "ten", "tenth" },
2390 { "11", "eleven", "eleventh" },
2391 { "12", "twelve", "twelfth" },
2393 { NULL, NULL, NULL },
2397 char *s_lower = getStringToLower(s);
2400 for (i = 0; number_text[i][0] != NULL; i++)
2401 for (j = 0; j < 3; j++)
2402 if (strEqual(s_lower, number_text[i][j]))
2407 if (strEqual(s_lower, "false") ||
2408 strEqual(s_lower, "no") ||
2409 strEqual(s_lower, "off"))
2411 else if (strEqual(s_lower, "true") ||
2412 strEqual(s_lower, "yes") ||
2413 strEqual(s_lower, "on"))
2424 boolean get_boolean_from_string(char *s)
2426 char *s_lower = getStringToLower(s);
2427 boolean result = FALSE;
2429 if (strEqual(s_lower, "true") ||
2430 strEqual(s_lower, "yes") ||
2431 strEqual(s_lower, "on") ||
2432 get_integer_from_string(s) == 1)
2440 int get_switch3_from_string(char *s)
2442 char *s_lower = getStringToLower(s);
2445 if (strEqual(s_lower, "true") ||
2446 strEqual(s_lower, "yes") ||
2447 strEqual(s_lower, "on") ||
2448 get_integer_from_string(s) == 1)
2450 else if (strEqual(s_lower, "auto"))
2458 int get_player_nr_from_string(char *s)
2460 static char *player_text[] =
2470 char *s_lower = getStringToLower(s);
2474 for (i = 0; player_text[i] != NULL; i++)
2475 if (strEqual(s_lower, player_text[i]))
2484 // ----------------------------------------------------------------------------
2485 // functions for generic lists
2486 // ----------------------------------------------------------------------------
2488 ListNode *newListNode(void)
2490 return checked_calloc(sizeof(ListNode));
2493 void addNodeToList(ListNode **node_first, char *key, void *content)
2495 ListNode *node_new = newListNode();
2497 node_new->key = getStringCopy(key);
2498 node_new->content = content;
2499 node_new->next = *node_first;
2502 (*node_first)->prev = node_new;
2504 *node_first = node_new;
2507 void deleteNodeFromList(ListNode **node_first, char *key,
2508 void (*destructor_function)(void *))
2510 if (node_first == NULL || *node_first == NULL)
2513 if (strEqual((*node_first)->key, key))
2515 // after first recursion, (*node_first)->prev->next == *node_first,
2516 // so *node_first would be overwritten with (*node_first)->next
2517 // => use a copy of *node_first (and later of (*node_first)->next)
2518 ListNode *node = *node_first;
2519 ListNode *node_next = node->next;
2521 checked_free(node->key);
2523 if (destructor_function)
2524 destructor_function(node->content);
2527 node->prev->next = node->next;
2530 node->next->prev = node->prev;
2534 // after removing node, set list pointer to next valid list node
2535 // (this is important if the first node of the list was deleted)
2536 *node_first = node_next;
2540 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2544 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2546 if (node_first == NULL)
2549 if (strEqual(node_first->key, key))
2552 return getNodeFromKey(node_first->next, key);
2555 int getNumNodes(ListNode *node_first)
2557 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2561 static void dumpList(ListNode *node_first)
2563 ListNode *node = node_first;
2567 Debug("internal:dumpList", "['%s' (%d)]", node->key,
2568 ((struct ListNodeInfo *)node->content)->num_references);
2572 Debug("internal:dumpList", "[%d nodes]", getNumNodes(node_first));
2577 // ----------------------------------------------------------------------------
2578 // functions for file handling
2579 // ----------------------------------------------------------------------------
2581 #define MAX_BUFFER_SIZE 4096
2583 File *openFile(char *filename, char *mode)
2585 File *file = checked_calloc(sizeof(File));
2587 file->file = fopen(filename, mode);
2589 if (file->file != NULL)
2591 file->filename = getStringCopy(filename);
2596 #if defined(PLATFORM_ANDROID)
2597 file->asset_file = SDL_RWFromFile(filename, mode);
2599 if (file->asset_file != NULL)
2601 file->file_is_asset = TRUE;
2602 file->filename = getStringCopy(filename);
2613 int closeFile(File *file)
2620 #if defined(PLATFORM_ANDROID)
2621 if (file->asset_file)
2622 result = SDL_RWclose(file->asset_file);
2626 result = fclose(file->file);
2628 checked_free(file->filename);
2634 int checkEndOfFile(File *file)
2636 #if defined(PLATFORM_ANDROID)
2637 if (file->file_is_asset)
2638 return file->end_of_file;
2641 return feof(file->file);
2644 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2646 #if defined(PLATFORM_ANDROID)
2647 if (file->file_is_asset)
2649 if (file->end_of_file)
2652 size_t num_items_read =
2653 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2655 if (num_items_read < num_items)
2656 file->end_of_file = TRUE;
2658 return num_items_read;
2662 return fread(buffer, item_size, num_items, file->file);
2665 size_t writeFile(File *file, void *buffer, size_t item_size, size_t num_items)
2667 return fwrite(buffer, item_size, num_items, file->file);
2670 int seekFile(File *file, long offset, int whence)
2672 #if defined(PLATFORM_ANDROID)
2673 if (file->file_is_asset)
2675 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2676 whence == SEEK_CUR ? RW_SEEK_CUR :
2677 whence == SEEK_END ? RW_SEEK_END : 0);
2679 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2683 return fseek(file->file, offset, whence);
2686 int getByteFromFile(File *file)
2688 #if defined(PLATFORM_ANDROID)
2689 if (file->file_is_asset)
2691 if (file->end_of_file)
2695 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2697 if (num_bytes_read < 1)
2698 file->end_of_file = TRUE;
2700 return (file->end_of_file ? EOF : (int)c);
2704 return fgetc(file->file);
2707 char *getStringFromFile(File *file, char *line, int size)
2709 #if defined(PLATFORM_ANDROID)
2710 if (file->file_is_asset)
2712 if (file->end_of_file)
2715 char *line_ptr = line;
2716 int num_bytes_read = 0;
2718 while (num_bytes_read < size - 1 &&
2719 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2720 *line_ptr++ != '\n')
2725 if (strlen(line) == 0)
2727 file->end_of_file = TRUE;
2736 return fgets(line, size, file->file);
2739 int copyFile(char *filename_from, char *filename_to)
2741 File *file_from, *file_to;
2743 if ((file_from = openFile(filename_from, MODE_READ)) == NULL)
2748 if ((file_to = openFile(filename_to, MODE_WRITE)) == NULL)
2750 closeFile(file_from);
2755 while (!checkEndOfFile(file_from))
2757 byte buffer[MAX_BUFFER_SIZE];
2758 size_t bytes_read = readFile(file_from, buffer, 1, MAX_BUFFER_SIZE);
2760 writeFile(file_to, buffer, 1, bytes_read);
2763 closeFile(file_from);
2770 // ----------------------------------------------------------------------------
2771 // functions for directory handling
2772 // ----------------------------------------------------------------------------
2774 Directory *openDirectory(char *dir_name)
2776 Directory *dir = checked_calloc(sizeof(Directory));
2778 dir->dir = opendir(dir_name);
2780 if (dir->dir != NULL)
2782 dir->filename = getStringCopy(dir_name);
2787 #if defined(PLATFORM_ANDROID)
2788 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2790 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2792 checked_free(asset_toc_filename);
2794 if (dir->asset_toc_file != NULL)
2796 dir->directory_is_asset = TRUE;
2797 dir->filename = getStringCopy(dir_name);
2808 int closeDirectory(Directory *dir)
2815 #if defined(PLATFORM_ANDROID)
2816 if (dir->asset_toc_file)
2817 result = SDL_RWclose(dir->asset_toc_file);
2821 result = closedir(dir->dir);
2824 freeDirectoryEntry(dir->dir_entry);
2826 checked_free(dir->filename);
2832 DirectoryEntry *readDirectory(Directory *dir)
2835 freeDirectoryEntry(dir->dir_entry);
2837 dir->dir_entry = NULL;
2839 #if defined(PLATFORM_ANDROID)
2840 if (dir->directory_is_asset)
2842 char line[MAX_LINE_LEN];
2843 char *line_ptr = line;
2844 int num_bytes_read = 0;
2846 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2847 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2856 if (strlen(line) == 0)
2859 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2861 dir->dir_entry->is_directory = FALSE;
2862 if (line[strlen(line) - 1] == '/')
2864 dir->dir_entry->is_directory = TRUE;
2866 line[strlen(line) - 1] = '\0';
2869 dir->dir_entry->basename = getStringCopy(line);
2870 dir->dir_entry->filename = getPath2(dir->filename, line);
2872 return dir->dir_entry;
2876 struct dirent *dir_entry = readdir(dir->dir);
2878 if (dir_entry == NULL)
2881 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2883 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2884 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2886 struct stat file_status;
2888 dir->dir_entry->is_directory =
2889 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2890 S_ISDIR(file_status.st_mode));
2892 return dir->dir_entry;
2895 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2897 if (dir_entry == NULL)
2900 checked_free(dir_entry->basename);
2901 checked_free(dir_entry->filename);
2902 checked_free(dir_entry);
2906 // ----------------------------------------------------------------------------
2907 // functions for checking files and filenames
2908 // ----------------------------------------------------------------------------
2910 boolean directoryExists(char *dir_name)
2912 if (dir_name == NULL)
2915 struct stat file_status;
2916 boolean success = (stat(dir_name, &file_status) == 0 &&
2917 S_ISDIR(file_status.st_mode));
2919 #if defined(PLATFORM_ANDROID)
2922 // this might be an asset directory; check by trying to open toc file
2923 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2924 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2926 checked_free(asset_toc_filename);
2928 success = (file != NULL);
2938 boolean fileExists(char *filename)
2940 if (filename == NULL)
2943 boolean success = (access(filename, F_OK) == 0);
2945 #if defined(PLATFORM_ANDROID)
2948 // this might be an asset file; check by trying to open it
2949 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2951 success = (file != NULL);
2962 static boolean fileHasPrefix(char *basename, char *prefix)
2964 static char *basename_lower = NULL;
2965 int basename_length, prefix_length;
2967 checked_free(basename_lower);
2969 if (basename == NULL || prefix == NULL)
2972 basename_lower = getStringToLower(basename);
2973 basename_length = strlen(basename_lower);
2974 prefix_length = strlen(prefix);
2976 if (basename_length > prefix_length + 1 &&
2977 basename_lower[prefix_length] == '.' &&
2978 strncmp(basename_lower, prefix, prefix_length) == 0)
2985 static boolean fileHasSuffix(char *basename, char *suffix)
2987 static char *basename_lower = NULL;
2988 int basename_length, suffix_length;
2990 checked_free(basename_lower);
2992 if (basename == NULL || suffix == NULL)
2995 basename_lower = getStringToLower(basename);
2996 basename_length = strlen(basename_lower);
2997 suffix_length = strlen(suffix);
2999 if (basename_length > suffix_length + 1 &&
3000 basename_lower[basename_length - suffix_length - 1] == '.' &&
3001 strEqual(&basename_lower[basename_length - suffix_length], suffix))
3007 static boolean FileCouldBeArtwork(char *filename)
3009 char *basename = getBaseNamePtr(filename);
3011 return (!strEqual(basename, ".") &&
3012 !strEqual(basename, "..") &&
3013 !fileHasSuffix(basename, "txt") &&
3014 !fileHasSuffix(basename, "conf") &&
3015 !directoryExists(filename));
3018 boolean FileIsGraphic(char *filename)
3020 return FileCouldBeArtwork(filename);
3023 boolean FileIsSound(char *filename)
3025 return FileCouldBeArtwork(filename);
3028 boolean FileIsMusic(char *filename)
3030 return FileCouldBeArtwork(filename);
3033 boolean FileIsArtworkType(char *filename, int type)
3035 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
3036 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
3037 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
3043 // ----------------------------------------------------------------------------
3044 // functions for loading artwork configuration information
3045 // ----------------------------------------------------------------------------
3047 char *get_mapped_token(char *token)
3049 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
3050 static char *map_token_prefix[][2] =
3052 { "char_procent", "char_percent" },
3053 { "bd_magic_wall_filling", "bd_magic_wall.filling" },
3054 { "bd_magic_wall_emptying", "bd_magic_wall.emptying" },
3055 { "bd_butterfly_left", "bd_butterfly.left" },
3056 { "bd_butterfly_right", "bd_butterfly.right" },
3057 { "bd_butterfly_up", "bd_butterfly.up" },
3058 { "bd_butterfly_down", "bd_butterfly.down" },
3059 { "bd_firefly_left", "bd_firefly.left" },
3060 { "bd_firefly_right", "bd_firefly.right" },
3061 { "bd_firefly_up", "bd_firefly.up" },
3062 { "bd_firefly_down", "bd_firefly.down" },
3068 for (i = 0; map_token_prefix[i][0] != NULL; i++)
3070 int len_token_prefix = strlen(map_token_prefix[i][0]);
3072 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
3073 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
3076 // change tokens containing ".gfx" by moving the "gfx" part to the very left
3077 char *gfx_substring = ".gfx";
3078 char *gfx_prefix = "gfx.";
3079 if (strstr(token, gfx_substring) != NULL)
3081 char *token_prefix = getStringCopy(token);
3082 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
3083 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
3086 // cut off token string at ".gfx" substring position
3087 *token_gfx_pos = '\0';
3089 // put together prefix "gfx." and token prefix and suffix without ".gfx"
3090 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
3094 return mapped_token;
3100 static char *get_special_base_token(struct ArtworkListInfo *artwork_info,
3103 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
3104 static struct ConfigTypeInfo prefix_list[] =
3106 { "global.anim_1" },
3107 { "global.anim_2" },
3108 { "global.anim_3" },
3109 { "global.anim_4" },
3110 { "global.anim_5" },
3111 { "global.anim_6" },
3112 { "global.anim_7" },
3113 { "global.anim_8" },
3114 { "global.anim_9" },
3115 { "global.anim_10" },
3116 { "global.anim_11" },
3117 { "global.anim_12" },
3118 { "global.anim_13" },
3119 { "global.anim_14" },
3120 { "global.anim_15" },
3121 { "global.anim_16" },
3122 { "global.anim_17" },
3123 { "global.anim_18" },
3124 { "global.anim_19" },
3125 { "global.anim_20" },
3126 { "global.anim_21" },
3127 { "global.anim_22" },
3128 { "global.anim_23" },
3129 { "global.anim_24" },
3130 { "global.anim_25" },
3131 { "global.anim_26" },
3132 { "global.anim_27" },
3133 { "global.anim_28" },
3134 { "global.anim_29" },
3135 { "global.anim_30" },
3136 { "global.anim_31" },
3137 { "global.anim_32" },
3141 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3142 boolean prefix_found = FALSE;
3146 // search for prefix to check if base token has to be created
3147 for (i = 0; prefix_list[i].token != NULL; i++)
3148 if (strPrefix(token, prefix_list[i].token))
3149 prefix_found = TRUE;
3154 // search for suffix (parameter) to determine base token length
3155 for (i = 0; suffix_list[i].token != NULL; i++)
3156 if (strSuffix(token, suffix_list[i].token))
3157 len_suffix = strlen(suffix_list[i].token);
3159 return getStringCopyN(token, strlen(token) - len_suffix);
3162 static void FreeCustomArtworkList(struct ArtworkListInfo *,
3163 struct ListNodeInfo ***, int *);
3165 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
3166 struct ConfigTypeInfo *suffix_list,
3167 char **ignore_tokens,
3168 int num_file_list_entries)
3170 SetupFileHash *ignore_tokens_hash;
3171 struct FileInfo *file_list;
3172 int num_file_list_entries_found = 0;
3173 int num_suffix_list_entries = 0;
3177 // create hash from list of tokens to be ignored (for quick access)
3178 ignore_tokens_hash = newSetupFileHash();
3179 for (i = 0; ignore_tokens[i] != NULL; i++)
3180 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
3182 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
3184 for (i = 0; suffix_list[i].token != NULL; i++)
3185 num_suffix_list_entries++;
3187 // always start with reliable default values
3188 for (i = 0; i < num_file_list_entries; i++)
3190 file_list[i].token = NULL;
3192 file_list[i].default_filename = NULL;
3193 file_list[i].filename = NULL;
3195 if (num_suffix_list_entries > 0)
3197 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3199 file_list[i].default_parameter = checked_calloc(parameter_array_size);
3200 file_list[i].parameter = checked_calloc(parameter_array_size);
3202 for (j = 0; j < num_suffix_list_entries; j++)
3204 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
3205 setString(&file_list[i].parameter[j], suffix_list[j].value);
3208 file_list[i].redefined = FALSE;
3209 file_list[i].fallback_to_default = FALSE;
3210 file_list[i].default_is_cloned = FALSE;
3216 for (i = 0; config_list[i].token != NULL; i++)
3218 int len_config_token = strlen(config_list[i].token);
3219 boolean is_file_entry = TRUE;
3221 for (j = 0; suffix_list[j].token != NULL; j++)
3223 int len_suffix = strlen(suffix_list[j].token);
3225 if (len_suffix < len_config_token &&
3226 strEqual(&config_list[i].token[len_config_token - len_suffix],
3227 suffix_list[j].token))
3229 setString(&file_list[list_pos].default_parameter[j],
3230 config_list[i].value);
3232 is_file_entry = FALSE;
3238 // the following tokens are no file definitions, but other config tokens
3239 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
3240 is_file_entry = FALSE;
3247 if (list_pos >= num_file_list_entries)
3250 file_list[list_pos].token = config_list[i].token;
3251 file_list[list_pos].default_filename = config_list[i].value;
3254 if (strSuffix(config_list[i].token, ".clone_from"))
3255 file_list[list_pos].default_is_cloned = TRUE;
3258 num_file_list_entries_found = list_pos + 1;
3259 if (num_file_list_entries_found != num_file_list_entries)
3262 Error("inconsistant config list information:");
3263 Error("- should be: %d (according to 'src/conf_xxx.h')",
3264 num_file_list_entries);
3265 Error("- found to be: %d (according to 'src/conf_xxx.c')",
3266 num_file_list_entries_found);
3271 freeSetupFileHash(ignore_tokens_hash);
3276 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3278 int len_token = strlen(token);
3279 int len_suffix = strlen(suffix);
3281 if (start_pos < 0) // compare suffix from end of string
3282 start_pos += len_token;
3284 if (start_pos < 0 || start_pos + len_suffix > len_token)
3287 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3290 if (token[start_pos + len_suffix] == '\0')
3293 if (token[start_pos + len_suffix] == '.')
3299 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3301 static void read_token_parameters(SetupFileHash *setup_file_hash,
3302 struct ConfigTypeInfo *suffix_list,
3303 struct FileInfo *file_list_entry)
3305 // check for config token that is the base token without any suffixes
3306 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3307 char *known_token_value = KNOWN_TOKEN_VALUE;
3310 if (filename != NULL)
3312 setString(&file_list_entry->filename, filename);
3314 // when file definition found, set all parameters to default values
3315 for (i = 0; suffix_list[i].token != NULL; i++)
3316 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3318 file_list_entry->redefined = TRUE;
3320 // mark config file token as well known from default config
3321 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3324 // check for config tokens that can be build by base token and suffixes
3325 for (i = 0; suffix_list[i].token != NULL; i++)
3327 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3328 char *value = getHashEntry(setup_file_hash, token);
3332 setString(&file_list_entry->parameter[i], value);
3334 // mark config file token as well known from default config
3335 setHashEntry(setup_file_hash, token, known_token_value);
3342 static void add_dynamic_file_list_entry(struct FileInfo **list,
3343 int *num_list_entries,
3344 SetupFileHash *extra_file_hash,
3345 struct ConfigTypeInfo *suffix_list,
3346 int num_suffix_list_entries,
3349 struct FileInfo *new_list_entry;
3350 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3352 (*num_list_entries)++;
3353 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3354 new_list_entry = &(*list)[*num_list_entries - 1];
3356 new_list_entry->token = getStringCopy(token);
3357 new_list_entry->default_filename = NULL;
3358 new_list_entry->filename = NULL;
3359 new_list_entry->parameter = checked_calloc(parameter_array_size);
3361 new_list_entry->redefined = FALSE;
3362 new_list_entry->fallback_to_default = FALSE;
3363 new_list_entry->default_is_cloned = FALSE;
3365 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3368 static void add_property_mapping(struct PropertyMapping **list,
3369 int *num_list_entries,
3370 int base_index, int ext1_index,
3371 int ext2_index, int ext3_index,
3374 struct PropertyMapping *new_list_entry;
3376 (*num_list_entries)++;
3377 *list = checked_realloc(*list,
3378 *num_list_entries * sizeof(struct PropertyMapping));
3379 new_list_entry = &(*list)[*num_list_entries - 1];
3381 new_list_entry->base_index = base_index;
3382 new_list_entry->ext1_index = ext1_index;
3383 new_list_entry->ext2_index = ext2_index;
3384 new_list_entry->ext3_index = ext3_index;
3386 new_list_entry->artwork_index = artwork_index;
3389 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3392 struct FileInfo *file_list = artwork_info->file_list;
3393 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3394 char **base_prefixes = artwork_info->base_prefixes;
3395 char **ext1_suffixes = artwork_info->ext1_suffixes;
3396 char **ext2_suffixes = artwork_info->ext2_suffixes;
3397 char **ext3_suffixes = artwork_info->ext3_suffixes;
3398 char **ignore_tokens = artwork_info->ignore_tokens;
3399 int num_file_list_entries = artwork_info->num_file_list_entries;
3400 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3401 int num_base_prefixes = artwork_info->num_base_prefixes;
3402 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3403 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3404 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3405 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3406 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3407 SetupFileHash *extra_file_hash, *empty_file_hash;
3408 char *known_token_value = KNOWN_TOKEN_VALUE;
3409 char *base_token_value = UNDEFINED_FILENAME;
3412 if (filename == NULL)
3415 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3418 // separate valid (defined) from empty (undefined) config token values
3419 valid_file_hash = newSetupFileHash();
3420 empty_file_hash = newSetupFileHash();
3421 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3423 char *value = HASH_ITERATION_VALUE(itr);
3425 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3426 HASH_ITERATION_TOKEN(itr), value);
3428 END_HASH_ITERATION(setup_file_hash, itr)
3430 // at this point, we do not need the setup file hash anymore -- free it
3431 freeSetupFileHash(setup_file_hash);
3433 // prevent changing hash while iterating over it by using a temporary copy
3434 valid_file_hash_tmp = newSetupFileHash();
3435 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3437 setHashEntry(valid_file_hash_tmp,
3438 HASH_ITERATION_TOKEN(itr),
3439 HASH_ITERATION_VALUE(itr));
3441 END_HASH_ITERATION(valid_file_hash, itr)
3443 // (iterate over same temporary hash, as modifications are independent)
3445 // map deprecated to current tokens (using prefix match and replace)
3446 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3448 char *token = HASH_ITERATION_TOKEN(itr);
3449 char *mapped_token = get_mapped_token(token);
3451 if (mapped_token != NULL)
3453 char *value = HASH_ITERATION_VALUE(itr);
3456 setHashEntry(valid_file_hash, mapped_token, value);
3458 // ignore old token (by setting it to "known" keyword)
3459 setHashEntry(valid_file_hash, token, known_token_value);
3464 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3466 // add special base tokens (using prefix match and replace)
3467 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3469 char *token = HASH_ITERATION_TOKEN(itr);
3470 char *base_token = get_special_base_token(artwork_info, token);
3472 if (base_token != NULL)
3474 // add base token only if it does not already exist
3475 if (getHashEntry(valid_file_hash, base_token) == NULL)
3476 setHashEntry(valid_file_hash, base_token, base_token_value);
3481 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3483 // free temporary hash used for iteration
3484 freeSetupFileHash(valid_file_hash_tmp);
3486 // read parameters for all known config file tokens
3487 for (i = 0; i < num_file_list_entries; i++)
3488 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3490 // set all tokens that can be ignored here to "known" keyword
3491 for (i = 0; i < num_ignore_tokens; i++)
3492 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3494 // copy all unknown config file tokens to extra config hash
3495 extra_file_hash = newSetupFileHash();
3496 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3498 char *value = HASH_ITERATION_VALUE(itr);
3500 if (!strEqual(value, known_token_value))
3501 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3503 END_HASH_ITERATION(valid_file_hash, itr)
3505 // at this point, we do not need the valid file hash anymore -- free it
3506 freeSetupFileHash(valid_file_hash);
3508 // now try to determine valid, dynamically defined config tokens
3510 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3512 struct FileInfo **dynamic_file_list =
3513 &artwork_info->dynamic_file_list;
3514 int *num_dynamic_file_list_entries =
3515 &artwork_info->num_dynamic_file_list_entries;
3516 struct PropertyMapping **property_mapping =
3517 &artwork_info->property_mapping;
3518 int *num_property_mapping_entries =
3519 &artwork_info->num_property_mapping_entries;
3520 int current_summarized_file_list_entry =
3521 artwork_info->num_file_list_entries +
3522 artwork_info->num_dynamic_file_list_entries;
3523 char *token = HASH_ITERATION_TOKEN(itr);
3524 int len_token = strlen(token);
3526 boolean base_prefix_found = FALSE;
3527 boolean parameter_suffix_found = FALSE;
3529 // skip all parameter definitions (handled by read_token_parameters())
3530 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3532 int len_suffix = strlen(suffix_list[i].token);
3534 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3535 parameter_suffix_found = TRUE;
3538 if (parameter_suffix_found)
3541 // ---------- step 0: search for matching base prefix ----------
3544 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3546 char *base_prefix = base_prefixes[i];
3547 int len_base_prefix = strlen(base_prefix);
3548 boolean ext1_suffix_found = FALSE;
3549 boolean ext2_suffix_found = FALSE;
3550 boolean ext3_suffix_found = FALSE;
3551 boolean exact_match = FALSE;
3552 int base_index = -1;
3553 int ext1_index = -1;
3554 int ext2_index = -1;
3555 int ext3_index = -1;
3557 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3559 if (!base_prefix_found)
3564 if (start_pos + len_base_prefix == len_token) // exact match
3568 add_dynamic_file_list_entry(dynamic_file_list,
3569 num_dynamic_file_list_entries,
3572 num_suffix_list_entries,
3574 add_property_mapping(property_mapping,
3575 num_property_mapping_entries,
3576 base_index, -1, -1, -1,
3577 current_summarized_file_list_entry);
3581 // ---------- step 1: search for matching first suffix ----------
3583 start_pos += len_base_prefix;
3584 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3586 char *ext1_suffix = ext1_suffixes[j];
3587 int len_ext1_suffix = strlen(ext1_suffix);
3589 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3591 if (!ext1_suffix_found)
3596 if (start_pos + len_ext1_suffix == len_token) // exact match
3600 add_dynamic_file_list_entry(dynamic_file_list,
3601 num_dynamic_file_list_entries,
3604 num_suffix_list_entries,
3606 add_property_mapping(property_mapping,
3607 num_property_mapping_entries,
3608 base_index, ext1_index, -1, -1,
3609 current_summarized_file_list_entry);
3613 start_pos += len_ext1_suffix;
3619 // ---------- step 2: search for matching second suffix ----------
3621 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3623 char *ext2_suffix = ext2_suffixes[k];
3624 int len_ext2_suffix = strlen(ext2_suffix);
3626 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3628 if (!ext2_suffix_found)
3633 if (start_pos + len_ext2_suffix == len_token) // exact match
3637 add_dynamic_file_list_entry(dynamic_file_list,
3638 num_dynamic_file_list_entries,
3641 num_suffix_list_entries,
3643 add_property_mapping(property_mapping,
3644 num_property_mapping_entries,
3645 base_index, ext1_index, ext2_index, -1,
3646 current_summarized_file_list_entry);
3650 start_pos += len_ext2_suffix;
3656 // ---------- step 3: search for matching third suffix ----------
3658 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3660 char *ext3_suffix = ext3_suffixes[l];
3661 int len_ext3_suffix = strlen(ext3_suffix);
3663 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3665 if (!ext3_suffix_found)
3670 if (start_pos + len_ext3_suffix == len_token) // exact match
3674 add_dynamic_file_list_entry(dynamic_file_list,
3675 num_dynamic_file_list_entries,
3678 num_suffix_list_entries,
3680 add_property_mapping(property_mapping,
3681 num_property_mapping_entries,
3682 base_index, ext1_index, ext2_index, ext3_index,
3683 current_summarized_file_list_entry);
3689 END_HASH_ITERATION(extra_file_hash, itr)
3691 if (artwork_info->num_dynamic_file_list_entries > 0)
3693 artwork_info->dynamic_artwork_list =
3694 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3695 artwork_info->sizeof_artwork_list_entry);
3698 if (options.verbose && IS_PARENT_PROCESS())
3700 SetupFileList *setup_file_list, *list;
3701 boolean dynamic_tokens_found = FALSE;
3702 boolean unknown_tokens_found = FALSE;
3703 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3705 // list may be NULL for empty artwork config files
3706 setup_file_list = loadSetupFileList(filename);
3708 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3710 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3711 dynamic_tokens_found = TRUE;
3713 unknown_tokens_found = TRUE;
3715 END_HASH_ITERATION(extra_file_hash, itr)
3717 if (options.debug && dynamic_tokens_found)
3719 Debug("config", "---");
3720 Debug("config", "dynamic token(s) found in config file:");
3721 Debug("config", "- config file: '%s'", filename);
3723 for (list = setup_file_list; list != NULL; list = list->next)
3725 char *value = getHashEntry(extra_file_hash, list->token);
3727 if (value != NULL && strEqual(value, known_token_value))
3728 Debug("config", "- dynamic token: '%s'", list->token);
3731 Debug("config", "---");
3734 if (unknown_tokens_found)
3737 Warn("unknown token(s) found in config file:");
3738 Warn("- config file: '%s'", filename);
3740 for (list = setup_file_list; list != NULL; list = list->next)
3742 char *value = getHashEntry(extra_file_hash, list->token);
3744 if (value != NULL && !strEqual(value, known_token_value))
3745 Warn("- dynamic token: '%s'", list->token);
3751 if (undefined_values_found)
3754 Warn("undefined values found in config file:");
3755 Warn("- config file: '%s'", filename);
3757 for (list = setup_file_list; list != NULL; list = list->next)
3759 char *value = getHashEntry(empty_file_hash, list->token);
3762 Warn("- undefined value for token: '%s'", list->token);
3768 freeSetupFileList(setup_file_list);
3771 freeSetupFileHash(extra_file_hash);
3772 freeSetupFileHash(empty_file_hash);
3775 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3777 struct FileInfo *file_list = artwork_info->file_list;
3778 int num_file_list_entries = artwork_info->num_file_list_entries;
3779 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3780 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3783 DrawInitTextHead("Loading artwork config");
3784 DrawInitTextItem(ARTWORKINFO_FILENAME(artwork_info->type));
3786 // always start with reliable default values
3787 for (i = 0; i < num_file_list_entries; i++)
3789 setString(&file_list[i].filename, file_list[i].default_filename);
3791 for (j = 0; j < num_suffix_list_entries; j++)
3792 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3794 file_list[i].redefined = FALSE;
3795 file_list[i].fallback_to_default = FALSE;
3798 // free previous dynamic artwork file array
3799 if (artwork_info->dynamic_file_list != NULL)
3801 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3803 free(artwork_info->dynamic_file_list[i].token);
3804 free(artwork_info->dynamic_file_list[i].filename);
3805 free(artwork_info->dynamic_file_list[i].parameter);
3808 free(artwork_info->dynamic_file_list);
3809 artwork_info->dynamic_file_list = NULL;
3811 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3812 &artwork_info->num_dynamic_file_list_entries);
3815 // free previous property mapping
3816 if (artwork_info->property_mapping != NULL)
3818 free(artwork_info->property_mapping);
3820 artwork_info->property_mapping = NULL;
3821 artwork_info->num_property_mapping_entries = 0;
3824 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3826 // first look for special artwork configured in level series config
3827 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3829 if (fileExists(filename_base))
3830 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3833 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3835 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3836 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3839 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3840 struct ListNodeInfo **listnode)
3844 char *filename = (*listnode)->source_filename;
3846 if (--(*listnode)->num_references <= 0)
3847 deleteNodeFromList(&artwork_info->content_list, filename,
3848 artwork_info->free_artwork);
3854 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3855 struct ListNodeInfo **listnode,
3856 struct FileInfo *file_list_entry)
3866 char *basename = file_list_entry->filename;
3867 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3869 // mark all images from non-default graphics directory as "redefined"
3870 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS &&
3871 !strPrefix(filename, options.graphics_directory))
3872 file_list_entry->redefined = TRUE;
3874 if (filename == NULL)
3876 Warn("cannot find artwork file '%s'", basename);
3878 basename = file_list_entry->default_filename;
3880 // fail for cloned default artwork that has no default filename defined
3881 if (file_list_entry->default_is_cloned &&
3882 strEqual(basename, UNDEFINED_FILENAME))
3884 void (*error_func)(char *, ...) = Warn;
3886 // we can get away without sounds and music, but not without graphics
3887 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3890 error_func("token '%s' was cloned and has no default filename",
3891 file_list_entry->token);
3896 // dynamic artwork has no default filename / skip empty default artwork
3897 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3900 file_list_entry->fallback_to_default = TRUE;
3902 Warn("trying default artwork file '%s'", basename);
3904 filename = getCustomArtworkFilename(basename, artwork_info->type);
3906 if (filename == NULL)
3908 void (*error_func)(char *, ...) = Warn;
3910 // we can get away without sounds and music, but not without graphics
3911 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3914 error_func("cannot find default artwork file '%s'", basename);
3920 // check if the old and the new artwork file are the same
3921 if (*listnode && strEqual((*listnode)->source_filename, filename))
3923 // The old and new artwork are the same (have the same filename and path).
3924 // This usually means that this artwork does not exist in this artwork set
3925 // and a fallback to the existing artwork is done.
3930 // delete existing artwork file entry
3931 deleteArtworkListEntry(artwork_info, listnode);
3933 // check if the new artwork file already exists in the list of artwork
3934 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3936 *listnode = (struct ListNodeInfo *)node->content;
3937 (*listnode)->num_references++;
3942 DrawInitTextHead(init_text[artwork_info->type]);
3943 DrawInitTextItem(basename);
3945 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3947 // add new artwork file entry to the list of artwork files
3948 (*listnode)->num_references = 1;
3949 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3954 void (*error_func)(char *, ...) = Warn;
3956 // we can get away without sounds and music, but not without graphics
3957 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3960 error_func("cannot load artwork file '%s'", basename);
3966 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3967 struct ListNodeInfo **listnode,
3968 struct FileInfo *file_list_entry)
3970 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3972 deleteArtworkListEntry(artwork_info, listnode);
3977 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3980 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3982 struct FileInfo *file_list = artwork_info->file_list;
3983 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3984 int num_file_list_entries = artwork_info->num_file_list_entries;
3985 int num_dynamic_file_list_entries =
3986 artwork_info->num_dynamic_file_list_entries;
3989 print_timestamp_init("ReloadCustomArtworkList");
3991 for (i = 0; i < num_file_list_entries; i++)
3992 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3995 for (i = 0; i < num_dynamic_file_list_entries; i++)
3996 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3997 &dynamic_file_list[i]);
3999 print_timestamp_done("ReloadCustomArtworkList");
4002 dumpList(artwork_info->content_list);
4006 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
4007 struct ListNodeInfo ***list,
4008 int *num_list_entries)
4015 for (i = 0; i < *num_list_entries; i++)
4016 deleteArtworkListEntry(artwork_info, &(*list)[i]);
4020 *num_list_entries = 0;
4023 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
4025 if (artwork_info == NULL)
4028 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
4029 &artwork_info->num_file_list_entries);
4031 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
4032 &artwork_info->num_dynamic_file_list_entries);
4036 // ----------------------------------------------------------------------------
4037 // functions only needed for non-Unix (non-command-line) systems
4038 // (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")
4039 // (now also added for Windows, to create files in user data directory)
4040 // ----------------------------------------------------------------------------
4042 char *getLogFilename(char *basename)
4044 return getPath2(getMainUserGameDataDir(), basename);
4047 void OpenLogFiles(void)
4051 InitMainUserDataDirectory();
4053 for (i = 0; i < NUM_LOGS; i++)
4055 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
4058 program.log_file[i] = program.log_file_default[i]; // reset to default
4060 Warn("cannot open file '%s' for writing: %s",
4061 program.log_filename[i], strerror(errno));
4064 // output should be unbuffered so it is not truncated in a crash
4065 setbuf(program.log_file[i], NULL);
4069 void CloseLogFiles(void)
4073 for (i = 0; i < NUM_LOGS; i++)
4074 if (program.log_file[i] != program.log_file_default[i])
4075 fclose(program.log_file[i]);
4078 void DumpLogFile(int nr)
4080 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
4082 if (log_file == NULL)
4085 while (!feof(log_file))
4086 fputc(fgetc(log_file), stdout);
4091 void NotifyUserAboutErrorFile(void)
4093 #if defined(PLATFORM_WIN32)
4094 char *title_text = getStringCat2(program.program_title, " Error Message");
4095 char *error_text = getStringCat2("The program was aborted due to an error; "
4096 "for details, see the following error file:"
4098 program.log_filename[LOG_ERR_ID]);
4100 MessageBox(NULL, error_text, title_text, MB_OK);
4105 // ----------------------------------------------------------------------------
4106 // the following is only for debugging purpose and normally not used
4107 // ----------------------------------------------------------------------------
4111 #define DEBUG_PRINT_INIT_TIMESTAMPS TRUE
4112 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
4114 #define DEBUG_NUM_TIMESTAMPS 10
4115 #define DEBUG_TIME_IN_MICROSECONDS 0
4117 #if DEBUG_TIME_IN_MICROSECONDS
4118 static double Counter_Microseconds(void)
4120 static struct timeval base_time = { 0, 0 };
4121 struct timeval current_time;
4124 gettimeofday(¤t_time, NULL);
4126 // reset base time in case of wrap-around
4127 if (current_time.tv_sec < base_time.tv_sec)
4128 base_time = current_time;
4131 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
4132 ((double)(current_time.tv_usec - base_time.tv_usec));
4134 return counter; // return microseconds since last init
4138 static char *debug_print_timestamp_get_padding(int padding_size)
4140 static char *padding = NULL;
4141 int max_padding_size = 100;
4143 if (padding == NULL)
4145 padding = checked_calloc(max_padding_size + 1);
4146 memset(padding, ' ', max_padding_size);
4149 return &padding[MAX(0, max_padding_size - padding_size)];
4152 void debug_print_timestamp(int counter_nr, char *message)
4154 int indent_size = 8;
4155 int padding_size = 40;
4156 float timestamp_interval;
4159 Fail("debugging: invalid negative counter");
4160 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
4161 Fail("debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
4163 #if DEBUG_TIME_IN_MICROSECONDS
4164 static double counter[DEBUG_NUM_TIMESTAMPS][2];
4167 counter[counter_nr][0] = Counter_Microseconds();
4169 static int counter[DEBUG_NUM_TIMESTAMPS][2];
4172 counter[counter_nr][0] = Counter();
4175 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
4176 counter[counter_nr][1] = counter[counter_nr][0];
4179 Debug("time:init", "%s%s%s %.3f %s",
4180 debug_print_timestamp_get_padding(counter_nr * indent_size),
4182 debug_print_timestamp_get_padding(padding_size - strlen(message)),
4183 timestamp_interval / 1000,
4188 static void debug_print_parent_only(char *format, ...)
4190 if (!IS_PARENT_PROCESS())
4197 va_start(ap, format);
4198 vprintf(format, ap);
4208 static void print_timestamp_ext(char *message, char *mode)
4210 #if DEBUG_PRINT_INIT_TIMESTAMPS
4211 static char *debug_message = NULL;
4212 static char *last_message = NULL;
4213 static int counter_nr = 0;
4214 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
4216 checked_free(debug_message);
4217 debug_message = getStringCat3(mode, " ", message);
4219 if (strEqual(mode, "INIT"))
4221 debug_print_timestamp(counter_nr, NULL);
4223 if (counter_nr + 1 < max_depth)
4224 debug_print_timestamp(counter_nr, debug_message);
4228 debug_print_timestamp(counter_nr, NULL);
4230 else if (strEqual(mode, "DONE"))
4234 if (counter_nr + 1 < max_depth ||
4235 (counter_nr == 0 && max_depth == 1))
4237 last_message = message;
4239 if (counter_nr == 0 && max_depth == 1)
4241 checked_free(debug_message);
4242 debug_message = getStringCat3("TIME", " ", message);
4245 debug_print_timestamp(counter_nr, debug_message);
4248 else if (!strEqual(mode, "TIME") ||
4249 !strEqual(message, last_message))
4251 if (counter_nr < max_depth)
4252 debug_print_timestamp(counter_nr, debug_message);
4257 void print_timestamp_init(char *message)
4259 print_timestamp_ext(message, "INIT");
4262 void print_timestamp_time(char *message)
4264 print_timestamp_ext(message, "TIME");
4267 void print_timestamp_done(char *message)
4269 print_timestamp_ext(message, "DONE");