1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
14 #include <sys/types.h>
24 #if !defined(PLATFORM_WIN32)
26 #include <sys/param.h>
36 /* ========================================================================= */
37 /* some generic helper functions */
38 /* ========================================================================= */
40 /* ------------------------------------------------------------------------- */
41 /* logging functions */
42 /* ------------------------------------------------------------------------- */
44 #define DUPLICATE_LOG_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 /* string functions */
256 /* ------------------------------------------------------------------------- */
258 /* int2str() returns a number converted to a string;
259 the used memory is static, but will be overwritten by later calls,
260 so if you want to save the result, copy it to a private string buffer;
261 there can be 10 local calls of int2str() without buffering the result --
262 the 11th call will then destroy the result from the first call and so on.
265 char *int2str(int number, int size)
267 static char shift_array[10][40];
268 static int shift_counter = 0;
269 char *s = shift_array[shift_counter];
271 shift_counter = (shift_counter + 1) % 10;
278 sprintf(s, " %09d", number);
279 return &s[strlen(s) - size];
283 sprintf(s, "%d", number);
289 /* something similar to "int2str()" above, but allocates its own memory
290 and has a different interface; we cannot use "itoa()", because this
291 seems to be already defined when cross-compiling to the win32 target */
293 char *i_to_a(unsigned int i)
295 static char *a = NULL;
299 if (i > 2147483647) /* yes, this is a kludge */
302 a = checked_malloc(10 + 1);
310 /* calculate base-2 logarithm of argument (rounded down to integer;
311 this function returns the number of the highest bit set in argument) */
313 int log_2(unsigned int x)
319 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
326 boolean getTokenValueFromString(char *string, char **token, char **value)
328 return getTokenValueFromSetupLine(string, token, value);
332 /* ------------------------------------------------------------------------- */
333 /* counter functions */
334 /* ------------------------------------------------------------------------- */
336 /* maximal allowed length of a command line option */
337 #define MAX_OPTION_LEN 256
339 static unsigned int getCurrentMS()
341 return SDL_GetTicks();
344 static unsigned int mainCounter(int mode)
346 static unsigned int base_ms = 0;
347 unsigned int current_ms;
349 /* get current system milliseconds */
350 current_ms = getCurrentMS();
352 /* reset base timestamp in case of counter reset or wrap-around */
353 if (mode == INIT_COUNTER || current_ms < base_ms)
354 base_ms = current_ms;
356 /* return milliseconds since last counter reset */
357 return current_ms - base_ms;
360 void InitCounter() /* set counter back to zero */
362 mainCounter(INIT_COUNTER);
365 unsigned int Counter() /* get milliseconds since last call of InitCounter() */
367 return mainCounter(READ_COUNTER);
370 static void sleep_milliseconds(unsigned int milliseconds_delay)
372 SDL_Delay(milliseconds_delay);
375 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
377 sleep_milliseconds(delay);
380 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
381 unsigned int actual_counter)
383 if (actual_counter >= *counter_var &&
384 actual_counter < *counter_var + delay)
387 *counter_var = actual_counter;
392 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
394 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
397 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
399 return DelayReachedExt(counter_var, delay, Counter());
402 void ResetDelayCounterExt(unsigned int *counter_var,
403 unsigned int actual_counter)
405 DelayReachedExt(counter_var, 0, actual_counter);
408 void ResetFrameCounter(unsigned int *frame_counter_var)
410 FrameReached(frame_counter_var, 0);
413 void ResetDelayCounter(unsigned int *counter_var)
415 DelayReached(counter_var, 0);
418 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
420 unsigned int actual_counter;
425 actual_counter = Counter();
427 if (actual_counter >= *counter_var &&
428 actual_counter < *counter_var + delay)
429 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
434 if (*counter_var != 0 &&
436 actual_counter >= *counter_var + delay)
438 int lag = actual_counter - (*counter_var + delay);
439 int delay2 = (delay + 1) / 2;
442 skip_frames = (lag + delay2) / delay;
445 *counter_var = actual_counter;
450 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
451 int *loop_var, int last_loop_value)
453 int skip_frames = WaitUntilDelayReached(counter_var, delay);
457 printf("::: %d: %d ms", *loop_var, delay);
459 printf(" -> SKIP %d FRAME(S) [%d ms]", skip_frames, skip_frames * delay);
464 if (skip_frames == 0)
467 // when skipping frames, make sure to never skip the last frame, as
468 // this may be needed for animations to reach a defined end state;
469 // furthermore, we assume that this function is called at the end
470 // of a "for" loop, which continues by incrementing the loop variable
471 // by one before checking the loop condition again; therefore we have
472 // to check against the last loop value minus one here
476 if (*loop_var < last_loop_value) // never skip the last frame
478 *loop_var += skip_frames;
480 if (*loop_var > last_loop_value) // never skip the last frame
481 *loop_var = last_loop_value;
486 /* ------------------------------------------------------------------------- */
487 /* random generator functions */
488 /* ------------------------------------------------------------------------- */
490 unsigned int init_random_number(int nr, int seed)
492 if (seed == NEW_RANDOMIZE)
494 /* default random seed */
495 seed = (int)time(NULL); // seconds since the epoch
497 #if !defined(PLATFORM_WIN32)
498 /* add some more randomness */
499 struct timeval current_time;
501 gettimeofday(¤t_time, NULL);
503 seed += (int)current_time.tv_usec; // microseconds since the epoch
506 /* add some more randomness */
507 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
509 /* add some more randomness */
510 seed += GetSimpleRandom(1000000);
513 srandom_linux_libc(nr, (unsigned int) seed);
515 return (unsigned int) seed;
518 unsigned int get_random_number(int nr, int max)
520 return (max > 0 ? random_linux_libc(nr) % max : 0);
524 /* ------------------------------------------------------------------------- */
525 /* system info functions */
526 /* ------------------------------------------------------------------------- */
528 #if !defined(PLATFORM_ANDROID)
529 static char *get_corrected_real_name(char *real_name)
531 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
532 char *from_ptr = real_name;
533 char *to_ptr = real_name_new;
535 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
536 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
538 /* the name field read from "passwd" file may also contain additional
539 user information, separated by commas, which will be removed here */
540 if (*from_ptr == ',')
543 /* the user's real name may contain 'german sharp s' characters,
544 which have no equivalent in upper case letters (used by our fonts) */
545 if (*from_ptr == CHAR_BYTE_SHARP_S)
552 *to_ptr++ = *from_ptr++;
557 return real_name_new;
563 static char *login_name = NULL;
565 #if defined(PLATFORM_WIN32)
566 if (login_name == NULL)
568 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
569 login_name = checked_malloc(buffer_size);
571 if (GetUserName(login_name, &buffer_size) == 0)
572 strcpy(login_name, ANONYMOUS_NAME);
575 if (login_name == NULL)
579 if ((pwd = getpwuid(getuid())) == NULL)
580 login_name = ANONYMOUS_NAME;
582 login_name = getStringCopy(pwd->pw_name);
591 static char *real_name = NULL;
593 #if defined(PLATFORM_WIN32)
594 if (real_name == NULL)
596 static char buffer[MAX_USERNAME_LEN + 1];
597 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
599 if (GetUserName(buffer, &buffer_size) != 0)
600 real_name = get_corrected_real_name(buffer);
602 real_name = ANONYMOUS_NAME;
604 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
605 if (real_name == NULL)
609 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
610 real_name = get_corrected_real_name(pwd->pw_gecos);
612 real_name = ANONYMOUS_NAME;
615 real_name = ANONYMOUS_NAME;
621 time_t getFileTimestampEpochSeconds(char *filename)
623 struct stat file_status;
625 if (stat(filename, &file_status) != 0) /* cannot stat file */
628 return file_status.st_mtime;
632 /* ------------------------------------------------------------------------- */
633 /* path manipulation functions */
634 /* ------------------------------------------------------------------------- */
636 static char *getLastPathSeparatorPtr(char *filename)
638 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
640 if (last_separator == NULL) /* also try DOS/Windows variant */
641 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
643 return last_separator;
646 char *getBaseNamePtr(char *filename)
648 char *last_separator = getLastPathSeparatorPtr(filename);
650 if (last_separator != NULL)
651 return last_separator + 1; /* separator found: strip base path */
653 return filename; /* no separator found: filename has no path */
656 char *getBaseName(char *filename)
658 return getStringCopy(getBaseNamePtr(filename));
661 char *getBaseNameNoSuffix(char *filename)
663 char *basename = getStringCopy(getBaseNamePtr(filename));
665 // remove trailing suffix (separated by dot or hyphen)
666 if (basename[0] != '.' && basename[0] != '-')
668 if (strchr(basename, '.') != NULL)
669 *strchr(basename, '.') = '\0';
671 if (strchr(basename, '-') != NULL)
672 *strchr(basename, '-') = '\0';
678 char *getBasePath(char *filename)
680 char *basepath = getStringCopy(filename);
681 char *last_separator = getLastPathSeparatorPtr(basepath);
683 if (last_separator != NULL)
684 *last_separator = '\0'; /* separator found: strip basename */
686 basepath = "."; /* no separator found: use current path */
691 static char *getProgramMainDataPath()
693 char *main_data_path = getStringCopy(program.command_basepath);
695 #if defined(PLATFORM_MACOSX)
696 static char *main_data_binary_subdir = NULL;
697 static char *main_data_files_subdir = NULL;
699 if (main_data_binary_subdir == NULL)
701 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
703 strlen(MAC_APP_BINARY_SUBDIR) + 1);
705 sprintf(main_data_binary_subdir, "%s.app/%s",
706 program.program_title, MAC_APP_BINARY_SUBDIR);
709 if (main_data_files_subdir == NULL)
711 main_data_files_subdir = checked_malloc(strlen(program.program_title) + 1 +
713 strlen(MAC_APP_FILES_SUBDIR) + 1);
715 sprintf(main_data_files_subdir, "%s.app/%s",
716 program.program_title, MAC_APP_FILES_SUBDIR);
719 if (strSuffix(main_data_path, main_data_binary_subdir))
721 char *main_data_path_old = main_data_path;
723 // cut relative path to Mac OS X application binary directory from path
724 main_data_path[strlen(main_data_path) -
725 strlen(main_data_binary_subdir)] = '\0';
727 // cut trailing path separator from path (but not if path is root directory)
728 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
729 main_data_path[strlen(main_data_path) - 1] = '\0';
731 // replace empty path with current directory
732 if (strEqual(main_data_path, ""))
733 main_data_path = ".";
735 // add relative path to Mac OS X application resources directory to path
736 main_data_path = getPath2(main_data_path, main_data_files_subdir);
738 free(main_data_path_old);
742 return main_data_path;
746 /* ------------------------------------------------------------------------- */
747 /* various string functions */
748 /* ------------------------------------------------------------------------- */
750 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
752 if (s1 == NULL || s2 == NULL || sep == NULL)
755 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
758 sprintf(complete_string, "%s%s%s", s1, sep, s2);
760 return complete_string;
763 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
765 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
768 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
769 strlen(s2) + strlen(sep) +
772 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
774 return complete_string;
777 char *getStringCat2(char *s1, char *s2)
779 return getStringCat2WithSeparator(s1, s2, "");
782 char *getStringCat3(char *s1, char *s2, char *s3)
784 return getStringCat3WithSeparator(s1, s2, s3, "");
787 char *getPath2(char *path1, char *path2)
789 #if defined(PLATFORM_ANDROID)
790 // workaround for reading from assets directory -- skip "." subdirs in path
791 if (strEqual(path1, "."))
792 return getStringCopy(path2);
793 else if (strEqual(path2, "."))
794 return getStringCopy(path1);
797 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
800 char *getPath3(char *path1, char *path2, char *path3)
802 #if defined(PLATFORM_ANDROID)
803 // workaround for reading from assets directory -- skip "." subdirs in path
804 if (strEqual(path1, "."))
805 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
806 else if (strEqual(path2, "."))
807 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
808 else if (strEqual(path3, "."))
809 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
812 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
815 static char *getPngOrPcxIfNotExists(char *filename)
817 // switch from PNG to PCX file and vice versa, if file does not exist
818 // (backwards compatibility with PCX files used in previous versions)
820 if (!fileExists(filename) && strSuffix(filename, ".png"))
821 strcpy(&filename[strlen(filename) - 3], "pcx");
822 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
823 strcpy(&filename[strlen(filename) - 3], "png");
828 char *getImg2(char *path1, char *path2)
830 return getPngOrPcxIfNotExists(getPath2(path1, path2));
833 char *getImg3(char *path1, char *path2, char *path3)
835 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
838 char *getStringCopy(const char *s)
845 s_copy = checked_malloc(strlen(s) + 1);
851 char *getStringCopyN(const char *s, int n)
854 int s_len = MAX(0, n);
859 s_copy = checked_malloc(s_len + 1);
860 strncpy(s_copy, s, s_len);
861 s_copy[s_len] = '\0';
866 char *getStringCopyNStatic(const char *s, int n)
868 static char *s_copy = NULL;
870 checked_free(s_copy);
872 s_copy = getStringCopyN(s, n);
877 char *getStringToLower(const char *s)
879 char *s_copy = checked_malloc(strlen(s) + 1);
880 char *s_ptr = s_copy;
883 *s_ptr++ = tolower(*s++);
889 void setString(char **old_value, char *new_value)
891 checked_free(*old_value);
893 *old_value = getStringCopy(new_value);
896 boolean strEqual(char *s1, char *s2)
898 return (s1 == NULL && s2 == NULL ? TRUE :
899 s1 == NULL && s2 != NULL ? FALSE :
900 s1 != NULL && s2 == NULL ? FALSE :
901 strcmp(s1, s2) == 0);
904 boolean strEqualN(char *s1, char *s2, int n)
906 return (s1 == NULL && s2 == NULL ? TRUE :
907 s1 == NULL && s2 != NULL ? FALSE :
908 s1 != NULL && s2 == NULL ? FALSE :
909 strncmp(s1, s2, n) == 0);
912 boolean strPrefix(char *s, char *prefix)
914 return (s == NULL && prefix == NULL ? TRUE :
915 s == NULL && prefix != NULL ? FALSE :
916 s != NULL && prefix == NULL ? FALSE :
917 strncmp(s, prefix, strlen(prefix)) == 0);
920 boolean strSuffix(char *s, char *suffix)
922 return (s == NULL && suffix == NULL ? TRUE :
923 s == NULL && suffix != NULL ? FALSE :
924 s != NULL && suffix == NULL ? FALSE :
925 strlen(s) < strlen(suffix) ? FALSE :
926 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
929 boolean strPrefixLower(char *s, char *prefix)
931 char *s_lower = getStringToLower(s);
932 boolean match = strPrefix(s_lower, prefix);
939 boolean strSuffixLower(char *s, char *suffix)
941 char *s_lower = getStringToLower(s);
942 boolean match = strSuffix(s_lower, suffix);
950 /* ------------------------------------------------------------------------- */
951 /* command line option handling functions */
952 /* ------------------------------------------------------------------------- */
954 void GetOptions(int argc, char *argv[],
955 void (*print_usage_function)(void),
956 void (*print_version_function)(void))
958 char *ro_base_path = RO_BASE_PATH;
959 char *rw_base_path = RW_BASE_PATH;
960 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
961 char **options_left = &argvplus[1];
963 /* replace original "argv" with null-terminated array of string pointers */
965 argvplus[argc] = argv[argc];
967 /* if the program is configured to start from current directory (default),
968 determine program package directory from program binary (some versions
969 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
970 set the current working directory to the program package directory) */
972 if (strEqual(ro_base_path, "."))
973 ro_base_path = getProgramMainDataPath();
974 if (strEqual(rw_base_path, "."))
975 rw_base_path = getProgramMainDataPath();
977 /* initialize global program options */
978 options.server_host = NULL;
979 options.server_port = 0;
981 options.ro_base_directory = ro_base_path;
982 options.rw_base_directory = rw_base_path;
983 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
984 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
985 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
986 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
987 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
988 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
990 options.execute_command = NULL;
991 options.special_flags = NULL;
993 options.mytapes = FALSE;
994 options.serveronly = FALSE;
995 options.network = FALSE;
996 options.verbose = FALSE;
997 options.debug = FALSE;
1000 options.verbose = TRUE;
1002 #if !defined(PLATFORM_UNIX)
1003 if (*options_left == NULL) /* no options given -- enable verbose mode */
1004 options.verbose = TRUE;
1009 #if defined(PLATFORM_ANDROID)
1010 options.debug = TRUE;
1014 while (*options_left)
1016 char option_str[MAX_OPTION_LEN];
1017 char *option = options_left[0];
1018 char *next_option = options_left[1];
1019 char *option_arg = NULL;
1020 int option_len = strlen(option);
1022 if (option_len >= MAX_OPTION_LEN)
1023 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1025 strcpy(option_str, option); /* copy argument into buffer */
1026 option = option_str;
1028 if (strEqual(option, "--")) /* stop scanning arguments */
1031 if (strPrefix(option, "--")) /* treat '--' like '-' */
1034 option_arg = strchr(option, '=');
1035 if (option_arg == NULL) /* no '=' in option */
1036 option_arg = next_option;
1039 *option_arg++ = '\0'; /* cut argument from option */
1040 if (*option_arg == '\0') /* no argument after '=' */
1041 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
1044 option_len = strlen(option);
1046 if (strEqual(option, "-"))
1048 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1050 else if (strncmp(option, "-help", option_len) == 0)
1052 print_usage_function();
1056 else if (strncmp(option, "-basepath", option_len) == 0)
1058 if (option_arg == NULL)
1059 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1061 /* this should be extended to separate options for ro and rw data */
1062 options.ro_base_directory = ro_base_path = option_arg;
1063 options.rw_base_directory = rw_base_path = option_arg;
1064 if (option_arg == next_option)
1067 /* adjust paths for sub-directories in base directory accordingly */
1068 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1069 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1070 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1071 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1072 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1073 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
1075 else if (strncmp(option, "-levels", option_len) == 0)
1077 if (option_arg == NULL)
1078 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1080 options.level_directory = option_arg;
1081 if (option_arg == next_option)
1084 else if (strncmp(option, "-graphics", option_len) == 0)
1086 if (option_arg == NULL)
1087 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1089 options.graphics_directory = option_arg;
1090 if (option_arg == next_option)
1093 else if (strncmp(option, "-sounds", option_len) == 0)
1095 if (option_arg == NULL)
1096 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1098 options.sounds_directory = option_arg;
1099 if (option_arg == next_option)
1102 else if (strncmp(option, "-music", option_len) == 0)
1104 if (option_arg == NULL)
1105 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1107 options.music_directory = option_arg;
1108 if (option_arg == next_option)
1111 else if (strncmp(option, "-mytapes", option_len) == 0)
1113 options.mytapes = TRUE;
1115 else if (strncmp(option, "-network", option_len) == 0)
1117 options.network = TRUE;
1119 else if (strncmp(option, "-serveronly", option_len) == 0)
1121 options.serveronly = TRUE;
1123 else if (strncmp(option, "-debug", option_len) == 0)
1125 options.debug = TRUE;
1127 else if (strncmp(option, "-verbose", option_len) == 0)
1129 options.verbose = TRUE;
1131 else if (strncmp(option, "-version", option_len) == 0 ||
1132 strncmp(option, "-V", option_len) == 0)
1134 print_version_function();
1138 else if (strPrefix(option, "-D"))
1140 options.special_flags = getStringCopy(&option[2]);
1142 else if (strncmp(option, "-execute", option_len) == 0)
1144 if (option_arg == NULL)
1145 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1147 options.execute_command = option_arg;
1148 if (option_arg == next_option)
1151 /* when doing batch processing, always enable verbose mode (warnings) */
1152 options.verbose = TRUE;
1154 #if defined(PLATFORM_MACOSX)
1155 else if (strPrefix(option, "-psn"))
1157 /* ignore process serial number when launched via GUI on Mac OS X */
1160 else if (*option == '-')
1162 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1164 else if (options.server_host == NULL)
1166 options.server_host = *options_left;
1168 else if (options.server_port == 0)
1170 options.server_port = atoi(*options_left);
1171 if (options.server_port < 1024)
1172 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1175 Error(ERR_EXIT_HELP, "too many arguments");
1182 /* ------------------------------------------------------------------------- */
1183 /* error handling functions */
1184 /* ------------------------------------------------------------------------- */
1186 #define MAX_INTERNAL_ERROR_SIZE 1024
1188 /* used by SetError() and GetError() to store internal error messages */
1189 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1191 void SetError(char *format, ...)
1195 va_start(ap, format);
1196 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1202 return internal_error;
1205 void Error(int mode, char *format, ...)
1207 static boolean last_line_was_separator = FALSE;
1208 char *process_name = "";
1210 if (program.log_file[LOG_ERR_ID] == NULL)
1213 #if defined(PLATFORM_ANDROID)
1214 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1215 mode & ERR_INFO ? ANDROID_LOG_INFO :
1216 mode & ERR_WARN ? ANDROID_LOG_WARN :
1217 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1218 ANDROID_LOG_UNKNOWN);
1221 /* display debug messages only when running in debug mode */
1222 if (mode & ERR_DEBUG && !options.debug)
1225 /* display warnings only when running in verbose mode */
1226 if (mode & ERR_WARN && !options.verbose)
1229 if (mode == ERR_INFO_LINE)
1231 if (!last_line_was_separator)
1232 printf_log_line(format, 79);
1234 last_line_was_separator = TRUE;
1239 last_line_was_separator = FALSE;
1241 if (mode & ERR_SOUND_SERVER)
1242 process_name = " sound server";
1243 else if (mode & ERR_NETWORK_SERVER)
1244 process_name = " network server";
1245 else if (mode & ERR_NETWORK_CLIENT)
1246 process_name = " network client **";
1250 #if !defined(PLATFORM_ANDROID)
1251 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1254 if (mode & ERR_WARN)
1255 printf_log_nonewline("warning: ");
1257 if (mode & ERR_EXIT)
1258 printf_log_nonewline("fatal error: ");
1262 va_start(ap, format);
1263 vprintf_log(format, ap);
1266 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1268 va_start(ap, format);
1269 program.exit_message_function(format, ap);
1274 if (mode & ERR_HELP)
1275 printf_log("%s: Try option '--help' for more information.",
1276 program.command_basename);
1278 if (mode & ERR_EXIT)
1279 printf_log("%s%s: aborting", program.command_basename, process_name);
1281 if (mode & ERR_EXIT)
1283 if (mode & ERR_FROM_SERVER)
1284 exit(1); /* child process: normal exit */
1286 program.exit_function(1); /* main process: clean up stuff */
1291 /* ------------------------------------------------------------------------- */
1292 /* checked memory allocation and freeing functions */
1293 /* ------------------------------------------------------------------------- */
1295 void *checked_malloc(unsigned int size)
1302 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1307 void *checked_calloc(unsigned int size)
1311 ptr = calloc(1, size);
1314 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1319 void *checked_realloc(void *ptr, unsigned int size)
1321 ptr = realloc(ptr, size);
1324 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1329 void checked_free(void *ptr)
1331 if (ptr != NULL) /* this check should be done by free() anyway */
1335 void clear_mem(void *ptr, unsigned int size)
1337 #if defined(PLATFORM_WIN32)
1338 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1339 char *cptr = (char *)ptr;
1344 memset(ptr, 0, size);
1349 /* ------------------------------------------------------------------------- */
1350 /* various helper functions */
1351 /* ------------------------------------------------------------------------- */
1353 void swap_numbers(int *i1, int *i2)
1361 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1373 /* the "put" variants of the following file access functions check for the file
1374 pointer being != NULL and return the number of bytes they have or would have
1375 written; this allows for chunk writing functions to first determine the size
1376 of the (not yet written) chunk, write the correct chunk size and finally
1377 write the chunk itself */
1379 int getFile8BitInteger(File *file)
1381 return getByteFromFile(file);
1384 int putFile8BitInteger(FILE *file, int value)
1392 int getFile16BitInteger(File *file, int byte_order)
1394 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1395 return ((getByteFromFile(file) << 8) |
1396 (getByteFromFile(file) << 0));
1397 else /* BYTE_ORDER_LITTLE_ENDIAN */
1398 return ((getByteFromFile(file) << 0) |
1399 (getByteFromFile(file) << 8));
1402 int putFile16BitInteger(FILE *file, int value, int byte_order)
1406 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1408 fputc((value >> 8) & 0xff, file);
1409 fputc((value >> 0) & 0xff, file);
1411 else /* BYTE_ORDER_LITTLE_ENDIAN */
1413 fputc((value >> 0) & 0xff, file);
1414 fputc((value >> 8) & 0xff, file);
1421 int getFile32BitInteger(File *file, int byte_order)
1423 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1424 return ((getByteFromFile(file) << 24) |
1425 (getByteFromFile(file) << 16) |
1426 (getByteFromFile(file) << 8) |
1427 (getByteFromFile(file) << 0));
1428 else /* BYTE_ORDER_LITTLE_ENDIAN */
1429 return ((getByteFromFile(file) << 0) |
1430 (getByteFromFile(file) << 8) |
1431 (getByteFromFile(file) << 16) |
1432 (getByteFromFile(file) << 24));
1435 int putFile32BitInteger(FILE *file, int value, int byte_order)
1439 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1441 fputc((value >> 24) & 0xff, file);
1442 fputc((value >> 16) & 0xff, file);
1443 fputc((value >> 8) & 0xff, file);
1444 fputc((value >> 0) & 0xff, file);
1446 else /* BYTE_ORDER_LITTLE_ENDIAN */
1448 fputc((value >> 0) & 0xff, file);
1449 fputc((value >> 8) & 0xff, file);
1450 fputc((value >> 16) & 0xff, file);
1451 fputc((value >> 24) & 0xff, file);
1458 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1461 const int chunk_name_length = 4;
1463 /* read chunk name */
1464 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1467 if (chunk_size != NULL)
1469 /* read chunk size */
1470 *chunk_size = getFile32BitInteger(file, byte_order);
1473 return (checkEndOfFile(file) ? FALSE : TRUE);
1476 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1481 /* write chunk name */
1483 fputs(chunk_name, file);
1485 num_bytes += strlen(chunk_name);
1487 if (chunk_size >= 0)
1489 /* write chunk size */
1491 putFile32BitInteger(file, chunk_size, byte_order);
1499 int getFileVersion(File *file)
1501 int version_major = getByteFromFile(file);
1502 int version_minor = getByteFromFile(file);
1503 int version_patch = getByteFromFile(file);
1504 int version_build = getByteFromFile(file);
1506 return VERSION_IDENT(version_major, version_minor, version_patch,
1510 int putFileVersion(FILE *file, int version)
1514 int version_major = VERSION_MAJOR(version);
1515 int version_minor = VERSION_MINOR(version);
1516 int version_patch = VERSION_PATCH(version);
1517 int version_build = VERSION_BUILD(version);
1519 fputc(version_major, file);
1520 fputc(version_minor, file);
1521 fputc(version_patch, file);
1522 fputc(version_build, file);
1528 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1532 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1533 buffer[i] = getByteFromFile(file);
1536 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1540 for(i = 0; i < bytes; i++)
1541 fputc(buffer[i], file);
1544 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1546 while (bytes-- && !checkEndOfFile(file))
1547 getByteFromFile(file);
1550 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1557 /* ------------------------------------------------------------------------- */
1558 /* functions to translate key identifiers between different format */
1559 /* ------------------------------------------------------------------------- */
1561 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1562 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1563 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1564 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1566 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1575 /* normal cursor keys */
1576 { KSYM_Left, "XK_Left", "cursor left" },
1577 { KSYM_Right, "XK_Right", "cursor right" },
1578 { KSYM_Up, "XK_Up", "cursor up" },
1579 { KSYM_Down, "XK_Down", "cursor down" },
1581 /* keypad cursor keys */
1583 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1584 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1585 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1586 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1589 /* other keypad keys */
1590 #ifdef KSYM_KP_Enter
1591 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1592 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1593 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1594 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1595 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1596 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1600 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1601 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1602 { KSYM_Control_L, "XK_Control_L", "left control" },
1603 { KSYM_Control_R, "XK_Control_R", "right control" },
1604 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1605 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1606 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1607 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1608 #if !defined(TARGET_SDL2)
1609 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1610 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1612 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1613 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1615 /* some special keys */
1616 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1617 { KSYM_Delete, "XK_Delete", "delete" },
1618 { KSYM_Insert, "XK_Insert", "insert" },
1619 { KSYM_Tab, "XK_Tab", "tab" },
1620 { KSYM_Home, "XK_Home", "home" },
1621 { KSYM_End, "XK_End", "end" },
1622 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1623 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1625 #if defined(TARGET_SDL2)
1626 { KSYM_Select, "XK_Select", "select" },
1627 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1628 { KSYM_Back, "XK_Back", "back" }, /* back key */
1629 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
1630 #if defined(PLATFORM_ANDROID)
1631 { KSYM_Rewind, "XK_Rewind", "rewind" },
1632 { KSYM_FastForward, "XK_FastForward", "fast forward" },
1636 /* ASCII 0x20 to 0x40 keys (except numbers) */
1637 { KSYM_space, "XK_space", "space" },
1638 { KSYM_exclam, "XK_exclam", "!" },
1639 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1640 { KSYM_numbersign, "XK_numbersign", "#" },
1641 { KSYM_dollar, "XK_dollar", "$" },
1642 { KSYM_percent, "XK_percent", "%" },
1643 { KSYM_ampersand, "XK_ampersand", "&" },
1644 { KSYM_apostrophe, "XK_apostrophe", "'" },
1645 { KSYM_parenleft, "XK_parenleft", "(" },
1646 { KSYM_parenright, "XK_parenright", ")" },
1647 { KSYM_asterisk, "XK_asterisk", "*" },
1648 { KSYM_plus, "XK_plus", "+" },
1649 { KSYM_comma, "XK_comma", "," },
1650 { KSYM_minus, "XK_minus", "-" },
1651 { KSYM_period, "XK_period", "." },
1652 { KSYM_slash, "XK_slash", "/" },
1653 { KSYM_colon, "XK_colon", ":" },
1654 { KSYM_semicolon, "XK_semicolon", ";" },
1655 { KSYM_less, "XK_less", "<" },
1656 { KSYM_equal, "XK_equal", "=" },
1657 { KSYM_greater, "XK_greater", ">" },
1658 { KSYM_question, "XK_question", "?" },
1659 { KSYM_at, "XK_at", "@" },
1661 /* more ASCII keys */
1662 { KSYM_bracketleft, "XK_bracketleft", "[" },
1663 { KSYM_backslash, "XK_backslash", "\\" },
1664 { KSYM_bracketright,"XK_bracketright", "]" },
1665 { KSYM_asciicircum, "XK_asciicircum", "^" },
1666 { KSYM_underscore, "XK_underscore", "_" },
1667 { KSYM_grave, "XK_grave", "grave" },
1668 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1669 { KSYM_braceleft, "XK_braceleft", "brace left" },
1670 { KSYM_bar, "XK_bar", "bar" },
1671 { KSYM_braceright, "XK_braceright", "brace right" },
1672 { KSYM_asciitilde, "XK_asciitilde", "~" },
1674 /* special (non-ASCII) keys */
1675 { KSYM_degree, "XK_degree", "degree" },
1676 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1677 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1678 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1679 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1680 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1681 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1682 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1684 #if defined(TARGET_SDL2)
1685 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1686 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1687 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1688 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1689 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1690 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1691 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1692 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1693 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1695 /* other keys (for reverse mapping only) */
1696 { KSYM_space, "XK_space", " " },
1699 #if defined(TARGET_SDL2)
1700 /* keypad keys are not in numerical order in SDL2 */
1701 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1702 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1703 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1704 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1705 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1706 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1707 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1708 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1709 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1710 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1713 /* end-of-array identifier */
1719 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1721 static char name_buffer[30];
1724 if (key >= KSYM_A && key <= KSYM_Z)
1725 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1726 else if (key >= KSYM_a && key <= KSYM_z)
1727 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1728 else if (key >= KSYM_0 && key <= KSYM_9)
1729 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1730 #if !defined(TARGET_SDL2)
1731 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1732 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1734 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1735 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1736 else if (key == KSYM_UNDEFINED)
1737 strcpy(name_buffer, "(undefined)");
1744 if (key == translate_key[i].key)
1746 strcpy(name_buffer, translate_key[i].name);
1750 while (translate_key[++i].name);
1752 if (!translate_key[i].name)
1753 strcpy(name_buffer, "(unknown)");
1756 *name = name_buffer;
1758 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1760 static char name_buffer[30];
1763 if (key >= KSYM_A && key <= KSYM_Z)
1764 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1765 else if (key >= KSYM_a && key <= KSYM_z)
1766 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1767 else if (key >= KSYM_0 && key <= KSYM_9)
1768 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1769 #if !defined(TARGET_SDL2)
1770 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1771 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1773 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1774 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1775 else if (key == KSYM_UNDEFINED)
1776 strcpy(name_buffer, "[undefined]");
1783 if (key == translate_key[i].key)
1785 strcpy(name_buffer, translate_key[i].x11name);
1789 while (translate_key[++i].x11name);
1791 if (!translate_key[i].x11name)
1792 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1795 *x11name = name_buffer;
1797 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1799 Key key = KSYM_UNDEFINED;
1800 char *name_ptr = *name;
1802 if (strlen(*name) == 1)
1804 char c = name_ptr[0];
1806 if (c >= 'A' && c <= 'Z')
1807 key = KSYM_A + (Key)(c - 'A');
1808 else if (c >= 'a' && c <= 'z')
1809 key = KSYM_a + (Key)(c - 'a');
1810 else if (c >= '0' && c <= '9')
1811 key = KSYM_0 + (Key)(c - '0');
1814 if (key == KSYM_UNDEFINED)
1820 if (strEqual(translate_key[i].name, *name))
1822 key = translate_key[i].key;
1826 while (translate_key[++i].x11name);
1829 if (key == KSYM_UNDEFINED)
1830 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1834 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1836 Key key = KSYM_UNDEFINED;
1837 char *name_ptr = *x11name;
1839 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1841 char c = name_ptr[3];
1843 if (c >= 'A' && c <= 'Z')
1844 key = KSYM_A + (Key)(c - 'A');
1845 else if (c >= 'a' && c <= 'z')
1846 key = KSYM_a + (Key)(c - 'a');
1847 else if (c >= '0' && c <= '9')
1848 key = KSYM_0 + (Key)(c - '0');
1850 #if !defined(TARGET_SDL2)
1851 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1853 char c = name_ptr[6];
1855 if (c >= '0' && c <= '9')
1856 key = KSYM_KP_0 + (Key)(c - '0');
1859 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1861 char c1 = name_ptr[4];
1862 char c2 = name_ptr[5];
1865 if ((c1 >= '0' && c1 <= '9') &&
1866 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1867 d = atoi(&name_ptr[4]);
1869 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1870 key = KSYM_F1 + (Key)(d - 1);
1872 else if (strPrefix(name_ptr, "XK_"))
1878 if (strEqual(name_ptr, translate_key[i].x11name))
1880 key = translate_key[i].key;
1884 while (translate_key[++i].x11name);
1886 else if (strPrefix(name_ptr, "0x"))
1888 unsigned int value = 0;
1894 char c = *name_ptr++;
1897 if (c >= '0' && c <= '9')
1899 else if (c >= 'a' && c <= 'f')
1900 d = (int)(c - 'a' + 10);
1901 else if (c >= 'A' && c <= 'F')
1902 d = (int)(c - 'A' + 10);
1910 value = value * 16 + d;
1921 char *getKeyNameFromKey(Key key)
1925 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1929 char *getX11KeyNameFromKey(Key key)
1933 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1937 Key getKeyFromKeyName(char *name)
1941 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1945 Key getKeyFromX11KeyName(char *x11name)
1949 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1953 char getCharFromKey(Key key)
1959 } translate_key_char[] =
1961 /* special (non-ASCII) keys (ISO-8859-1) */
1962 { KSYM_degree, CHAR_BYTE_DEGREE },
1963 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1964 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1965 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1966 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1967 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1968 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1969 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1971 /* end-of-array identifier */
1975 char *keyname = getKeyNameFromKey(key);
1978 if (strlen(keyname) == 1)
1980 else if (strEqual(keyname, "space"))
1988 if (key == translate_key_char[i].key)
1990 c = translate_key_char[i].key_char;
1995 while (translate_key_char[++i].key_char);
2001 char getValidConfigValueChar(char c)
2003 if (c == '#' || /* used to mark comments */
2004 c == '\\') /* used to mark continued lines */
2011 /* ------------------------------------------------------------------------- */
2012 /* functions to translate string identifiers to integer or boolean value */
2013 /* ------------------------------------------------------------------------- */
2015 int get_integer_from_string(char *s)
2017 static char *number_text[][3] =
2019 { "0", "zero", "null", },
2020 { "1", "one", "first" },
2021 { "2", "two", "second" },
2022 { "3", "three", "third" },
2023 { "4", "four", "fourth" },
2024 { "5", "five", "fifth" },
2025 { "6", "six", "sixth" },
2026 { "7", "seven", "seventh" },
2027 { "8", "eight", "eighth" },
2028 { "9", "nine", "ninth" },
2029 { "10", "ten", "tenth" },
2030 { "11", "eleven", "eleventh" },
2031 { "12", "twelve", "twelfth" },
2033 { NULL, NULL, NULL },
2037 char *s_lower = getStringToLower(s);
2040 for (i = 0; number_text[i][0] != NULL; i++)
2041 for (j = 0; j < 3; j++)
2042 if (strEqual(s_lower, number_text[i][j]))
2047 if (strEqual(s_lower, "false") ||
2048 strEqual(s_lower, "no") ||
2049 strEqual(s_lower, "off"))
2051 else if (strEqual(s_lower, "true") ||
2052 strEqual(s_lower, "yes") ||
2053 strEqual(s_lower, "on"))
2064 boolean get_boolean_from_string(char *s)
2066 char *s_lower = getStringToLower(s);
2067 boolean result = FALSE;
2069 if (strEqual(s_lower, "true") ||
2070 strEqual(s_lower, "yes") ||
2071 strEqual(s_lower, "on") ||
2072 get_integer_from_string(s) == 1)
2080 int get_switch3_from_string(char *s)
2082 char *s_lower = getStringToLower(s);
2085 if (strEqual(s_lower, "true") ||
2086 strEqual(s_lower, "yes") ||
2087 strEqual(s_lower, "on") ||
2088 get_integer_from_string(s) == 1)
2090 else if (strEqual(s_lower, "auto"))
2099 /* ------------------------------------------------------------------------- */
2100 /* functions for generic lists */
2101 /* ------------------------------------------------------------------------- */
2103 ListNode *newListNode()
2105 return checked_calloc(sizeof(ListNode));
2108 void addNodeToList(ListNode **node_first, char *key, void *content)
2110 ListNode *node_new = newListNode();
2112 node_new->key = getStringCopy(key);
2113 node_new->content = content;
2114 node_new->next = *node_first;
2117 (*node_first)->prev = node_new;
2119 *node_first = node_new;
2122 void deleteNodeFromList(ListNode **node_first, char *key,
2123 void (*destructor_function)(void *))
2125 if (node_first == NULL || *node_first == NULL)
2128 if (strEqual((*node_first)->key, key))
2130 // after first recursion, (*node_first)->prev->next == *node_first,
2131 // so *node_first would be overwritten with (*node_first)->next
2132 // => use a copy of *node_first (and later of (*node_first)->next)
2133 ListNode *node = *node_first;
2134 ListNode *node_next = node->next;
2136 checked_free(node->key);
2138 if (destructor_function)
2139 destructor_function(node->content);
2142 node->prev->next = node->next;
2145 node->next->prev = node->prev;
2149 // after removing node, set list pointer to next valid list node
2150 // (this is important if the first node of the list was deleted)
2151 *node_first = node_next;
2155 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2159 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2161 if (node_first == NULL)
2164 if (strEqual(node_first->key, key))
2167 return getNodeFromKey(node_first->next, key);
2170 int getNumNodes(ListNode *node_first)
2172 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2175 void dumpList(ListNode *node_first)
2177 ListNode *node = node_first;
2181 printf("['%s' (%d)]\n", node->key,
2182 ((struct ListNodeInfo *)node->content)->num_references);
2186 printf("[%d nodes]\n", getNumNodes(node_first));
2190 /* ------------------------------------------------------------------------- */
2191 /* functions for file handling */
2192 /* ------------------------------------------------------------------------- */
2194 File *openFile(char *filename, char *mode)
2196 File *file = checked_calloc(sizeof(File));
2198 file->file = fopen(filename, mode);
2200 if (file->file != NULL)
2202 file->filename = getStringCopy(filename);
2207 #if defined(PLATFORM_ANDROID)
2208 file->asset_file = SDL_RWFromFile(filename, mode);
2210 if (file->asset_file != NULL)
2212 file->file_is_asset = TRUE;
2213 file->filename = getStringCopy(filename);
2224 int closeFile(File *file)
2231 #if defined(PLATFORM_ANDROID)
2232 if (file->asset_file)
2233 result = SDL_RWclose(file->asset_file);
2237 result = fclose(file->file);
2239 checked_free(file->filename);
2245 int checkEndOfFile(File *file)
2247 #if defined(PLATFORM_ANDROID)
2248 if (file->file_is_asset)
2249 return file->end_of_file;
2252 return feof(file->file);
2255 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2257 #if defined(PLATFORM_ANDROID)
2258 if (file->file_is_asset)
2260 if (file->end_of_file)
2263 size_t num_items_read =
2264 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2266 if (num_items_read < num_items)
2267 file->end_of_file = TRUE;
2269 return num_items_read;
2273 return fread(buffer, item_size, num_items, file->file);
2276 int seekFile(File *file, long offset, int whence)
2278 #if defined(PLATFORM_ANDROID)
2279 if (file->file_is_asset)
2281 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2282 whence == SEEK_CUR ? RW_SEEK_CUR :
2283 whence == SEEK_END ? RW_SEEK_END : 0);
2285 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2289 return fseek(file->file, offset, whence);
2292 int getByteFromFile(File *file)
2294 #if defined(PLATFORM_ANDROID)
2295 if (file->file_is_asset)
2297 if (file->end_of_file)
2301 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2303 if (num_bytes_read < 1)
2304 file->end_of_file = TRUE;
2306 return (file->end_of_file ? EOF : (int)c);
2310 return fgetc(file->file);
2313 char *getStringFromFile(File *file, char *line, int size)
2315 #if defined(PLATFORM_ANDROID)
2316 if (file->file_is_asset)
2318 if (file->end_of_file)
2321 char *line_ptr = line;
2322 int num_bytes_read = 0;
2324 while (num_bytes_read < size - 1 &&
2325 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2326 *line_ptr++ != '\n')
2331 if (strlen(line) == 0)
2333 file->end_of_file = TRUE;
2342 return fgets(line, size, file->file);
2346 /* ------------------------------------------------------------------------- */
2347 /* functions for directory handling */
2348 /* ------------------------------------------------------------------------- */
2350 Directory *openDirectory(char *dir_name)
2352 Directory *dir = checked_calloc(sizeof(Directory));
2354 dir->dir = opendir(dir_name);
2356 if (dir->dir != NULL)
2358 dir->filename = getStringCopy(dir_name);
2363 #if defined(PLATFORM_ANDROID)
2364 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2366 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2368 checked_free(asset_toc_filename);
2370 if (dir->asset_toc_file != NULL)
2372 dir->directory_is_asset = TRUE;
2373 dir->filename = getStringCopy(dir_name);
2384 int closeDirectory(Directory *dir)
2391 #if defined(PLATFORM_ANDROID)
2392 if (dir->asset_toc_file)
2393 result = SDL_RWclose(dir->asset_toc_file);
2397 result = closedir(dir->dir);
2400 freeDirectoryEntry(dir->dir_entry);
2402 checked_free(dir->filename);
2408 DirectoryEntry *readDirectory(Directory *dir)
2411 freeDirectoryEntry(dir->dir_entry);
2413 dir->dir_entry = NULL;
2415 #if defined(PLATFORM_ANDROID)
2416 if (dir->directory_is_asset)
2418 char line[MAX_LINE_LEN];
2419 char *line_ptr = line;
2420 int num_bytes_read = 0;
2422 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2423 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2432 if (strlen(line) == 0)
2435 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2437 dir->dir_entry->is_directory = FALSE;
2438 if (line[strlen(line) - 1] == '/')
2440 dir->dir_entry->is_directory = TRUE;
2442 line[strlen(line) - 1] = '\0';
2445 dir->dir_entry->basename = getStringCopy(line);
2446 dir->dir_entry->filename = getPath2(dir->filename, line);
2448 return dir->dir_entry;
2452 struct dirent *dir_entry = readdir(dir->dir);
2454 if (dir_entry == NULL)
2457 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2459 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2460 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2462 struct stat file_status;
2464 dir->dir_entry->is_directory =
2465 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2466 S_ISDIR(file_status.st_mode));
2468 return dir->dir_entry;
2471 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2473 if (dir_entry == NULL)
2476 checked_free(dir_entry->basename);
2477 checked_free(dir_entry->filename);
2478 checked_free(dir_entry);
2482 /* ------------------------------------------------------------------------- */
2483 /* functions for checking files and filenames */
2484 /* ------------------------------------------------------------------------- */
2486 boolean directoryExists(char *dir_name)
2488 if (dir_name == NULL)
2491 struct stat file_status;
2492 boolean success = (stat(dir_name, &file_status) == 0 &&
2493 S_ISDIR(file_status.st_mode));
2495 #if defined(PLATFORM_ANDROID)
2498 // this might be an asset directory; check by trying to open toc file
2499 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2500 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2502 checked_free(asset_toc_filename);
2504 success = (file != NULL);
2514 boolean fileExists(char *filename)
2516 if (filename == NULL)
2519 boolean success = (access(filename, F_OK) == 0);
2521 #if defined(PLATFORM_ANDROID)
2524 // this might be an asset file; check by trying to open it
2525 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2527 success = (file != NULL);
2537 boolean fileHasPrefix(char *basename, char *prefix)
2539 static char *basename_lower = NULL;
2540 int basename_length, prefix_length;
2542 checked_free(basename_lower);
2544 if (basename == NULL || prefix == NULL)
2547 basename_lower = getStringToLower(basename);
2548 basename_length = strlen(basename_lower);
2549 prefix_length = strlen(prefix);
2551 if (basename_length > prefix_length + 1 &&
2552 basename_lower[prefix_length] == '.' &&
2553 strncmp(basename_lower, prefix, prefix_length) == 0)
2559 boolean fileHasSuffix(char *basename, char *suffix)
2561 static char *basename_lower = NULL;
2562 int basename_length, suffix_length;
2564 checked_free(basename_lower);
2566 if (basename == NULL || suffix == NULL)
2569 basename_lower = getStringToLower(basename);
2570 basename_length = strlen(basename_lower);
2571 suffix_length = strlen(suffix);
2573 if (basename_length > suffix_length + 1 &&
2574 basename_lower[basename_length - suffix_length - 1] == '.' &&
2575 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2581 static boolean FileCouldBeArtwork(char *filename)
2583 char *basename = getBaseNamePtr(filename);
2585 return (!strEqual(basename, ".") &&
2586 !strEqual(basename, "..") &&
2587 !fileHasSuffix(basename, "txt") &&
2588 !fileHasSuffix(basename, "conf") &&
2589 !directoryExists(filename));
2592 boolean FileIsGraphic(char *filename)
2594 return FileCouldBeArtwork(filename);
2597 boolean FileIsSound(char *filename)
2599 return FileCouldBeArtwork(filename);
2602 boolean FileIsMusic(char *filename)
2604 return FileCouldBeArtwork(filename);
2607 boolean FileIsArtworkType(char *filename, int type)
2609 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2610 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2611 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2617 /* ------------------------------------------------------------------------- */
2618 /* functions for loading artwork configuration information */
2619 /* ------------------------------------------------------------------------- */
2621 char *get_mapped_token(char *token)
2623 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2624 static char *map_token_prefix[][2] =
2626 { "char_procent", "char_percent" },
2631 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2633 int len_token_prefix = strlen(map_token_prefix[i][0]);
2635 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2636 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2639 // change tokens containing ".gfx" by moving the "gfx" part to the very left
2640 char *gfx_substring = ".gfx";
2641 char *gfx_prefix = "gfx.";
2642 if (strstr(token, gfx_substring) != NULL)
2644 char *token_prefix = getStringCopy(token);
2645 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
2646 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
2649 // cut off token string at ".gfx" substring position
2650 *token_gfx_pos = '\0';
2652 // put together prefix "gfx." and token prefix and suffix without ".gfx"
2653 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
2657 return mapped_token;
2663 char *get_special_base_token(struct ArtworkListInfo *artwork_info, char *token)
2665 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2666 static struct ConfigTypeInfo prefix_list[] =
2668 { "global.anim_1" },
2669 { "global.anim_2" },
2670 { "global.anim_3" },
2671 { "global.anim_4" },
2672 { "global.anim_5" },
2673 { "global.anim_6" },
2674 { "global.anim_7" },
2675 { "global.anim_8" },
2676 { "global.anim_9" },
2677 { "global.anim_10" },
2678 { "global.anim_11" },
2679 { "global.anim_12" },
2680 { "global.anim_13" },
2681 { "global.anim_14" },
2682 { "global.anim_15" },
2683 { "global.anim_16" },
2684 { "global.anim_17" },
2685 { "global.anim_18" },
2686 { "global.anim_19" },
2687 { "global.anim_20" },
2688 { "global.anim_21" },
2689 { "global.anim_22" },
2690 { "global.anim_23" },
2691 { "global.anim_24" },
2692 { "global.anim_25" },
2693 { "global.anim_26" },
2694 { "global.anim_27" },
2695 { "global.anim_28" },
2696 { "global.anim_29" },
2697 { "global.anim_30" },
2698 { "global.anim_31" },
2699 { "global.anim_32" },
2703 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2704 boolean prefix_found = FALSE;
2708 /* search for prefix to check if base token has to be created */
2709 for (i = 0; prefix_list[i].token != NULL; i++)
2710 if (strPrefix(token, prefix_list[i].token))
2711 prefix_found = TRUE;
2716 /* search for suffix (parameter) to determine base token length */
2717 for (i = 0; suffix_list[i].token != NULL; i++)
2718 if (strSuffix(token, suffix_list[i].token))
2719 len_suffix = strlen(suffix_list[i].token);
2721 return getStringCopyN(token, strlen(token) - len_suffix);
2724 /* This function checks if a string <s> of the format "string1, string2, ..."
2725 exactly contains a string <s_contained>. */
2727 static boolean string_has_parameter(char *s, char *s_contained)
2731 if (s == NULL || s_contained == NULL)
2734 if (strlen(s_contained) > strlen(s))
2737 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2739 char next_char = s[strlen(s_contained)];
2741 /* check if next character is delimiter or whitespace */
2742 return (next_char == ',' || next_char == '\0' ||
2743 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2746 /* check if string contains another parameter string after a comma */
2747 substring = strchr(s, ',');
2748 if (substring == NULL) /* string does not contain a comma */
2751 /* advance string pointer to next character after the comma */
2754 /* skip potential whitespaces after the comma */
2755 while (*substring == ' ' || *substring == '\t')
2758 return string_has_parameter(substring, s_contained);
2761 int get_anim_parameter_value(char *s)
2763 char *pattern_1 = "click:anim_";
2764 char *pattern_2 = ".part_";
2765 char *matching_char = NULL;
2767 int result = ANIM_EVENT_NONE;
2769 matching_char = strstr(s_ptr, pattern_1);
2770 if (matching_char == NULL)
2771 return ANIM_EVENT_NONE;
2773 s_ptr = matching_char + strlen(pattern_1);
2775 // check for main animation number ("anim_X" or "anim_XX")
2776 if (*s_ptr >= '0' && *s_ptr <= '9')
2778 int gic_anim_nr = (*s_ptr++ - '0');
2780 if (*s_ptr >= '0' && *s_ptr <= '9')
2781 gic_anim_nr = 10 * gic_anim_nr + (*s_ptr++ - '0');
2783 if (gic_anim_nr < 1 || gic_anim_nr > MAX_GLOBAL_ANIMS)
2784 return ANIM_EVENT_NONE;
2786 result |= gic_anim_nr << ANIM_EVENT_ANIM_BIT;
2790 // invalid main animation number specified
2792 return ANIM_EVENT_NONE;
2795 // check for animation part number ("part_X" or "part_XX") (optional)
2796 if (strPrefix(s_ptr, pattern_2))
2798 s_ptr += strlen(pattern_2);
2800 if (*s_ptr >= '0' && *s_ptr <= '9')
2802 int gic_part_nr = (*s_ptr++ - '0');
2804 if (*s_ptr >= '0' && *s_ptr <= '9')
2805 gic_part_nr = 10 * gic_part_nr + (*s_ptr++ - '0');
2807 if (gic_part_nr < 1 || gic_part_nr > MAX_GLOBAL_ANIM_PARTS)
2808 return ANIM_EVENT_NONE;
2810 result |= gic_part_nr << ANIM_EVENT_PART_BIT;
2814 // invalid animation part number specified
2816 return ANIM_EVENT_NONE;
2820 /* discard result if next character is neither delimiter nor whitespace */
2821 if (!(*s_ptr == ',' || *s_ptr == '\0' ||
2822 *s_ptr == ' ' || *s_ptr == '\t'))
2823 return ANIM_EVENT_NONE;
2828 int get_parameter_value(char *value_raw, char *suffix, int type)
2830 char *value = getStringToLower(value_raw);
2831 int result = 0; /* probably a save default value */
2833 if (strEqual(suffix, ".direction"))
2835 result = (strEqual(value, "left") ? MV_LEFT :
2836 strEqual(value, "right") ? MV_RIGHT :
2837 strEqual(value, "up") ? MV_UP :
2838 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2840 else if (strEqual(suffix, ".position"))
2842 result = (strEqual(value, "left") ? POS_LEFT :
2843 strEqual(value, "right") ? POS_RIGHT :
2844 strEqual(value, "top") ? POS_TOP :
2845 strEqual(value, "upper") ? POS_UPPER :
2846 strEqual(value, "middle") ? POS_MIDDLE :
2847 strEqual(value, "lower") ? POS_LOWER :
2848 strEqual(value, "bottom") ? POS_BOTTOM :
2849 strEqual(value, "any") ? POS_ANY :
2850 strEqual(value, "last") ? POS_LAST : POS_UNDEFINED);
2852 else if (strEqual(suffix, ".align"))
2854 result = (strEqual(value, "left") ? ALIGN_LEFT :
2855 strEqual(value, "right") ? ALIGN_RIGHT :
2856 strEqual(value, "center") ? ALIGN_CENTER :
2857 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2859 else if (strEqual(suffix, ".valign"))
2861 result = (strEqual(value, "top") ? VALIGN_TOP :
2862 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2863 strEqual(value, "middle") ? VALIGN_MIDDLE :
2864 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2866 else if (strEqual(suffix, ".anim_mode"))
2868 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2869 string_has_parameter(value, "loop") ? ANIM_LOOP :
2870 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2871 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2872 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2873 string_has_parameter(value, "random") ? ANIM_RANDOM :
2874 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2875 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2876 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2877 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2878 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2879 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2880 string_has_parameter(value, "all") ? ANIM_ALL :
2883 if (string_has_parameter(value, "once"))
2884 result |= ANIM_ONCE;
2886 if (string_has_parameter(value, "reverse"))
2887 result |= ANIM_REVERSE;
2889 if (string_has_parameter(value, "opaque_player"))
2890 result |= ANIM_OPAQUE_PLAYER;
2892 if (string_has_parameter(value, "static_panel"))
2893 result |= ANIM_STATIC_PANEL;
2895 else if (strEqual(suffix, ".init_event") ||
2896 strEqual(suffix, ".anim_event"))
2898 result = ANIM_EVENT_DEFAULT;
2900 if (string_has_parameter(value, "any"))
2901 result |= ANIM_EVENT_ANY;
2903 if (string_has_parameter(value, "click"))
2904 result |= ANIM_EVENT_SELF;
2906 // add optional "click:anim_X" or "click:anim_X.part_X" parameter
2907 result |= get_anim_parameter_value(value);
2909 else if (strEqual(suffix, ".class"))
2911 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2912 get_hash_from_key(value));
2914 else if (strEqual(suffix, ".style"))
2916 result = STYLE_DEFAULT;
2918 if (string_has_parameter(value, "accurate_borders"))
2919 result |= STYLE_ACCURATE_BORDERS;
2921 if (string_has_parameter(value, "inner_corners"))
2922 result |= STYLE_INNER_CORNERS;
2924 else if (strEqual(suffix, ".fade_mode"))
2926 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2927 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2928 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2929 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2930 string_has_parameter(value, "curtain") ? FADE_MODE_CURTAIN :
2933 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2935 result = gfx.get_font_from_token_function(value);
2937 else /* generic parameter of type integer or boolean */
2939 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2940 type == TYPE_INTEGER ? get_integer_from_string(value) :
2941 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2942 ARG_UNDEFINED_VALUE);
2950 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2951 struct ListNodeInfo ***, int *);
2953 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2954 struct ConfigTypeInfo *suffix_list,
2955 char **ignore_tokens,
2956 int num_file_list_entries)
2958 SetupFileHash *ignore_tokens_hash;
2959 struct FileInfo *file_list;
2960 int num_file_list_entries_found = 0;
2961 int num_suffix_list_entries = 0;
2965 /* create hash from list of tokens to be ignored (for quick access) */
2966 ignore_tokens_hash = newSetupFileHash();
2967 for (i = 0; ignore_tokens[i] != NULL; i++)
2968 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
2970 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2972 for (i = 0; suffix_list[i].token != NULL; i++)
2973 num_suffix_list_entries++;
2975 /* always start with reliable default values */
2976 for (i = 0; i < num_file_list_entries; i++)
2978 file_list[i].token = NULL;
2980 file_list[i].default_filename = NULL;
2981 file_list[i].filename = NULL;
2983 if (num_suffix_list_entries > 0)
2985 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2987 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2988 file_list[i].parameter = checked_calloc(parameter_array_size);
2990 for (j = 0; j < num_suffix_list_entries; j++)
2992 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2993 setString(&file_list[i].parameter[j], suffix_list[j].value);
2996 file_list[i].redefined = FALSE;
2997 file_list[i].fallback_to_default = FALSE;
2998 file_list[i].default_is_cloned = FALSE;
3004 for (i = 0; config_list[i].token != NULL; i++)
3006 int len_config_token = strlen(config_list[i].token);
3007 boolean is_file_entry = TRUE;
3009 for (j = 0; suffix_list[j].token != NULL; j++)
3011 int len_suffix = strlen(suffix_list[j].token);
3013 if (len_suffix < len_config_token &&
3014 strEqual(&config_list[i].token[len_config_token - len_suffix],
3015 suffix_list[j].token))
3017 setString(&file_list[list_pos].default_parameter[j],
3018 config_list[i].value);
3020 is_file_entry = FALSE;
3026 /* the following tokens are no file definitions, but other config tokens */
3027 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
3028 is_file_entry = FALSE;
3035 if (list_pos >= num_file_list_entries)
3038 file_list[list_pos].token = config_list[i].token;
3039 file_list[list_pos].default_filename = config_list[i].value;
3042 if (strSuffix(config_list[i].token, ".clone_from"))
3043 file_list[list_pos].default_is_cloned = TRUE;
3046 num_file_list_entries_found = list_pos + 1;
3047 if (num_file_list_entries_found != num_file_list_entries)
3049 Error(ERR_INFO_LINE, "-");
3050 Error(ERR_INFO, "inconsistant config list information:");
3051 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
3052 num_file_list_entries);
3053 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
3054 num_file_list_entries_found);
3055 Error(ERR_EXIT, "please fix");
3058 freeSetupFileHash(ignore_tokens_hash);
3063 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3065 int len_token = strlen(token);
3066 int len_suffix = strlen(suffix);
3068 if (start_pos < 0) /* compare suffix from end of string */
3069 start_pos += len_token;
3071 if (start_pos < 0 || start_pos + len_suffix > len_token)
3074 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3077 if (token[start_pos + len_suffix] == '\0')
3080 if (token[start_pos + len_suffix] == '.')
3086 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3088 static void read_token_parameters(SetupFileHash *setup_file_hash,
3089 struct ConfigTypeInfo *suffix_list,
3090 struct FileInfo *file_list_entry)
3092 /* check for config token that is the base token without any suffixes */
3093 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3094 char *known_token_value = KNOWN_TOKEN_VALUE;
3097 if (filename != NULL)
3099 setString(&file_list_entry->filename, filename);
3101 /* when file definition found, set all parameters to default values */
3102 for (i = 0; suffix_list[i].token != NULL; i++)
3103 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3105 file_list_entry->redefined = TRUE;
3107 /* mark config file token as well known from default config */
3108 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3111 /* check for config tokens that can be build by base token and suffixes */
3112 for (i = 0; suffix_list[i].token != NULL; i++)
3114 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3115 char *value = getHashEntry(setup_file_hash, token);
3119 setString(&file_list_entry->parameter[i], value);
3121 /* mark config file token as well known from default config */
3122 setHashEntry(setup_file_hash, token, known_token_value);
3129 static void add_dynamic_file_list_entry(struct FileInfo **list,
3130 int *num_list_entries,
3131 SetupFileHash *extra_file_hash,
3132 struct ConfigTypeInfo *suffix_list,
3133 int num_suffix_list_entries,
3136 struct FileInfo *new_list_entry;
3137 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3139 (*num_list_entries)++;
3140 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3141 new_list_entry = &(*list)[*num_list_entries - 1];
3143 new_list_entry->token = getStringCopy(token);
3144 new_list_entry->default_filename = NULL;
3145 new_list_entry->filename = NULL;
3146 new_list_entry->parameter = checked_calloc(parameter_array_size);
3148 new_list_entry->redefined = FALSE;
3149 new_list_entry->fallback_to_default = FALSE;
3150 new_list_entry->default_is_cloned = FALSE;
3152 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3155 static void add_property_mapping(struct PropertyMapping **list,
3156 int *num_list_entries,
3157 int base_index, int ext1_index,
3158 int ext2_index, int ext3_index,
3161 struct PropertyMapping *new_list_entry;
3163 (*num_list_entries)++;
3164 *list = checked_realloc(*list,
3165 *num_list_entries * sizeof(struct PropertyMapping));
3166 new_list_entry = &(*list)[*num_list_entries - 1];
3168 new_list_entry->base_index = base_index;
3169 new_list_entry->ext1_index = ext1_index;
3170 new_list_entry->ext2_index = ext2_index;
3171 new_list_entry->ext3_index = ext3_index;
3173 new_list_entry->artwork_index = artwork_index;
3176 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3179 struct FileInfo *file_list = artwork_info->file_list;
3180 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3181 char **base_prefixes = artwork_info->base_prefixes;
3182 char **ext1_suffixes = artwork_info->ext1_suffixes;
3183 char **ext2_suffixes = artwork_info->ext2_suffixes;
3184 char **ext3_suffixes = artwork_info->ext3_suffixes;
3185 char **ignore_tokens = artwork_info->ignore_tokens;
3186 int num_file_list_entries = artwork_info->num_file_list_entries;
3187 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3188 int num_base_prefixes = artwork_info->num_base_prefixes;
3189 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3190 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3191 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3192 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3193 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3194 SetupFileHash *extra_file_hash, *empty_file_hash;
3195 char *known_token_value = KNOWN_TOKEN_VALUE;
3196 char *base_token_value = UNDEFINED_FILENAME;
3199 if (filename == NULL)
3202 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3205 /* separate valid (defined) from empty (undefined) config token values */
3206 valid_file_hash = newSetupFileHash();
3207 empty_file_hash = newSetupFileHash();
3208 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3210 char *value = HASH_ITERATION_VALUE(itr);
3212 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3213 HASH_ITERATION_TOKEN(itr), value);
3215 END_HASH_ITERATION(setup_file_hash, itr)
3217 /* at this point, we do not need the setup file hash anymore -- free it */
3218 freeSetupFileHash(setup_file_hash);
3220 /* prevent changing hash while iterating over it by using a temporary copy */
3221 valid_file_hash_tmp = newSetupFileHash();
3222 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3224 setHashEntry(valid_file_hash_tmp,
3225 HASH_ITERATION_TOKEN(itr),
3226 HASH_ITERATION_VALUE(itr));
3228 END_HASH_ITERATION(valid_file_hash, itr)
3230 /* (iterate over same temporary hash, as modifications are independent) */
3232 /* map deprecated to current tokens (using prefix match and replace) */
3233 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3235 char *token = HASH_ITERATION_TOKEN(itr);
3236 char *mapped_token = get_mapped_token(token);
3238 if (mapped_token != NULL)
3240 char *value = HASH_ITERATION_VALUE(itr);
3242 /* add mapped token */
3243 setHashEntry(valid_file_hash, mapped_token, value);
3245 /* ignore old token (by setting it to "known" keyword) */
3246 setHashEntry(valid_file_hash, token, known_token_value);
3251 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3253 /* add special base tokens (using prefix match and replace) */
3254 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3256 char *token = HASH_ITERATION_TOKEN(itr);
3257 char *base_token = get_special_base_token(artwork_info, token);
3259 if (base_token != NULL)
3261 /* add base token only if it does not already exist */
3262 if (getHashEntry(valid_file_hash, base_token) == NULL)
3263 setHashEntry(valid_file_hash, base_token, base_token_value);
3268 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3270 /* free temporary hash used for iteration */
3271 freeSetupFileHash(valid_file_hash_tmp);
3273 /* read parameters for all known config file tokens */
3274 for (i = 0; i < num_file_list_entries; i++)
3275 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3277 /* set all tokens that can be ignored here to "known" keyword */
3278 for (i = 0; i < num_ignore_tokens; i++)
3279 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3281 /* copy all unknown config file tokens to extra config hash */
3282 extra_file_hash = newSetupFileHash();
3283 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3285 char *value = HASH_ITERATION_VALUE(itr);
3287 if (!strEqual(value, known_token_value))
3288 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3290 END_HASH_ITERATION(valid_file_hash, itr)
3292 /* at this point, we do not need the valid file hash anymore -- free it */
3293 freeSetupFileHash(valid_file_hash);
3295 /* now try to determine valid, dynamically defined config tokens */
3297 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3299 struct FileInfo **dynamic_file_list =
3300 &artwork_info->dynamic_file_list;
3301 int *num_dynamic_file_list_entries =
3302 &artwork_info->num_dynamic_file_list_entries;
3303 struct PropertyMapping **property_mapping =
3304 &artwork_info->property_mapping;
3305 int *num_property_mapping_entries =
3306 &artwork_info->num_property_mapping_entries;
3307 int current_summarized_file_list_entry =
3308 artwork_info->num_file_list_entries +
3309 artwork_info->num_dynamic_file_list_entries;
3310 char *token = HASH_ITERATION_TOKEN(itr);
3311 int len_token = strlen(token);
3313 boolean base_prefix_found = FALSE;
3314 boolean parameter_suffix_found = FALSE;
3316 /* skip all parameter definitions (handled by read_token_parameters()) */
3317 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3319 int len_suffix = strlen(suffix_list[i].token);
3321 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3322 parameter_suffix_found = TRUE;
3325 if (parameter_suffix_found)
3328 /* ---------- step 0: search for matching base prefix ---------- */
3331 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3333 char *base_prefix = base_prefixes[i];
3334 int len_base_prefix = strlen(base_prefix);
3335 boolean ext1_suffix_found = FALSE;
3336 boolean ext2_suffix_found = FALSE;
3337 boolean ext3_suffix_found = FALSE;
3338 boolean exact_match = FALSE;
3339 int base_index = -1;
3340 int ext1_index = -1;
3341 int ext2_index = -1;
3342 int ext3_index = -1;
3344 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3346 if (!base_prefix_found)
3351 if (start_pos + len_base_prefix == len_token) /* exact match */
3355 add_dynamic_file_list_entry(dynamic_file_list,
3356 num_dynamic_file_list_entries,
3359 num_suffix_list_entries,
3361 add_property_mapping(property_mapping,
3362 num_property_mapping_entries,
3363 base_index, -1, -1, -1,
3364 current_summarized_file_list_entry);
3368 /* ---------- step 1: search for matching first suffix ---------- */
3370 start_pos += len_base_prefix;
3371 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3373 char *ext1_suffix = ext1_suffixes[j];
3374 int len_ext1_suffix = strlen(ext1_suffix);
3376 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3378 if (!ext1_suffix_found)
3383 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3387 add_dynamic_file_list_entry(dynamic_file_list,
3388 num_dynamic_file_list_entries,
3391 num_suffix_list_entries,
3393 add_property_mapping(property_mapping,
3394 num_property_mapping_entries,
3395 base_index, ext1_index, -1, -1,
3396 current_summarized_file_list_entry);
3400 start_pos += len_ext1_suffix;
3406 /* ---------- step 2: search for matching second suffix ---------- */
3408 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3410 char *ext2_suffix = ext2_suffixes[k];
3411 int len_ext2_suffix = strlen(ext2_suffix);
3413 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3415 if (!ext2_suffix_found)
3420 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3424 add_dynamic_file_list_entry(dynamic_file_list,
3425 num_dynamic_file_list_entries,
3428 num_suffix_list_entries,
3430 add_property_mapping(property_mapping,
3431 num_property_mapping_entries,
3432 base_index, ext1_index, ext2_index, -1,
3433 current_summarized_file_list_entry);
3437 start_pos += len_ext2_suffix;
3443 /* ---------- step 3: search for matching third suffix ---------- */
3445 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3447 char *ext3_suffix = ext3_suffixes[l];
3448 int len_ext3_suffix = strlen(ext3_suffix);
3450 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3452 if (!ext3_suffix_found)
3457 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3461 add_dynamic_file_list_entry(dynamic_file_list,
3462 num_dynamic_file_list_entries,
3465 num_suffix_list_entries,
3467 add_property_mapping(property_mapping,
3468 num_property_mapping_entries,
3469 base_index, ext1_index, ext2_index, ext3_index,
3470 current_summarized_file_list_entry);
3476 END_HASH_ITERATION(extra_file_hash, itr)
3478 if (artwork_info->num_dynamic_file_list_entries > 0)
3480 artwork_info->dynamic_artwork_list =
3481 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3482 artwork_info->sizeof_artwork_list_entry);
3485 if (options.verbose && IS_PARENT_PROCESS())
3487 SetupFileList *setup_file_list, *list;
3488 boolean dynamic_tokens_found = FALSE;
3489 boolean unknown_tokens_found = FALSE;
3490 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3492 /* list may be NULL for empty artwork config files */
3493 setup_file_list = loadSetupFileList(filename);
3495 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3497 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3498 dynamic_tokens_found = TRUE;
3500 unknown_tokens_found = TRUE;
3502 END_HASH_ITERATION(extra_file_hash, itr)
3504 if (options.debug && dynamic_tokens_found)
3506 Error(ERR_INFO_LINE, "-");
3507 Error(ERR_INFO, "dynamic token(s) found in config file:");
3508 Error(ERR_INFO, "- config file: '%s'", filename);
3510 for (list = setup_file_list; list != NULL; list = list->next)
3512 char *value = getHashEntry(extra_file_hash, list->token);
3514 if (value != NULL && strEqual(value, known_token_value))
3515 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3518 Error(ERR_INFO_LINE, "-");
3521 if (unknown_tokens_found)
3523 Error(ERR_INFO_LINE, "-");
3524 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3525 Error(ERR_INFO, "- config file: '%s'", filename);
3527 for (list = setup_file_list; list != NULL; list = list->next)
3529 char *value = getHashEntry(extra_file_hash, list->token);
3531 if (value != NULL && !strEqual(value, known_token_value))
3532 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3535 Error(ERR_INFO_LINE, "-");
3538 if (undefined_values_found)
3540 Error(ERR_INFO_LINE, "-");
3541 Error(ERR_INFO, "warning: undefined values found in config file:");
3542 Error(ERR_INFO, "- config file: '%s'", filename);
3544 for (list = setup_file_list; list != NULL; list = list->next)
3546 char *value = getHashEntry(empty_file_hash, list->token);
3549 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3552 Error(ERR_INFO_LINE, "-");
3555 freeSetupFileList(setup_file_list);
3558 freeSetupFileHash(extra_file_hash);
3559 freeSetupFileHash(empty_file_hash);
3562 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3564 struct FileInfo *file_list = artwork_info->file_list;
3565 int num_file_list_entries = artwork_info->num_file_list_entries;
3566 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3567 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3570 DrawInitText("Loading artwork config", 120, FC_GREEN);
3571 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3573 /* always start with reliable default values */
3574 for (i = 0; i < num_file_list_entries; i++)
3576 setString(&file_list[i].filename, file_list[i].default_filename);
3578 for (j = 0; j < num_suffix_list_entries; j++)
3579 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3581 file_list[i].redefined = FALSE;
3582 file_list[i].fallback_to_default = FALSE;
3585 /* free previous dynamic artwork file array */
3586 if (artwork_info->dynamic_file_list != NULL)
3588 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3590 free(artwork_info->dynamic_file_list[i].token);
3591 free(artwork_info->dynamic_file_list[i].filename);
3592 free(artwork_info->dynamic_file_list[i].parameter);
3595 free(artwork_info->dynamic_file_list);
3596 artwork_info->dynamic_file_list = NULL;
3598 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3599 &artwork_info->num_dynamic_file_list_entries);
3602 /* free previous property mapping */
3603 if (artwork_info->property_mapping != NULL)
3605 free(artwork_info->property_mapping);
3607 artwork_info->property_mapping = NULL;
3608 artwork_info->num_property_mapping_entries = 0;
3611 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3613 /* first look for special artwork configured in level series config */
3614 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3616 if (fileExists(filename_base))
3617 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3620 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3622 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3623 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3626 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3627 struct ListNodeInfo **listnode)
3631 char *filename = (*listnode)->source_filename;
3633 if (--(*listnode)->num_references <= 0)
3634 deleteNodeFromList(&artwork_info->content_list, filename,
3635 artwork_info->free_artwork);
3641 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3642 struct ListNodeInfo **listnode,
3643 struct FileInfo *file_list_entry)
3653 char *basename = file_list_entry->filename;
3654 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3656 if (filename == NULL)
3658 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3660 basename = file_list_entry->default_filename;
3662 /* fail for cloned default artwork that has no default filename defined */
3663 if (file_list_entry->default_is_cloned &&
3664 strEqual(basename, UNDEFINED_FILENAME))
3666 int error_mode = ERR_WARN;
3668 /* we can get away without sounds and music, but not without graphics */
3669 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3670 error_mode = ERR_EXIT;
3672 Error(error_mode, "token '%s' was cloned and has no default filename",
3673 file_list_entry->token);
3678 /* dynamic artwork has no default filename / skip empty default artwork */
3679 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3682 file_list_entry->fallback_to_default = TRUE;
3684 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3686 filename = getCustomArtworkFilename(basename, artwork_info->type);
3688 if (filename == NULL)
3690 int error_mode = ERR_WARN;
3692 /* we can get away without sounds and music, but not without graphics */
3693 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3694 error_mode = ERR_EXIT;
3696 Error(error_mode, "cannot find default artwork file '%s'", basename);
3702 /* check if the old and the new artwork file are the same */
3703 if (*listnode && strEqual((*listnode)->source_filename, filename))
3705 /* The old and new artwork are the same (have the same filename and path).
3706 This usually means that this artwork does not exist in this artwork set
3707 and a fallback to the existing artwork is done. */
3712 /* delete existing artwork file entry */
3713 deleteArtworkListEntry(artwork_info, listnode);
3715 /* check if the new artwork file already exists in the list of artwork */
3716 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3718 *listnode = (struct ListNodeInfo *)node->content;
3719 (*listnode)->num_references++;
3724 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3725 DrawInitText(basename, 150, FC_YELLOW);
3727 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3729 /* add new artwork file entry to the list of artwork files */
3730 (*listnode)->num_references = 1;
3731 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3736 int error_mode = ERR_WARN;
3738 /* we can get away without sounds and music, but not without graphics */
3739 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3740 error_mode = ERR_EXIT;
3742 Error(error_mode, "cannot load artwork file '%s'", basename);
3748 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3749 struct ListNodeInfo **listnode,
3750 struct FileInfo *file_list_entry)
3752 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3754 deleteArtworkListEntry(artwork_info, listnode);
3759 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3762 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3764 struct FileInfo *file_list = artwork_info->file_list;
3765 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3766 int num_file_list_entries = artwork_info->num_file_list_entries;
3767 int num_dynamic_file_list_entries =
3768 artwork_info->num_dynamic_file_list_entries;
3771 print_timestamp_init("ReloadCustomArtworkList");
3773 for (i = 0; i < num_file_list_entries; i++)
3774 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3777 for (i = 0; i < num_dynamic_file_list_entries; i++)
3778 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3779 &dynamic_file_list[i]);
3781 print_timestamp_done("ReloadCustomArtworkList");
3784 dumpList(artwork_info->content_list);
3788 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3789 struct ListNodeInfo ***list,
3790 int *num_list_entries)
3797 for (i = 0; i < *num_list_entries; i++)
3798 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3802 *num_list_entries = 0;
3805 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3807 if (artwork_info == NULL)
3810 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3811 &artwork_info->num_file_list_entries);
3813 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3814 &artwork_info->num_dynamic_file_list_entries);
3818 /* ------------------------------------------------------------------------- */
3819 /* functions only needed for non-Unix (non-command-line) systems */
3820 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3821 /* (now also added for Windows, to create files in user data directory) */
3822 /* ------------------------------------------------------------------------- */
3824 char *getLogFilename(char *basename)
3826 return getPath2(getUserGameDataDir(), basename);
3833 InitUserDataDirectory();
3835 for (i = 0; i < NUM_LOGS; i++)
3837 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3840 program.log_file[i] = program.log_file_default[i]; // reset to default
3842 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3843 program.log_filename[i], strerror(errno));
3846 /* output should be unbuffered so it is not truncated in a crash */
3847 setbuf(program.log_file[i], NULL);
3851 void CloseLogFiles()
3855 for (i = 0; i < NUM_LOGS; i++)
3856 if (program.log_file[i] != program.log_file_default[i])
3857 fclose(program.log_file[i]);
3860 void DumpLogFile(int nr)
3862 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3864 if (log_file == NULL)
3867 while (!feof(log_file))
3868 fputc(fgetc(log_file), stdout);
3873 void NotifyUserAboutErrorFile()
3875 #if defined(PLATFORM_WIN32)
3876 char *title_text = getStringCat2(program.program_title, " Error Message");
3877 char *error_text = getStringCat2("The program was aborted due to an error; "
3878 "for details, see the following error file:"
3880 program.log_filename[LOG_ERR_ID]);
3882 MessageBox(NULL, error_text, title_text, MB_OK);
3887 /* ------------------------------------------------------------------------- */
3888 /* the following is only for debugging purpose and normally not used */
3889 /* ------------------------------------------------------------------------- */
3893 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3894 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3896 #define DEBUG_NUM_TIMESTAMPS 10
3897 #define DEBUG_TIME_IN_MICROSECONDS 0
3899 #if DEBUG_TIME_IN_MICROSECONDS
3900 static double Counter_Microseconds()
3902 static struct timeval base_time = { 0, 0 };
3903 struct timeval current_time;
3906 gettimeofday(¤t_time, NULL);
3908 /* reset base time in case of wrap-around */
3909 if (current_time.tv_sec < base_time.tv_sec)
3910 base_time = current_time;
3913 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3914 ((double)(current_time.tv_usec - base_time.tv_usec));
3916 return counter; /* return microseconds since last init */
3920 char *debug_print_timestamp_get_padding(int padding_size)
3922 static char *padding = NULL;
3923 int max_padding_size = 100;
3925 if (padding == NULL)
3927 padding = checked_calloc(max_padding_size + 1);
3928 memset(padding, ' ', max_padding_size);
3931 return &padding[MAX(0, max_padding_size - padding_size)];
3934 void debug_print_timestamp(int counter_nr, char *message)
3936 int indent_size = 8;
3937 int padding_size = 40;
3938 float timestamp_interval;
3941 Error(ERR_EXIT, "debugging: invalid negative counter");
3942 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3943 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3945 #if DEBUG_TIME_IN_MICROSECONDS
3946 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3949 counter[counter_nr][0] = Counter_Microseconds();
3951 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3954 counter[counter_nr][0] = Counter();
3957 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3958 counter[counter_nr][1] = counter[counter_nr][0];
3961 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3962 debug_print_timestamp_get_padding(counter_nr * indent_size),
3964 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3965 timestamp_interval / 1000,
3969 void debug_print_parent_only(char *format, ...)
3971 if (!IS_PARENT_PROCESS())
3978 va_start(ap, format);
3979 vprintf(format, ap);
3988 void print_timestamp_ext(char *message, char *mode)
3990 #if DEBUG_PRINT_INIT_TIMESTAMPS
3991 static char *debug_message = NULL;
3992 static char *last_message = NULL;
3993 static int counter_nr = 0;
3994 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3996 checked_free(debug_message);
3997 debug_message = getStringCat3(mode, " ", message);
3999 if (strEqual(mode, "INIT"))
4001 debug_print_timestamp(counter_nr, NULL);
4003 if (counter_nr + 1 < max_depth)
4004 debug_print_timestamp(counter_nr, debug_message);
4008 debug_print_timestamp(counter_nr, NULL);
4010 else if (strEqual(mode, "DONE"))
4014 if (counter_nr + 1 < max_depth ||
4015 (counter_nr == 0 && max_depth == 1))
4017 last_message = message;
4019 if (counter_nr == 0 && max_depth == 1)
4021 checked_free(debug_message);
4022 debug_message = getStringCat3("TIME", " ", message);
4025 debug_print_timestamp(counter_nr, debug_message);
4028 else if (!strEqual(mode, "TIME") ||
4029 !strEqual(message, last_message))
4031 if (counter_nr < max_depth)
4032 debug_print_timestamp(counter_nr, debug_message);
4037 void print_timestamp_init(char *message)
4039 print_timestamp_ext(message, "INIT");
4042 void print_timestamp_time(char *message)
4044 print_timestamp_ext(message, "TIME");
4047 void print_timestamp_done(char *message)
4049 print_timestamp_ext(message, "DONE");