1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
14 #include <sys/types.h>
24 #if !defined(PLATFORM_WIN32)
26 #include <sys/param.h>
36 // ============================================================================
37 // some generic helper functions
38 // ============================================================================
40 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
44 #define DUPLICATE_LOG_OUT_TO_STDOUT TRUE
45 #define DUPLICATE_LOG_ERR_TO_STDERR TRUE
48 #if defined(PLATFORM_ANDROID)
49 static int android_log_prio = ANDROID_LOG_INFO;
50 static char *android_log_buffer = NULL;
52 static void append_to_android_log_buffer(char *format, va_list ap)
54 char text_new[MAX_OUTPUT_LINESIZE];
56 // print text to temporary string
57 vsnprintf(text_new, MAX_OUTPUT_LINESIZE, format, ap);
59 if (android_log_buffer == NULL)
61 android_log_buffer = getStringCopy(text_new);
65 char *android_log_buffer_old = android_log_buffer;
67 // append new text to existing text
68 android_log_buffer = getStringCat2(android_log_buffer, text_new);
70 checked_free(android_log_buffer_old);
74 static void vprintf_log_nonewline(char *format, va_list ap)
76 // add log output to buffer until text with newline is printed
77 append_to_android_log_buffer(format, ap);
80 static void vprintf_log(char *format, va_list ap)
82 // add log output to buffer
83 append_to_android_log_buffer(format, ap);
85 // __android_log_vprint(android_log_prio, program.program_title, format, ap);
86 __android_log_write(android_log_prio, program.program_title,
89 checked_free(android_log_buffer);
90 android_log_buffer = NULL;
95 static void vprintf_log_nonewline(char *format, va_list ap)
97 FILE *file = program.log_file[LOG_ERR_ID];
99 #if DUPLICATE_LOG_ERR_TO_STDERR
100 if (file != program.log_file_default[LOG_ERR_ID])
105 vfprintf(program.log_file_default[LOG_ERR_ID], format, ap2);
111 vfprintf(file, format, ap);
114 static void vprintf_log(char *format, va_list ap)
116 FILE *file = program.log_file[LOG_ERR_ID];
117 char *newline = STRING_NEWLINE;
119 #if DUPLICATE_LOG_ERR_TO_STDERR
120 if (file != program.log_file_default[LOG_ERR_ID])
125 vfprintf(program.log_file_default[LOG_ERR_ID], format, ap2);
126 fprintf(program.log_file_default[LOG_ERR_ID], "%s", newline);
132 vfprintf(file, format, ap);
133 fprintf(file, "%s", newline);
137 static void printf_log_nonewline(char *format, ...)
141 va_start(ap, format);
142 vprintf_log_nonewline(format, ap);
146 static void printf_log(char *format, ...)
150 va_start(ap, format);
151 vprintf_log(format, ap);
155 static void printf_log_line(char *line_chars, int line_length)
159 for (i = 0; i < line_length; i++)
160 printf_log_nonewline("%s", line_chars);
166 // ----------------------------------------------------------------------------
167 // platform independent wrappers for printf() et al.
168 // ----------------------------------------------------------------------------
170 void fprintf_line(FILE *file, char *line_chars, int line_length)
174 for (i = 0; i < line_length; i++)
175 fprintf(file, "%s", line_chars);
180 void fprintf_line_with_prefix(FILE *file, char *prefix, char *line_chars,
183 fprintf(file, "%s", prefix);
184 fprintf_line(file, line_chars, line_length);
187 void printf_line(char *line_chars, int line_length)
189 fprintf_line(stdout, line_chars, line_length);
192 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
194 fprintf_line_with_prefix(stdout, prefix, line_chars, line_length);
197 static void vPrint(char *format, va_list ap)
199 FILE *file = program.log_file[LOG_OUT_ID];
201 #if DUPLICATE_LOG_OUT_TO_STDOUT
202 if (file != program.log_file_default[LOG_OUT_ID])
207 vfprintf(program.log_file_default[LOG_OUT_ID], format, ap2);
213 vfprintf(file, format, ap);
216 void Print(char *format, ...)
220 va_start(ap, format);
225 void PrintNoLog(char *format, ...)
227 FILE *file = program.log_file_default[LOG_OUT_ID];
230 va_start(ap, format);
231 vfprintf(file, format, ap);
237 void PrintLine(char *line_chars, int line_length)
241 for (i = 0; i < line_length; i++)
247 void PrintLineWithPrefix(char *prefix, char *line_chars, int line_length)
250 PrintLine(line_chars, line_length);
254 // ----------------------------------------------------------------------------
256 // ----------------------------------------------------------------------------
258 /* int2str() returns a number converted to a string;
259 the used memory is static, but will be overwritten by later calls,
260 so if you want to save the result, copy it to a private string buffer;
261 there can be 10 local calls of int2str() without buffering the result --
262 the 11th call will then destroy the result from the first call and so on. */
264 char *int2str(int number, int size)
266 static char shift_array[10][40];
267 static int shift_counter = 0;
268 char *s = shift_array[shift_counter];
270 shift_counter = (shift_counter + 1) % 10;
277 sprintf(s, " %09d", number);
278 return &s[strlen(s) - size];
282 sprintf(s, "%d", number);
288 // something similar to "int2str()" above, but allocates its own memory
289 // and has a different interface; we cannot use "itoa()", because this
290 // seems to be already defined when cross-compiling to the win32 target
292 char *i_to_a(unsigned int i)
294 static char *a = NULL;
298 if (i > 2147483647) // yes, this is a kludge
301 a = checked_malloc(10 + 1);
309 // calculate base-2 logarithm of argument (rounded down to integer;
310 // this function returns the number of the highest bit set in argument)
312 int log_2(unsigned int x)
318 x -= (1 << e); // for rounding down (rounding up: remove this line)
325 boolean getTokenValueFromString(char *string, char **token, char **value)
327 return getTokenValueFromSetupLine(string, token, value);
331 // ----------------------------------------------------------------------------
333 // ----------------------------------------------------------------------------
335 // maximal allowed length of a command line option
336 #define MAX_OPTION_LEN 256
338 static unsigned int getCurrentMS(void)
340 return SDL_GetTicks();
343 static unsigned int mainCounter(int mode)
345 static unsigned int base_ms = 0;
346 unsigned int current_ms;
348 // get current system milliseconds
349 current_ms = getCurrentMS();
351 // reset base timestamp in case of counter reset or wrap-around
352 if (mode == INIT_COUNTER || current_ms < base_ms)
353 base_ms = current_ms;
355 // return milliseconds since last counter reset
356 return current_ms - base_ms;
359 void InitCounter() // set counter back to zero
361 mainCounter(INIT_COUNTER);
364 unsigned int Counter() // get milliseconds since last call of InitCounter()
366 return mainCounter(READ_COUNTER);
369 static void sleep_milliseconds(unsigned int milliseconds_delay)
371 SDL_Delay(milliseconds_delay);
374 void Delay(unsigned int delay) // Sleep specified number of milliseconds
376 sleep_milliseconds(delay);
379 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
380 unsigned int actual_counter)
382 if (actual_counter >= *counter_var &&
383 actual_counter < *counter_var + delay)
386 *counter_var = actual_counter;
391 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
393 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
396 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
398 return DelayReachedExt(counter_var, delay, Counter());
401 void ResetDelayCounterExt(unsigned int *counter_var,
402 unsigned int actual_counter)
404 DelayReachedExt(counter_var, 0, actual_counter);
407 void ResetFrameCounter(unsigned int *frame_counter_var)
409 FrameReached(frame_counter_var, 0);
412 void ResetDelayCounter(unsigned int *counter_var)
414 DelayReached(counter_var, 0);
417 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
419 unsigned int actual_counter;
424 actual_counter = Counter();
426 if (actual_counter >= *counter_var &&
427 actual_counter < *counter_var + delay)
428 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
433 if (*counter_var != 0 &&
435 actual_counter >= *counter_var + delay)
437 int lag = actual_counter - (*counter_var + delay);
438 int delay2 = (delay + 1) / 2;
441 skip_frames = (lag + delay2) / delay;
444 *counter_var = actual_counter;
449 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
450 int *loop_var, int last_loop_value)
452 int skip_frames = WaitUntilDelayReached(counter_var, delay);
456 printf("::: %d: %d ms", *loop_var, delay);
458 printf(" -> SKIP %d FRAME(S) [%d ms]", skip_frames, skip_frames * delay);
463 if (skip_frames == 0)
466 // when skipping frames, make sure to never skip the last frame, as
467 // this may be needed for animations to reach a defined end state;
468 // furthermore, we assume that this function is called at the end
469 // of a "for" loop, which continues by incrementing the loop variable
470 // by one before checking the loop condition again; therefore we have
471 // to check against the last loop value minus one here
475 if (*loop_var < last_loop_value) // never skip the last frame
477 *loop_var += skip_frames;
479 if (*loop_var > last_loop_value) // never skip the last frame
480 *loop_var = last_loop_value;
485 // ----------------------------------------------------------------------------
486 // random generator functions
487 // ----------------------------------------------------------------------------
489 unsigned int init_random_number(int nr, int seed)
491 if (seed == NEW_RANDOMIZE)
493 // default random seed
494 seed = (int)time(NULL); // seconds since the epoch
496 #if !defined(PLATFORM_WIN32)
497 // add some more randomness
498 struct timeval current_time;
500 gettimeofday(¤t_time, NULL);
502 seed += (int)current_time.tv_usec; // microseconds since the epoch
505 // add some more randomness
506 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
508 // add some more randomness
509 seed += GetSimpleRandom(1000000);
512 srandom_linux_libc(nr, (unsigned int) seed);
514 return (unsigned int) seed;
517 unsigned int get_random_number(int nr, int max)
519 return (max > 0 ? random_linux_libc(nr) % max : 0);
523 // ----------------------------------------------------------------------------
524 // system info functions
525 // ----------------------------------------------------------------------------
527 #if !defined(PLATFORM_ANDROID)
528 static char *get_corrected_real_name(char *real_name)
530 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
531 char *from_ptr = real_name;
532 char *to_ptr = real_name_new;
534 // copy the name string, but not more than MAX_USERNAME_LEN characters
535 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
537 // the name field read from "passwd" file may also contain additional
538 // user information, separated by commas, which will be removed here
539 if (*from_ptr == ',')
542 // the user's real name may contain 'german sharp s' characters,
543 // which have no equivalent in upper case letters (used by our fonts)
544 if (*from_ptr == CHAR_BYTE_SHARP_S)
551 *to_ptr++ = *from_ptr++;
556 return real_name_new;
560 char *getLoginName(void)
562 static char *login_name = NULL;
564 #if defined(PLATFORM_WIN32)
565 if (login_name == NULL)
567 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
568 login_name = checked_malloc(buffer_size);
570 if (GetUserName(login_name, &buffer_size) == 0)
571 strcpy(login_name, ANONYMOUS_NAME);
573 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
574 if (login_name == NULL)
578 if ((pwd = getpwuid(getuid())) == NULL)
579 login_name = ANONYMOUS_NAME;
581 login_name = getStringCopy(pwd->pw_name);
584 login_name = ANONYMOUS_NAME;
590 char *getRealName(void)
592 static char *real_name = NULL;
594 #if defined(PLATFORM_WIN32)
595 if (real_name == NULL)
597 static char buffer[MAX_USERNAME_LEN + 1];
598 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
600 if (GetUserName(buffer, &buffer_size) != 0)
601 real_name = get_corrected_real_name(buffer);
603 real_name = ANONYMOUS_NAME;
605 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
606 if (real_name == NULL)
610 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
611 real_name = get_corrected_real_name(pwd->pw_gecos);
613 real_name = ANONYMOUS_NAME;
616 real_name = ANONYMOUS_NAME;
622 time_t getFileTimestampEpochSeconds(char *filename)
624 struct stat file_status;
626 if (stat(filename, &file_status) != 0) // cannot stat file
629 return file_status.st_mtime;
633 // ----------------------------------------------------------------------------
634 // path manipulation functions
635 // ----------------------------------------------------------------------------
637 static char *getLastPathSeparatorPtr(char *filename)
639 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
641 if (last_separator == NULL) // also try DOS/Windows variant
642 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
644 return last_separator;
647 char *getBaseNamePtr(char *filename)
649 char *last_separator = getLastPathSeparatorPtr(filename);
651 if (last_separator != NULL)
652 return last_separator + 1; // separator found: strip base path
654 return filename; // no separator found: filename has no path
657 char *getBaseName(char *filename)
659 return getStringCopy(getBaseNamePtr(filename));
662 char *getBaseNameNoSuffix(char *filename)
664 char *basename = getStringCopy(getBaseNamePtr(filename));
666 // remove trailing suffix (separated by dot or hyphen)
667 if (basename[0] != '.' && basename[0] != '-')
669 if (strchr(basename, '.') != NULL)
670 *strchr(basename, '.') = '\0';
672 if (strchr(basename, '-') != NULL)
673 *strchr(basename, '-') = '\0';
679 char *getBasePath(char *filename)
681 char *basepath = getStringCopy(filename);
682 char *last_separator = getLastPathSeparatorPtr(basepath);
684 // if no separator was found, use current directory
685 if (last_separator == NULL)
689 return getStringCopy(".");
692 // separator found: strip basename
693 *last_separator = '\0';
699 // ----------------------------------------------------------------------------
700 // various string functions
701 // ----------------------------------------------------------------------------
703 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
705 if (s1 == NULL || s2 == NULL || sep == NULL)
708 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
711 sprintf(complete_string, "%s%s%s", s1, sep, s2);
713 return complete_string;
716 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
718 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
721 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
722 strlen(s2) + strlen(sep) +
725 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
727 return complete_string;
730 char *getStringCat2(char *s1, char *s2)
732 return getStringCat2WithSeparator(s1, s2, "");
735 char *getStringCat3(char *s1, char *s2, char *s3)
737 return getStringCat3WithSeparator(s1, s2, s3, "");
740 char *getPath2(char *path1, char *path2)
742 #if defined(PLATFORM_ANDROID)
743 // workaround for reading from assets directory -- skip "." subdirs in path
744 if (strEqual(path1, "."))
745 return getStringCopy(path2);
746 else if (strEqual(path2, "."))
747 return getStringCopy(path1);
750 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
753 char *getPath3(char *path1, char *path2, char *path3)
755 #if defined(PLATFORM_ANDROID)
756 // workaround for reading from assets directory -- skip "." subdirs in path
757 if (strEqual(path1, "."))
758 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
759 else if (strEqual(path2, "."))
760 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
761 else if (strEqual(path3, "."))
762 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
765 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
768 static char *getPngOrPcxIfNotExists(char *filename)
770 // switch from PNG to PCX file and vice versa, if file does not exist
771 // (backwards compatibility with PCX files used in previous versions)
773 if (!fileExists(filename) && strSuffix(filename, ".png"))
774 strcpy(&filename[strlen(filename) - 3], "pcx");
775 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
776 strcpy(&filename[strlen(filename) - 3], "png");
781 char *getImg2(char *path1, char *path2)
783 return getPngOrPcxIfNotExists(getPath2(path1, path2));
786 char *getImg3(char *path1, char *path2, char *path3)
788 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
791 char *getStringCopy(const char *s)
798 s_copy = checked_malloc(strlen(s) + 1);
804 char *getStringCopyN(const char *s, int n)
807 int s_len = MAX(0, n);
812 s_copy = checked_malloc(s_len + 1);
813 strncpy(s_copy, s, s_len);
814 s_copy[s_len] = '\0';
819 char *getStringCopyNStatic(const char *s, int n)
821 static char *s_copy = NULL;
823 checked_free(s_copy);
825 s_copy = getStringCopyN(s, n);
830 char *getStringToLower(const char *s)
832 char *s_copy = checked_malloc(strlen(s) + 1);
833 char *s_ptr = s_copy;
836 *s_ptr++ = tolower(*s++);
842 void setString(char **old_value, char *new_value)
844 checked_free(*old_value);
846 *old_value = getStringCopy(new_value);
849 boolean strEqual(char *s1, char *s2)
851 return (s1 == NULL && s2 == NULL ? TRUE :
852 s1 == NULL && s2 != NULL ? FALSE :
853 s1 != NULL && s2 == NULL ? FALSE :
854 strcmp(s1, s2) == 0);
857 boolean strEqualN(char *s1, char *s2, int n)
859 return (s1 == NULL && s2 == NULL ? TRUE :
860 s1 == NULL && s2 != NULL ? FALSE :
861 s1 != NULL && s2 == NULL ? FALSE :
862 strncmp(s1, s2, n) == 0);
865 boolean strPrefix(char *s, char *prefix)
867 return (s == NULL && prefix == NULL ? TRUE :
868 s == NULL && prefix != NULL ? FALSE :
869 s != NULL && prefix == NULL ? FALSE :
870 strncmp(s, prefix, strlen(prefix)) == 0);
873 boolean strSuffix(char *s, char *suffix)
875 return (s == NULL && suffix == NULL ? TRUE :
876 s == NULL && suffix != NULL ? FALSE :
877 s != NULL && suffix == NULL ? FALSE :
878 strlen(s) < strlen(suffix) ? FALSE :
879 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
882 boolean strPrefixLower(char *s, char *prefix)
884 char *s_lower = getStringToLower(s);
885 boolean match = strPrefix(s_lower, prefix);
892 boolean strSuffixLower(char *s, char *suffix)
894 char *s_lower = getStringToLower(s);
895 boolean match = strSuffix(s_lower, suffix);
903 // ----------------------------------------------------------------------------
904 // command line option handling functions
905 // ----------------------------------------------------------------------------
907 void GetOptions(int argc, char *argv[],
908 void (*print_usage_function)(void),
909 void (*print_version_function)(void))
911 char *ro_base_path = getProgramMainDataPath(argv[0], RO_BASE_PATH);
912 char *rw_base_path = getProgramMainDataPath(argv[0], RW_BASE_PATH);
913 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
914 char **options_left = &argvplus[1];
916 // replace original "argv" with null-terminated array of string pointers
918 argvplus[argc] = argv[argc];
920 // initialize global program options
921 options.server_host = NULL;
922 options.server_port = 0;
924 options.ro_base_directory = ro_base_path;
925 options.rw_base_directory = rw_base_path;
926 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
927 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
928 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
929 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
930 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
931 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
933 options.execute_command = NULL;
934 options.special_flags = NULL;
936 options.mytapes = FALSE;
937 options.serveronly = FALSE;
938 options.network = FALSE;
939 options.verbose = FALSE;
940 options.debug = FALSE;
943 options.verbose = TRUE;
945 #if !defined(PLATFORM_UNIX)
946 if (*options_left == NULL) // no options given -- enable verbose mode
947 options.verbose = TRUE;
952 #if defined(PLATFORM_ANDROID)
953 options.debug = TRUE;
957 while (*options_left)
959 char option_str[MAX_OPTION_LEN];
960 char *option = options_left[0];
961 char *next_option = options_left[1];
962 char *option_arg = NULL;
963 int option_len = strlen(option);
965 if (option_len >= MAX_OPTION_LEN)
966 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
968 strcpy(option_str, option); // copy argument into buffer
971 if (strEqual(option, "--")) // stop scanning arguments
974 if (strPrefix(option, "--")) // treat '--' like '-'
977 option_arg = strchr(option, '=');
978 if (option_arg == NULL) // no '=' in option
979 option_arg = next_option;
982 *option_arg++ = '\0'; // cut argument from option
983 if (*option_arg == '\0') // no argument after '='
984 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
987 option_len = strlen(option);
989 if (strEqual(option, "-"))
991 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
993 else if (strncmp(option, "-help", option_len) == 0)
995 print_usage_function();
999 else if (strncmp(option, "-basepath", option_len) == 0)
1001 if (option_arg == NULL)
1002 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1004 // this should be extended to separate options for ro and rw data
1005 options.ro_base_directory = ro_base_path = option_arg;
1006 options.rw_base_directory = rw_base_path = option_arg;
1007 if (option_arg == next_option)
1010 // adjust paths for sub-directories in base directory accordingly
1011 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1012 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1013 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1014 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1015 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1016 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
1018 else if (strncmp(option, "-levels", option_len) == 0)
1020 if (option_arg == NULL)
1021 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1023 options.level_directory = option_arg;
1024 if (option_arg == next_option)
1027 else if (strncmp(option, "-graphics", option_len) == 0)
1029 if (option_arg == NULL)
1030 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1032 options.graphics_directory = option_arg;
1033 if (option_arg == next_option)
1036 else if (strncmp(option, "-sounds", option_len) == 0)
1038 if (option_arg == NULL)
1039 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1041 options.sounds_directory = option_arg;
1042 if (option_arg == next_option)
1045 else if (strncmp(option, "-music", option_len) == 0)
1047 if (option_arg == NULL)
1048 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1050 options.music_directory = option_arg;
1051 if (option_arg == next_option)
1054 else if (strncmp(option, "-mytapes", option_len) == 0)
1056 options.mytapes = TRUE;
1058 else if (strncmp(option, "-network", option_len) == 0)
1060 options.network = TRUE;
1062 else if (strncmp(option, "-serveronly", option_len) == 0)
1064 options.serveronly = TRUE;
1066 else if (strncmp(option, "-debug", option_len) == 0)
1068 options.debug = TRUE;
1070 else if (strncmp(option, "-verbose", option_len) == 0)
1072 options.verbose = TRUE;
1074 else if (strncmp(option, "-version", option_len) == 0 ||
1075 strncmp(option, "-V", option_len) == 0)
1077 print_version_function();
1081 else if (strPrefix(option, "-D"))
1083 options.special_flags = getStringCopy(&option[2]);
1085 else if (strncmp(option, "-execute", option_len) == 0)
1087 if (option_arg == NULL)
1088 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1090 options.execute_command = option_arg;
1091 if (option_arg == next_option)
1094 // when doing batch processing, always enable verbose mode (warnings)
1095 options.verbose = TRUE;
1097 #if defined(PLATFORM_MACOSX)
1098 else if (strPrefix(option, "-psn"))
1100 // ignore process serial number when launched via GUI on Mac OS X
1103 else if (*option == '-')
1105 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1107 else if (options.server_host == NULL)
1109 options.server_host = *options_left;
1111 else if (options.server_port == 0)
1113 options.server_port = atoi(*options_left);
1114 if (options.server_port < 1024)
1115 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1118 Error(ERR_EXIT_HELP, "too many arguments");
1125 // ----------------------------------------------------------------------------
1126 // error handling functions
1127 // ----------------------------------------------------------------------------
1129 #define MAX_INTERNAL_ERROR_SIZE 1024
1131 // used by SetError() and GetError() to store internal error messages
1132 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1134 void SetError(char *format, ...)
1138 va_start(ap, format);
1139 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1143 char *GetError(void)
1145 return internal_error;
1148 void Error(int mode, char *format, ...)
1150 static boolean last_line_was_separator = FALSE;
1151 char *process_name = "";
1153 if (program.log_file[LOG_ERR_ID] == NULL)
1156 #if defined(PLATFORM_ANDROID)
1157 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1158 mode & ERR_INFO ? ANDROID_LOG_INFO :
1159 mode & ERR_WARN ? ANDROID_LOG_WARN :
1160 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1161 ANDROID_LOG_UNKNOWN);
1164 // display debug messages only when running in debug mode
1165 if (mode & ERR_DEBUG && !options.debug)
1168 // display warnings only when running in verbose mode
1169 if (mode & ERR_WARN && !options.verbose)
1172 if (mode == ERR_INFO_LINE)
1174 if (!last_line_was_separator)
1175 printf_log_line(format, 79);
1177 last_line_was_separator = TRUE;
1182 last_line_was_separator = FALSE;
1184 if (mode & ERR_SOUND_SERVER)
1185 process_name = " sound server";
1186 else if (mode & ERR_NETWORK_SERVER)
1187 process_name = " network server";
1188 else if (mode & ERR_NETWORK_CLIENT)
1189 process_name = " network client **";
1193 #if !defined(PLATFORM_ANDROID)
1194 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1197 if (mode & ERR_WARN)
1198 printf_log_nonewline("warning: ");
1200 if (mode & ERR_EXIT)
1201 printf_log_nonewline("fatal error: ");
1205 va_start(ap, format);
1206 vprintf_log(format, ap);
1209 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1211 va_start(ap, format);
1212 program.exit_message_function(format, ap);
1217 if (mode & ERR_HELP)
1218 printf_log("%s: Try option '--help' for more information.",
1219 program.command_basename);
1221 if (mode & ERR_EXIT)
1222 printf_log("%s%s: aborting", program.command_basename, process_name);
1224 if (mode & ERR_EXIT)
1226 if (mode & ERR_FROM_SERVER)
1227 exit(1); // child process: normal exit
1229 program.exit_function(1); // main process: clean up stuff
1234 // ----------------------------------------------------------------------------
1235 // checked memory allocation and freeing functions
1236 // ----------------------------------------------------------------------------
1238 void *checked_malloc(unsigned int size)
1245 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1250 void *checked_calloc(unsigned int size)
1254 ptr = calloc(1, size);
1257 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1262 void *checked_realloc(void *ptr, unsigned int size)
1264 ptr = realloc(ptr, size);
1267 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1272 void checked_free(void *ptr)
1274 if (ptr != NULL) // this check should be done by free() anyway
1278 void clear_mem(void *ptr, unsigned int size)
1280 #if defined(PLATFORM_WIN32)
1281 // for unknown reason, memset() sometimes crashes when compiled with MinGW
1282 char *cptr = (char *)ptr;
1287 memset(ptr, 0, size);
1292 // ----------------------------------------------------------------------------
1293 // various helper functions
1294 // ----------------------------------------------------------------------------
1296 void swap_numbers(int *i1, int *i2)
1304 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1316 /* the "put" variants of the following file access functions check for the file
1317 pointer being != NULL and return the number of bytes they have or would have
1318 written; this allows for chunk writing functions to first determine the size
1319 of the (not yet written) chunk, write the correct chunk size and finally
1320 write the chunk itself */
1322 int getFile8BitInteger(File *file)
1324 return getByteFromFile(file);
1327 int putFile8BitInteger(FILE *file, int value)
1335 int getFile16BitInteger(File *file, int byte_order)
1337 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1338 return ((getByteFromFile(file) << 8) |
1339 (getByteFromFile(file) << 0));
1340 else // BYTE_ORDER_LITTLE_ENDIAN
1341 return ((getByteFromFile(file) << 0) |
1342 (getByteFromFile(file) << 8));
1345 int putFile16BitInteger(FILE *file, int value, int byte_order)
1349 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1351 fputc((value >> 8) & 0xff, file);
1352 fputc((value >> 0) & 0xff, file);
1354 else // BYTE_ORDER_LITTLE_ENDIAN
1356 fputc((value >> 0) & 0xff, file);
1357 fputc((value >> 8) & 0xff, file);
1364 int getFile32BitInteger(File *file, int byte_order)
1366 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1367 return ((getByteFromFile(file) << 24) |
1368 (getByteFromFile(file) << 16) |
1369 (getByteFromFile(file) << 8) |
1370 (getByteFromFile(file) << 0));
1371 else // BYTE_ORDER_LITTLE_ENDIAN
1372 return ((getByteFromFile(file) << 0) |
1373 (getByteFromFile(file) << 8) |
1374 (getByteFromFile(file) << 16) |
1375 (getByteFromFile(file) << 24));
1378 int putFile32BitInteger(FILE *file, int value, int byte_order)
1382 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1384 fputc((value >> 24) & 0xff, file);
1385 fputc((value >> 16) & 0xff, file);
1386 fputc((value >> 8) & 0xff, file);
1387 fputc((value >> 0) & 0xff, file);
1389 else // BYTE_ORDER_LITTLE_ENDIAN
1391 fputc((value >> 0) & 0xff, file);
1392 fputc((value >> 8) & 0xff, file);
1393 fputc((value >> 16) & 0xff, file);
1394 fputc((value >> 24) & 0xff, file);
1401 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1404 const int chunk_name_length = 4;
1407 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1410 if (chunk_size != NULL)
1413 *chunk_size = getFile32BitInteger(file, byte_order);
1416 return (checkEndOfFile(file) ? FALSE : TRUE);
1419 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1426 fputs(chunk_name, file);
1428 num_bytes += strlen(chunk_name);
1430 if (chunk_size >= 0)
1434 putFile32BitInteger(file, chunk_size, byte_order);
1442 int getFileVersion(File *file)
1444 int version_super = getByteFromFile(file);
1445 int version_major = getByteFromFile(file);
1446 int version_minor = getByteFromFile(file);
1447 int version_patch = getByteFromFile(file);
1449 return VERSION_IDENT(version_super, version_major, version_minor,
1453 int putFileVersion(FILE *file, int version)
1457 int version_super = VERSION_SUPER(version);
1458 int version_major = VERSION_MAJOR(version);
1459 int version_minor = VERSION_MINOR(version);
1460 int version_patch = VERSION_PATCH(version);
1462 fputc(version_super, file);
1463 fputc(version_major, file);
1464 fputc(version_minor, file);
1465 fputc(version_patch, file);
1471 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1475 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1476 buffer[i] = getByteFromFile(file);
1479 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1483 for(i = 0; i < bytes; i++)
1484 fputc(buffer[i], file);
1487 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1489 while (bytes-- && !checkEndOfFile(file))
1490 getByteFromFile(file);
1493 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1500 // ----------------------------------------------------------------------------
1501 // functions to translate key identifiers between different format
1502 // ----------------------------------------------------------------------------
1504 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1505 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1506 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1507 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1509 static void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1518 // return and escape keys
1519 { KSYM_Return, "XK_Return", "return" },
1520 { KSYM_Escape, "XK_Escape", "escape" },
1522 // normal cursor keys
1523 { KSYM_Left, "XK_Left", "cursor left" },
1524 { KSYM_Right, "XK_Right", "cursor right" },
1525 { KSYM_Up, "XK_Up", "cursor up" },
1526 { KSYM_Down, "XK_Down", "cursor down" },
1528 // keypad cursor keys
1530 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1531 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1532 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1533 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1536 // other keypad keys
1537 #ifdef KSYM_KP_Enter
1538 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1539 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1540 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1541 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1542 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1543 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1547 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1548 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1549 { KSYM_Control_L, "XK_Control_L", "left control" },
1550 { KSYM_Control_R, "XK_Control_R", "right control" },
1551 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1552 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1553 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1554 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1555 #if !defined(TARGET_SDL2)
1556 { KSYM_Super_L, "XK_Super_L", "left super" }, // Win-L
1557 { KSYM_Super_R, "XK_Super_R", "right super" }, // Win-R
1559 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, // Alt-R
1560 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, // Ctrl-R
1562 // some special keys
1563 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1564 { KSYM_Delete, "XK_Delete", "delete" },
1565 { KSYM_Insert, "XK_Insert", "insert" },
1566 { KSYM_Tab, "XK_Tab", "tab" },
1567 { KSYM_Home, "XK_Home", "home" },
1568 { KSYM_End, "XK_End", "end" },
1569 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1570 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1572 #if defined(TARGET_SDL2)
1573 { KSYM_Select, "XK_Select", "select" },
1574 { KSYM_Menu, "XK_Menu", "menu" }, // menu key
1575 { KSYM_Back, "XK_Back", "back" }, // back key
1576 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
1577 #if defined(PLATFORM_ANDROID)
1578 { KSYM_Rewind, "XK_Rewind", "rewind" },
1579 { KSYM_FastForward, "XK_FastForward", "fast forward" },
1583 // ASCII 0x20 to 0x40 keys (except numbers)
1584 { KSYM_space, "XK_space", "space" },
1585 { KSYM_exclam, "XK_exclam", "!" },
1586 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1587 { KSYM_numbersign, "XK_numbersign", "#" },
1588 { KSYM_dollar, "XK_dollar", "$" },
1589 { KSYM_percent, "XK_percent", "%" },
1590 { KSYM_ampersand, "XK_ampersand", "&" },
1591 { KSYM_apostrophe, "XK_apostrophe", "'" },
1592 { KSYM_parenleft, "XK_parenleft", "(" },
1593 { KSYM_parenright, "XK_parenright", ")" },
1594 { KSYM_asterisk, "XK_asterisk", "*" },
1595 { KSYM_plus, "XK_plus", "+" },
1596 { KSYM_comma, "XK_comma", "," },
1597 { KSYM_minus, "XK_minus", "-" },
1598 { KSYM_period, "XK_period", "." },
1599 { KSYM_slash, "XK_slash", "/" },
1600 { KSYM_colon, "XK_colon", ":" },
1601 { KSYM_semicolon, "XK_semicolon", ";" },
1602 { KSYM_less, "XK_less", "<" },
1603 { KSYM_equal, "XK_equal", "=" },
1604 { KSYM_greater, "XK_greater", ">" },
1605 { KSYM_question, "XK_question", "?" },
1606 { KSYM_at, "XK_at", "@" },
1609 { KSYM_bracketleft, "XK_bracketleft", "[" },
1610 { KSYM_backslash, "XK_backslash", "\\" },
1611 { KSYM_bracketright,"XK_bracketright", "]" },
1612 { KSYM_asciicircum, "XK_asciicircum", "^" },
1613 { KSYM_underscore, "XK_underscore", "_" },
1614 { KSYM_grave, "XK_grave", "grave" },
1615 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1616 { KSYM_braceleft, "XK_braceleft", "brace left" },
1617 { KSYM_bar, "XK_bar", "bar" },
1618 { KSYM_braceright, "XK_braceright", "brace right" },
1619 { KSYM_asciitilde, "XK_asciitilde", "~" },
1621 // special (non-ASCII) keys
1622 { KSYM_degree, "XK_degree", "degree" },
1623 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1624 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1625 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1626 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1627 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1628 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1629 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1631 #if defined(TARGET_SDL2)
1632 // special (non-ASCII) keys (UTF-8, for reverse mapping only)
1633 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1634 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1635 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1636 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1637 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1638 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1639 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1640 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1642 // other keys (for reverse mapping only)
1643 { KSYM_space, "XK_space", " " },
1646 #if defined(TARGET_SDL2)
1647 // keypad keys are not in numerical order in SDL2
1648 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1649 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1650 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1651 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1652 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1653 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1654 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1655 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1656 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1657 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1660 // end-of-array identifier
1666 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1668 static char name_buffer[30];
1671 if (key >= KSYM_A && key <= KSYM_Z)
1672 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1673 else if (key >= KSYM_a && key <= KSYM_z)
1674 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1675 else if (key >= KSYM_0 && key <= KSYM_9)
1676 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1677 #if !defined(TARGET_SDL2)
1678 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1679 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1681 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1682 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1683 else if (key == KSYM_UNDEFINED)
1684 strcpy(name_buffer, "(undefined)");
1691 if (key == translate_key[i].key)
1693 strcpy(name_buffer, translate_key[i].name);
1697 while (translate_key[++i].name);
1699 if (!translate_key[i].name)
1700 strcpy(name_buffer, "(unknown)");
1703 *name = name_buffer;
1705 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1707 static char name_buffer[30];
1710 if (key >= KSYM_A && key <= KSYM_Z)
1711 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1712 else if (key >= KSYM_a && key <= KSYM_z)
1713 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1714 else if (key >= KSYM_0 && key <= KSYM_9)
1715 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1716 #if !defined(TARGET_SDL2)
1717 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1718 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1720 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1721 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1722 else if (key == KSYM_UNDEFINED)
1723 strcpy(name_buffer, "[undefined]");
1730 if (key == translate_key[i].key)
1732 strcpy(name_buffer, translate_key[i].x11name);
1736 while (translate_key[++i].x11name);
1738 if (!translate_key[i].x11name)
1739 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1742 *x11name = name_buffer;
1744 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1746 Key key = KSYM_UNDEFINED;
1747 char *name_ptr = *name;
1749 if (strlen(*name) == 1)
1751 char c = name_ptr[0];
1753 if (c >= 'A' && c <= 'Z')
1754 key = KSYM_A + (Key)(c - 'A');
1755 else if (c >= 'a' && c <= 'z')
1756 key = KSYM_a + (Key)(c - 'a');
1757 else if (c >= '0' && c <= '9')
1758 key = KSYM_0 + (Key)(c - '0');
1761 if (key == KSYM_UNDEFINED)
1767 if (strEqual(translate_key[i].name, *name))
1769 key = translate_key[i].key;
1773 while (translate_key[++i].x11name);
1776 if (key == KSYM_UNDEFINED)
1777 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1781 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1783 Key key = KSYM_UNDEFINED;
1784 char *name_ptr = *x11name;
1786 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1788 char c = name_ptr[3];
1790 if (c >= 'A' && c <= 'Z')
1791 key = KSYM_A + (Key)(c - 'A');
1792 else if (c >= 'a' && c <= 'z')
1793 key = KSYM_a + (Key)(c - 'a');
1794 else if (c >= '0' && c <= '9')
1795 key = KSYM_0 + (Key)(c - '0');
1797 #if !defined(TARGET_SDL2)
1798 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1800 char c = name_ptr[6];
1802 if (c >= '0' && c <= '9')
1803 key = KSYM_KP_0 + (Key)(c - '0');
1806 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1808 char c1 = name_ptr[4];
1809 char c2 = name_ptr[5];
1812 if ((c1 >= '0' && c1 <= '9') &&
1813 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1814 d = atoi(&name_ptr[4]);
1816 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1817 key = KSYM_F1 + (Key)(d - 1);
1819 else if (strPrefix(name_ptr, "XK_"))
1825 if (strEqual(name_ptr, translate_key[i].x11name))
1827 key = translate_key[i].key;
1831 while (translate_key[++i].x11name);
1833 else if (strPrefix(name_ptr, "0x"))
1835 unsigned int value = 0;
1841 char c = *name_ptr++;
1844 if (c >= '0' && c <= '9')
1846 else if (c >= 'a' && c <= 'f')
1847 d = (int)(c - 'a' + 10);
1848 else if (c >= 'A' && c <= 'F')
1849 d = (int)(c - 'A' + 10);
1857 value = value * 16 + d;
1868 char *getKeyNameFromKey(Key key)
1872 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1876 char *getX11KeyNameFromKey(Key key)
1880 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1884 Key getKeyFromKeyName(char *name)
1888 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1892 Key getKeyFromX11KeyName(char *x11name)
1896 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1900 char getCharFromKey(Key key)
1906 } translate_key_char[] =
1908 // special (non-ASCII) keys (ISO-8859-1)
1909 { KSYM_degree, CHAR_BYTE_DEGREE },
1910 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1911 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1912 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1913 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1914 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1915 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1916 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1918 // end-of-array identifier
1922 char *keyname = getKeyNameFromKey(key);
1925 if (strlen(keyname) == 1)
1927 else if (strEqual(keyname, "space"))
1935 if (key == translate_key_char[i].key)
1937 c = translate_key_char[i].key_char;
1942 while (translate_key_char[++i].key_char);
1948 char getValidConfigValueChar(char c)
1950 if (c == '#' || // used to mark comments
1951 c == '\\') // used to mark continued lines
1958 // ----------------------------------------------------------------------------
1959 // functions to translate string identifiers to integer or boolean value
1960 // ----------------------------------------------------------------------------
1962 int get_integer_from_string(char *s)
1964 static char *number_text[][3] =
1966 { "0", "zero", "null", },
1967 { "1", "one", "first" },
1968 { "2", "two", "second" },
1969 { "3", "three", "third" },
1970 { "4", "four", "fourth" },
1971 { "5", "five", "fifth" },
1972 { "6", "six", "sixth" },
1973 { "7", "seven", "seventh" },
1974 { "8", "eight", "eighth" },
1975 { "9", "nine", "ninth" },
1976 { "10", "ten", "tenth" },
1977 { "11", "eleven", "eleventh" },
1978 { "12", "twelve", "twelfth" },
1980 { NULL, NULL, NULL },
1984 char *s_lower = getStringToLower(s);
1987 for (i = 0; number_text[i][0] != NULL; i++)
1988 for (j = 0; j < 3; j++)
1989 if (strEqual(s_lower, number_text[i][j]))
1994 if (strEqual(s_lower, "false") ||
1995 strEqual(s_lower, "no") ||
1996 strEqual(s_lower, "off"))
1998 else if (strEqual(s_lower, "true") ||
1999 strEqual(s_lower, "yes") ||
2000 strEqual(s_lower, "on"))
2011 boolean get_boolean_from_string(char *s)
2013 char *s_lower = getStringToLower(s);
2014 boolean result = FALSE;
2016 if (strEqual(s_lower, "true") ||
2017 strEqual(s_lower, "yes") ||
2018 strEqual(s_lower, "on") ||
2019 get_integer_from_string(s) == 1)
2027 int get_switch3_from_string(char *s)
2029 char *s_lower = getStringToLower(s);
2032 if (strEqual(s_lower, "true") ||
2033 strEqual(s_lower, "yes") ||
2034 strEqual(s_lower, "on") ||
2035 get_integer_from_string(s) == 1)
2037 else if (strEqual(s_lower, "auto"))
2045 int get_player_nr_from_string(char *s)
2047 static char *player_text[] =
2057 char *s_lower = getStringToLower(s);
2061 for (i = 0; player_text[i] != NULL; i++)
2062 if (strEqual(s_lower, player_text[i]))
2071 // ----------------------------------------------------------------------------
2072 // functions for generic lists
2073 // ----------------------------------------------------------------------------
2075 ListNode *newListNode(void)
2077 return checked_calloc(sizeof(ListNode));
2080 void addNodeToList(ListNode **node_first, char *key, void *content)
2082 ListNode *node_new = newListNode();
2084 node_new->key = getStringCopy(key);
2085 node_new->content = content;
2086 node_new->next = *node_first;
2089 (*node_first)->prev = node_new;
2091 *node_first = node_new;
2094 void deleteNodeFromList(ListNode **node_first, char *key,
2095 void (*destructor_function)(void *))
2097 if (node_first == NULL || *node_first == NULL)
2100 if (strEqual((*node_first)->key, key))
2102 // after first recursion, (*node_first)->prev->next == *node_first,
2103 // so *node_first would be overwritten with (*node_first)->next
2104 // => use a copy of *node_first (and later of (*node_first)->next)
2105 ListNode *node = *node_first;
2106 ListNode *node_next = node->next;
2108 checked_free(node->key);
2110 if (destructor_function)
2111 destructor_function(node->content);
2114 node->prev->next = node->next;
2117 node->next->prev = node->prev;
2121 // after removing node, set list pointer to next valid list node
2122 // (this is important if the first node of the list was deleted)
2123 *node_first = node_next;
2127 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2131 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2133 if (node_first == NULL)
2136 if (strEqual(node_first->key, key))
2139 return getNodeFromKey(node_first->next, key);
2142 int getNumNodes(ListNode *node_first)
2144 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2148 static void dumpList(ListNode *node_first)
2150 ListNode *node = node_first;
2154 printf("['%s' (%d)]\n", node->key,
2155 ((struct ListNodeInfo *)node->content)->num_references);
2159 printf("[%d nodes]\n", getNumNodes(node_first));
2164 // ----------------------------------------------------------------------------
2165 // functions for file handling
2166 // ----------------------------------------------------------------------------
2168 #define MAX_BUFFER_SIZE 4096
2170 File *openFile(char *filename, char *mode)
2172 File *file = checked_calloc(sizeof(File));
2174 file->file = fopen(filename, mode);
2176 if (file->file != NULL)
2178 file->filename = getStringCopy(filename);
2183 #if defined(PLATFORM_ANDROID)
2184 file->asset_file = SDL_RWFromFile(filename, mode);
2186 if (file->asset_file != NULL)
2188 file->file_is_asset = TRUE;
2189 file->filename = getStringCopy(filename);
2200 int closeFile(File *file)
2207 #if defined(PLATFORM_ANDROID)
2208 if (file->asset_file)
2209 result = SDL_RWclose(file->asset_file);
2213 result = fclose(file->file);
2215 checked_free(file->filename);
2221 int checkEndOfFile(File *file)
2223 #if defined(PLATFORM_ANDROID)
2224 if (file->file_is_asset)
2225 return file->end_of_file;
2228 return feof(file->file);
2231 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2233 #if defined(PLATFORM_ANDROID)
2234 if (file->file_is_asset)
2236 if (file->end_of_file)
2239 size_t num_items_read =
2240 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2242 if (num_items_read < num_items)
2243 file->end_of_file = TRUE;
2245 return num_items_read;
2249 return fread(buffer, item_size, num_items, file->file);
2252 size_t writeFile(File *file, void *buffer, size_t item_size, size_t num_items)
2254 return fwrite(buffer, item_size, num_items, file->file);
2257 int seekFile(File *file, long offset, int whence)
2259 #if defined(PLATFORM_ANDROID)
2260 if (file->file_is_asset)
2262 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2263 whence == SEEK_CUR ? RW_SEEK_CUR :
2264 whence == SEEK_END ? RW_SEEK_END : 0);
2266 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2270 return fseek(file->file, offset, whence);
2273 int getByteFromFile(File *file)
2275 #if defined(PLATFORM_ANDROID)
2276 if (file->file_is_asset)
2278 if (file->end_of_file)
2282 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2284 if (num_bytes_read < 1)
2285 file->end_of_file = TRUE;
2287 return (file->end_of_file ? EOF : (int)c);
2291 return fgetc(file->file);
2294 char *getStringFromFile(File *file, char *line, int size)
2296 #if defined(PLATFORM_ANDROID)
2297 if (file->file_is_asset)
2299 if (file->end_of_file)
2302 char *line_ptr = line;
2303 int num_bytes_read = 0;
2305 while (num_bytes_read < size - 1 &&
2306 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2307 *line_ptr++ != '\n')
2312 if (strlen(line) == 0)
2314 file->end_of_file = TRUE;
2323 return fgets(line, size, file->file);
2326 int copyFile(char *filename_from, char *filename_to)
2328 File *file_from, *file_to;
2330 if ((file_from = openFile(filename_from, MODE_READ)) == NULL)
2335 if ((file_to = openFile(filename_to, MODE_WRITE)) == NULL)
2337 closeFile(file_from);
2342 while (!checkEndOfFile(file_from))
2344 byte buffer[MAX_BUFFER_SIZE];
2345 size_t bytes_read = readFile(file_from, buffer, 1, MAX_BUFFER_SIZE);
2347 writeFile(file_to, buffer, 1, bytes_read);
2350 closeFile(file_from);
2357 // ----------------------------------------------------------------------------
2358 // functions for directory handling
2359 // ----------------------------------------------------------------------------
2361 Directory *openDirectory(char *dir_name)
2363 Directory *dir = checked_calloc(sizeof(Directory));
2365 dir->dir = opendir(dir_name);
2367 if (dir->dir != NULL)
2369 dir->filename = getStringCopy(dir_name);
2374 #if defined(PLATFORM_ANDROID)
2375 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2377 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2379 checked_free(asset_toc_filename);
2381 if (dir->asset_toc_file != NULL)
2383 dir->directory_is_asset = TRUE;
2384 dir->filename = getStringCopy(dir_name);
2395 int closeDirectory(Directory *dir)
2402 #if defined(PLATFORM_ANDROID)
2403 if (dir->asset_toc_file)
2404 result = SDL_RWclose(dir->asset_toc_file);
2408 result = closedir(dir->dir);
2411 freeDirectoryEntry(dir->dir_entry);
2413 checked_free(dir->filename);
2419 DirectoryEntry *readDirectory(Directory *dir)
2422 freeDirectoryEntry(dir->dir_entry);
2424 dir->dir_entry = NULL;
2426 #if defined(PLATFORM_ANDROID)
2427 if (dir->directory_is_asset)
2429 char line[MAX_LINE_LEN];
2430 char *line_ptr = line;
2431 int num_bytes_read = 0;
2433 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2434 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2443 if (strlen(line) == 0)
2446 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2448 dir->dir_entry->is_directory = FALSE;
2449 if (line[strlen(line) - 1] == '/')
2451 dir->dir_entry->is_directory = TRUE;
2453 line[strlen(line) - 1] = '\0';
2456 dir->dir_entry->basename = getStringCopy(line);
2457 dir->dir_entry->filename = getPath2(dir->filename, line);
2459 return dir->dir_entry;
2463 struct dirent *dir_entry = readdir(dir->dir);
2465 if (dir_entry == NULL)
2468 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2470 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2471 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2473 struct stat file_status;
2475 dir->dir_entry->is_directory =
2476 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2477 S_ISDIR(file_status.st_mode));
2479 return dir->dir_entry;
2482 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2484 if (dir_entry == NULL)
2487 checked_free(dir_entry->basename);
2488 checked_free(dir_entry->filename);
2489 checked_free(dir_entry);
2493 // ----------------------------------------------------------------------------
2494 // functions for checking files and filenames
2495 // ----------------------------------------------------------------------------
2497 boolean directoryExists(char *dir_name)
2499 if (dir_name == NULL)
2502 struct stat file_status;
2503 boolean success = (stat(dir_name, &file_status) == 0 &&
2504 S_ISDIR(file_status.st_mode));
2506 #if defined(PLATFORM_ANDROID)
2509 // this might be an asset directory; check by trying to open toc file
2510 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2511 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2513 checked_free(asset_toc_filename);
2515 success = (file != NULL);
2525 boolean fileExists(char *filename)
2527 if (filename == NULL)
2530 boolean success = (access(filename, F_OK) == 0);
2532 #if defined(PLATFORM_ANDROID)
2535 // this might be an asset file; check by trying to open it
2536 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2538 success = (file != NULL);
2549 static boolean fileHasPrefix(char *basename, char *prefix)
2551 static char *basename_lower = NULL;
2552 int basename_length, prefix_length;
2554 checked_free(basename_lower);
2556 if (basename == NULL || prefix == NULL)
2559 basename_lower = getStringToLower(basename);
2560 basename_length = strlen(basename_lower);
2561 prefix_length = strlen(prefix);
2563 if (basename_length > prefix_length + 1 &&
2564 basename_lower[prefix_length] == '.' &&
2565 strncmp(basename_lower, prefix, prefix_length) == 0)
2572 static boolean fileHasSuffix(char *basename, char *suffix)
2574 static char *basename_lower = NULL;
2575 int basename_length, suffix_length;
2577 checked_free(basename_lower);
2579 if (basename == NULL || suffix == NULL)
2582 basename_lower = getStringToLower(basename);
2583 basename_length = strlen(basename_lower);
2584 suffix_length = strlen(suffix);
2586 if (basename_length > suffix_length + 1 &&
2587 basename_lower[basename_length - suffix_length - 1] == '.' &&
2588 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2594 static boolean FileCouldBeArtwork(char *filename)
2596 char *basename = getBaseNamePtr(filename);
2598 return (!strEqual(basename, ".") &&
2599 !strEqual(basename, "..") &&
2600 !fileHasSuffix(basename, "txt") &&
2601 !fileHasSuffix(basename, "conf") &&
2602 !directoryExists(filename));
2605 boolean FileIsGraphic(char *filename)
2607 return FileCouldBeArtwork(filename);
2610 boolean FileIsSound(char *filename)
2612 return FileCouldBeArtwork(filename);
2615 boolean FileIsMusic(char *filename)
2617 return FileCouldBeArtwork(filename);
2620 boolean FileIsArtworkType(char *filename, int type)
2622 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2623 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2624 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2630 // ----------------------------------------------------------------------------
2631 // functions for loading artwork configuration information
2632 // ----------------------------------------------------------------------------
2634 char *get_mapped_token(char *token)
2636 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
2637 static char *map_token_prefix[][2] =
2639 { "char_procent", "char_percent" },
2640 { "bd_magic_wall_filling", "bd_magic_wall.filling" },
2641 { "bd_magic_wall_emptying", "bd_magic_wall.emptying" },
2642 { "bd_butterfly_left", "bd_butterfly.left" },
2643 { "bd_butterfly_right", "bd_butterfly.right" },
2644 { "bd_butterfly_up", "bd_butterfly.up" },
2645 { "bd_butterfly_down", "bd_butterfly.down" },
2646 { "bd_firefly_left", "bd_firefly.left" },
2647 { "bd_firefly_right", "bd_firefly.right" },
2648 { "bd_firefly_up", "bd_firefly.up" },
2649 { "bd_firefly_down", "bd_firefly.down" },
2655 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2657 int len_token_prefix = strlen(map_token_prefix[i][0]);
2659 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2660 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2663 // change tokens containing ".gfx" by moving the "gfx" part to the very left
2664 char *gfx_substring = ".gfx";
2665 char *gfx_prefix = "gfx.";
2666 if (strstr(token, gfx_substring) != NULL)
2668 char *token_prefix = getStringCopy(token);
2669 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
2670 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
2673 // cut off token string at ".gfx" substring position
2674 *token_gfx_pos = '\0';
2676 // put together prefix "gfx." and token prefix and suffix without ".gfx"
2677 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
2681 return mapped_token;
2687 static char *get_special_base_token(struct ArtworkListInfo *artwork_info,
2690 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
2691 static struct ConfigTypeInfo prefix_list[] =
2693 { "global.anim_1" },
2694 { "global.anim_2" },
2695 { "global.anim_3" },
2696 { "global.anim_4" },
2697 { "global.anim_5" },
2698 { "global.anim_6" },
2699 { "global.anim_7" },
2700 { "global.anim_8" },
2701 { "global.anim_9" },
2702 { "global.anim_10" },
2703 { "global.anim_11" },
2704 { "global.anim_12" },
2705 { "global.anim_13" },
2706 { "global.anim_14" },
2707 { "global.anim_15" },
2708 { "global.anim_16" },
2709 { "global.anim_17" },
2710 { "global.anim_18" },
2711 { "global.anim_19" },
2712 { "global.anim_20" },
2713 { "global.anim_21" },
2714 { "global.anim_22" },
2715 { "global.anim_23" },
2716 { "global.anim_24" },
2717 { "global.anim_25" },
2718 { "global.anim_26" },
2719 { "global.anim_27" },
2720 { "global.anim_28" },
2721 { "global.anim_29" },
2722 { "global.anim_30" },
2723 { "global.anim_31" },
2724 { "global.anim_32" },
2728 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2729 boolean prefix_found = FALSE;
2733 // search for prefix to check if base token has to be created
2734 for (i = 0; prefix_list[i].token != NULL; i++)
2735 if (strPrefix(token, prefix_list[i].token))
2736 prefix_found = TRUE;
2741 // search for suffix (parameter) to determine base token length
2742 for (i = 0; suffix_list[i].token != NULL; i++)
2743 if (strSuffix(token, suffix_list[i].token))
2744 len_suffix = strlen(suffix_list[i].token);
2746 return getStringCopyN(token, strlen(token) - len_suffix);
2749 // This function checks if a string <s> of the format "string1, string2, ..."
2750 // exactly contains a string <s_contained>.
2752 static boolean string_has_parameter(char *s, char *s_contained)
2756 if (s == NULL || s_contained == NULL)
2759 if (strlen(s_contained) > strlen(s))
2762 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2764 char next_char = s[strlen(s_contained)];
2766 // check if next character is delimiter or whitespace
2767 return (next_char == ',' || next_char == '\0' ||
2768 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2771 // check if string contains another parameter string after a comma
2772 substring = strchr(s, ',');
2773 if (substring == NULL) // string does not contain a comma
2776 // advance string pointer to next character after the comma
2779 // skip potential whitespaces after the comma
2780 while (*substring == ' ' || *substring == '\t')
2783 return string_has_parameter(substring, s_contained);
2786 static int get_anim_parameter_value(char *s)
2788 char *pattern_1 = "click:anim_";
2789 char *pattern_2 = ".part_";
2790 char *matching_char = NULL;
2792 int result = ANIM_EVENT_NONE;
2794 matching_char = strstr(s_ptr, pattern_1);
2795 if (matching_char == NULL)
2796 return ANIM_EVENT_NONE;
2798 s_ptr = matching_char + strlen(pattern_1);
2800 // check for main animation number ("anim_X" or "anim_XX")
2801 if (*s_ptr >= '0' && *s_ptr <= '9')
2803 int gic_anim_nr = (*s_ptr++ - '0');
2805 if (*s_ptr >= '0' && *s_ptr <= '9')
2806 gic_anim_nr = 10 * gic_anim_nr + (*s_ptr++ - '0');
2808 if (gic_anim_nr < 1 || gic_anim_nr > MAX_GLOBAL_ANIMS)
2809 return ANIM_EVENT_NONE;
2811 result |= gic_anim_nr << ANIM_EVENT_ANIM_BIT;
2815 // invalid main animation number specified
2817 return ANIM_EVENT_NONE;
2820 // check for animation part number ("part_X" or "part_XX") (optional)
2821 if (strPrefix(s_ptr, pattern_2))
2823 s_ptr += strlen(pattern_2);
2825 if (*s_ptr >= '0' && *s_ptr <= '9')
2827 int gic_part_nr = (*s_ptr++ - '0');
2829 if (*s_ptr >= '0' && *s_ptr <= '9')
2830 gic_part_nr = 10 * gic_part_nr + (*s_ptr++ - '0');
2832 if (gic_part_nr < 1 || gic_part_nr > MAX_GLOBAL_ANIM_PARTS)
2833 return ANIM_EVENT_NONE;
2835 result |= gic_part_nr << ANIM_EVENT_PART_BIT;
2839 // invalid animation part number specified
2841 return ANIM_EVENT_NONE;
2845 // discard result if next character is neither delimiter nor whitespace
2846 if (!(*s_ptr == ',' || *s_ptr == '\0' ||
2847 *s_ptr == ' ' || *s_ptr == '\t'))
2848 return ANIM_EVENT_NONE;
2853 static int get_anim_action_parameter_value(char *token)
2855 int result = getImageIDFromToken(token);
2859 char *gfx_token = getStringCat2("gfx.", token);
2861 result = getImageIDFromToken(gfx_token);
2863 checked_free(gfx_token);
2868 Key key = getKeyFromX11KeyName(token);
2870 if (key != KSYM_UNDEFINED)
2875 result = ANIM_EVENT_ACTION_NONE;
2880 int get_parameter_value(char *value_raw, char *suffix, int type)
2882 char *value = getStringToLower(value_raw);
2883 int result = 0; // probably a save default value
2885 if (strEqual(suffix, ".direction"))
2887 result = (strEqual(value, "left") ? MV_LEFT :
2888 strEqual(value, "right") ? MV_RIGHT :
2889 strEqual(value, "up") ? MV_UP :
2890 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2892 else if (strEqual(suffix, ".position"))
2894 result = (strEqual(value, "left") ? POS_LEFT :
2895 strEqual(value, "right") ? POS_RIGHT :
2896 strEqual(value, "top") ? POS_TOP :
2897 strEqual(value, "upper") ? POS_UPPER :
2898 strEqual(value, "middle") ? POS_MIDDLE :
2899 strEqual(value, "lower") ? POS_LOWER :
2900 strEqual(value, "bottom") ? POS_BOTTOM :
2901 strEqual(value, "any") ? POS_ANY :
2902 strEqual(value, "last") ? POS_LAST : POS_UNDEFINED);
2904 else if (strEqual(suffix, ".align"))
2906 result = (strEqual(value, "left") ? ALIGN_LEFT :
2907 strEqual(value, "right") ? ALIGN_RIGHT :
2908 strEqual(value, "center") ? ALIGN_CENTER :
2909 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2911 else if (strEqual(suffix, ".valign"))
2913 result = (strEqual(value, "top") ? VALIGN_TOP :
2914 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2915 strEqual(value, "middle") ? VALIGN_MIDDLE :
2916 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2918 else if (strEqual(suffix, ".anim_mode"))
2920 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2921 string_has_parameter(value, "loop") ? ANIM_LOOP :
2922 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2923 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2924 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2925 string_has_parameter(value, "random") ? ANIM_RANDOM :
2926 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2927 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2928 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2929 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2930 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2931 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2932 string_has_parameter(value, "all") ? ANIM_ALL :
2935 if (string_has_parameter(value, "once"))
2936 result |= ANIM_ONCE;
2938 if (string_has_parameter(value, "reverse"))
2939 result |= ANIM_REVERSE;
2941 if (string_has_parameter(value, "opaque_player"))
2942 result |= ANIM_OPAQUE_PLAYER;
2944 if (string_has_parameter(value, "static_panel"))
2945 result |= ANIM_STATIC_PANEL;
2947 else if (strEqual(suffix, ".init_event") ||
2948 strEqual(suffix, ".anim_event"))
2950 result = ANIM_EVENT_DEFAULT;
2952 if (string_has_parameter(value, "any"))
2953 result |= ANIM_EVENT_ANY;
2955 if (string_has_parameter(value, "click"))
2956 result |= ANIM_EVENT_SELF;
2958 // add optional "click:anim_X" or "click:anim_X.part_X" parameter
2959 result |= get_anim_parameter_value(value);
2961 else if (strEqual(suffix, ".init_event_action") ||
2962 strEqual(suffix, ".anim_event_action"))
2964 result = get_anim_action_parameter_value(value_raw);
2966 else if (strEqual(suffix, ".class"))
2968 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2969 get_hash_from_key(value));
2971 else if (strEqual(suffix, ".style"))
2973 result = STYLE_DEFAULT;
2975 if (string_has_parameter(value, "accurate_borders"))
2976 result |= STYLE_ACCURATE_BORDERS;
2978 if (string_has_parameter(value, "inner_corners"))
2979 result |= STYLE_INNER_CORNERS;
2981 if (string_has_parameter(value, "reverse"))
2982 result |= STYLE_REVERSE;
2984 if (string_has_parameter(value, "passthrough_clicks"))
2985 result |= STYLE_PASSTHROUGH;
2987 if (string_has_parameter(value, "multiple_actions"))
2988 result |= STYLE_MULTIPLE_ACTIONS;
2990 else if (strEqual(suffix, ".fade_mode"))
2992 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2993 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2994 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2995 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2996 string_has_parameter(value, "curtain") ? FADE_MODE_CURTAIN :
2999 else if (strPrefix(suffix, ".font")) // (may also be ".font_xyz")
3001 result = gfx.get_font_from_token_function(value);
3003 else // generic parameter of type integer or boolean
3005 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
3006 type == TYPE_INTEGER ? get_integer_from_string(value) :
3007 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
3008 ARG_UNDEFINED_VALUE);
3016 static void FreeCustomArtworkList(struct ArtworkListInfo *,
3017 struct ListNodeInfo ***, int *);
3019 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
3020 struct ConfigTypeInfo *suffix_list,
3021 char **ignore_tokens,
3022 int num_file_list_entries)
3024 SetupFileHash *ignore_tokens_hash;
3025 struct FileInfo *file_list;
3026 int num_file_list_entries_found = 0;
3027 int num_suffix_list_entries = 0;
3031 // create hash from list of tokens to be ignored (for quick access)
3032 ignore_tokens_hash = newSetupFileHash();
3033 for (i = 0; ignore_tokens[i] != NULL; i++)
3034 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
3036 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
3038 for (i = 0; suffix_list[i].token != NULL; i++)
3039 num_suffix_list_entries++;
3041 // always start with reliable default values
3042 for (i = 0; i < num_file_list_entries; i++)
3044 file_list[i].token = NULL;
3046 file_list[i].default_filename = NULL;
3047 file_list[i].filename = NULL;
3049 if (num_suffix_list_entries > 0)
3051 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3053 file_list[i].default_parameter = checked_calloc(parameter_array_size);
3054 file_list[i].parameter = checked_calloc(parameter_array_size);
3056 for (j = 0; j < num_suffix_list_entries; j++)
3058 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
3059 setString(&file_list[i].parameter[j], suffix_list[j].value);
3062 file_list[i].redefined = FALSE;
3063 file_list[i].fallback_to_default = FALSE;
3064 file_list[i].default_is_cloned = FALSE;
3070 for (i = 0; config_list[i].token != NULL; i++)
3072 int len_config_token = strlen(config_list[i].token);
3073 boolean is_file_entry = TRUE;
3075 for (j = 0; suffix_list[j].token != NULL; j++)
3077 int len_suffix = strlen(suffix_list[j].token);
3079 if (len_suffix < len_config_token &&
3080 strEqual(&config_list[i].token[len_config_token - len_suffix],
3081 suffix_list[j].token))
3083 setString(&file_list[list_pos].default_parameter[j],
3084 config_list[i].value);
3086 is_file_entry = FALSE;
3092 // the following tokens are no file definitions, but other config tokens
3093 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
3094 is_file_entry = FALSE;
3101 if (list_pos >= num_file_list_entries)
3104 file_list[list_pos].token = config_list[i].token;
3105 file_list[list_pos].default_filename = config_list[i].value;
3108 if (strSuffix(config_list[i].token, ".clone_from"))
3109 file_list[list_pos].default_is_cloned = TRUE;
3112 num_file_list_entries_found = list_pos + 1;
3113 if (num_file_list_entries_found != num_file_list_entries)
3115 Error(ERR_INFO_LINE, "-");
3116 Error(ERR_INFO, "inconsistant config list information:");
3117 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
3118 num_file_list_entries);
3119 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
3120 num_file_list_entries_found);
3121 Error(ERR_EXIT, "please fix");
3124 freeSetupFileHash(ignore_tokens_hash);
3129 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3131 int len_token = strlen(token);
3132 int len_suffix = strlen(suffix);
3134 if (start_pos < 0) // compare suffix from end of string
3135 start_pos += len_token;
3137 if (start_pos < 0 || start_pos + len_suffix > len_token)
3140 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3143 if (token[start_pos + len_suffix] == '\0')
3146 if (token[start_pos + len_suffix] == '.')
3152 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3154 static void read_token_parameters(SetupFileHash *setup_file_hash,
3155 struct ConfigTypeInfo *suffix_list,
3156 struct FileInfo *file_list_entry)
3158 // check for config token that is the base token without any suffixes
3159 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3160 char *known_token_value = KNOWN_TOKEN_VALUE;
3163 if (filename != NULL)
3165 setString(&file_list_entry->filename, filename);
3167 // when file definition found, set all parameters to default values
3168 for (i = 0; suffix_list[i].token != NULL; i++)
3169 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3171 file_list_entry->redefined = TRUE;
3173 // mark config file token as well known from default config
3174 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3177 // check for config tokens that can be build by base token and suffixes
3178 for (i = 0; suffix_list[i].token != NULL; i++)
3180 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3181 char *value = getHashEntry(setup_file_hash, token);
3185 setString(&file_list_entry->parameter[i], value);
3187 // mark config file token as well known from default config
3188 setHashEntry(setup_file_hash, token, known_token_value);
3195 static void add_dynamic_file_list_entry(struct FileInfo **list,
3196 int *num_list_entries,
3197 SetupFileHash *extra_file_hash,
3198 struct ConfigTypeInfo *suffix_list,
3199 int num_suffix_list_entries,
3202 struct FileInfo *new_list_entry;
3203 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3205 (*num_list_entries)++;
3206 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3207 new_list_entry = &(*list)[*num_list_entries - 1];
3209 new_list_entry->token = getStringCopy(token);
3210 new_list_entry->default_filename = NULL;
3211 new_list_entry->filename = NULL;
3212 new_list_entry->parameter = checked_calloc(parameter_array_size);
3214 new_list_entry->redefined = FALSE;
3215 new_list_entry->fallback_to_default = FALSE;
3216 new_list_entry->default_is_cloned = FALSE;
3218 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3221 static void add_property_mapping(struct PropertyMapping **list,
3222 int *num_list_entries,
3223 int base_index, int ext1_index,
3224 int ext2_index, int ext3_index,
3227 struct PropertyMapping *new_list_entry;
3229 (*num_list_entries)++;
3230 *list = checked_realloc(*list,
3231 *num_list_entries * sizeof(struct PropertyMapping));
3232 new_list_entry = &(*list)[*num_list_entries - 1];
3234 new_list_entry->base_index = base_index;
3235 new_list_entry->ext1_index = ext1_index;
3236 new_list_entry->ext2_index = ext2_index;
3237 new_list_entry->ext3_index = ext3_index;
3239 new_list_entry->artwork_index = artwork_index;
3242 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3245 struct FileInfo *file_list = artwork_info->file_list;
3246 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3247 char **base_prefixes = artwork_info->base_prefixes;
3248 char **ext1_suffixes = artwork_info->ext1_suffixes;
3249 char **ext2_suffixes = artwork_info->ext2_suffixes;
3250 char **ext3_suffixes = artwork_info->ext3_suffixes;
3251 char **ignore_tokens = artwork_info->ignore_tokens;
3252 int num_file_list_entries = artwork_info->num_file_list_entries;
3253 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3254 int num_base_prefixes = artwork_info->num_base_prefixes;
3255 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3256 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3257 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3258 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3259 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3260 SetupFileHash *extra_file_hash, *empty_file_hash;
3261 char *known_token_value = KNOWN_TOKEN_VALUE;
3262 char *base_token_value = UNDEFINED_FILENAME;
3265 if (filename == NULL)
3268 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3271 // separate valid (defined) from empty (undefined) config token values
3272 valid_file_hash = newSetupFileHash();
3273 empty_file_hash = newSetupFileHash();
3274 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3276 char *value = HASH_ITERATION_VALUE(itr);
3278 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3279 HASH_ITERATION_TOKEN(itr), value);
3281 END_HASH_ITERATION(setup_file_hash, itr)
3283 // at this point, we do not need the setup file hash anymore -- free it
3284 freeSetupFileHash(setup_file_hash);
3286 // prevent changing hash while iterating over it by using a temporary copy
3287 valid_file_hash_tmp = newSetupFileHash();
3288 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3290 setHashEntry(valid_file_hash_tmp,
3291 HASH_ITERATION_TOKEN(itr),
3292 HASH_ITERATION_VALUE(itr));
3294 END_HASH_ITERATION(valid_file_hash, itr)
3296 // (iterate over same temporary hash, as modifications are independent)
3298 // map deprecated to current tokens (using prefix match and replace)
3299 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3301 char *token = HASH_ITERATION_TOKEN(itr);
3302 char *mapped_token = get_mapped_token(token);
3304 if (mapped_token != NULL)
3306 char *value = HASH_ITERATION_VALUE(itr);
3309 setHashEntry(valid_file_hash, mapped_token, value);
3311 // ignore old token (by setting it to "known" keyword)
3312 setHashEntry(valid_file_hash, token, known_token_value);
3317 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3319 // add special base tokens (using prefix match and replace)
3320 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3322 char *token = HASH_ITERATION_TOKEN(itr);
3323 char *base_token = get_special_base_token(artwork_info, token);
3325 if (base_token != NULL)
3327 // add base token only if it does not already exist
3328 if (getHashEntry(valid_file_hash, base_token) == NULL)
3329 setHashEntry(valid_file_hash, base_token, base_token_value);
3334 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3336 // free temporary hash used for iteration
3337 freeSetupFileHash(valid_file_hash_tmp);
3339 // read parameters for all known config file tokens
3340 for (i = 0; i < num_file_list_entries; i++)
3341 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3343 // set all tokens that can be ignored here to "known" keyword
3344 for (i = 0; i < num_ignore_tokens; i++)
3345 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3347 // copy all unknown config file tokens to extra config hash
3348 extra_file_hash = newSetupFileHash();
3349 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3351 char *value = HASH_ITERATION_VALUE(itr);
3353 if (!strEqual(value, known_token_value))
3354 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3356 END_HASH_ITERATION(valid_file_hash, itr)
3358 // at this point, we do not need the valid file hash anymore -- free it
3359 freeSetupFileHash(valid_file_hash);
3361 // now try to determine valid, dynamically defined config tokens
3363 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3365 struct FileInfo **dynamic_file_list =
3366 &artwork_info->dynamic_file_list;
3367 int *num_dynamic_file_list_entries =
3368 &artwork_info->num_dynamic_file_list_entries;
3369 struct PropertyMapping **property_mapping =
3370 &artwork_info->property_mapping;
3371 int *num_property_mapping_entries =
3372 &artwork_info->num_property_mapping_entries;
3373 int current_summarized_file_list_entry =
3374 artwork_info->num_file_list_entries +
3375 artwork_info->num_dynamic_file_list_entries;
3376 char *token = HASH_ITERATION_TOKEN(itr);
3377 int len_token = strlen(token);
3379 boolean base_prefix_found = FALSE;
3380 boolean parameter_suffix_found = FALSE;
3382 // skip all parameter definitions (handled by read_token_parameters())
3383 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3385 int len_suffix = strlen(suffix_list[i].token);
3387 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3388 parameter_suffix_found = TRUE;
3391 if (parameter_suffix_found)
3394 // ---------- step 0: search for matching base prefix ----------
3397 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3399 char *base_prefix = base_prefixes[i];
3400 int len_base_prefix = strlen(base_prefix);
3401 boolean ext1_suffix_found = FALSE;
3402 boolean ext2_suffix_found = FALSE;
3403 boolean ext3_suffix_found = FALSE;
3404 boolean exact_match = FALSE;
3405 int base_index = -1;
3406 int ext1_index = -1;
3407 int ext2_index = -1;
3408 int ext3_index = -1;
3410 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3412 if (!base_prefix_found)
3417 if (start_pos + len_base_prefix == len_token) // exact match
3421 add_dynamic_file_list_entry(dynamic_file_list,
3422 num_dynamic_file_list_entries,
3425 num_suffix_list_entries,
3427 add_property_mapping(property_mapping,
3428 num_property_mapping_entries,
3429 base_index, -1, -1, -1,
3430 current_summarized_file_list_entry);
3434 // ---------- step 1: search for matching first suffix ----------
3436 start_pos += len_base_prefix;
3437 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3439 char *ext1_suffix = ext1_suffixes[j];
3440 int len_ext1_suffix = strlen(ext1_suffix);
3442 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3444 if (!ext1_suffix_found)
3449 if (start_pos + len_ext1_suffix == len_token) // exact match
3453 add_dynamic_file_list_entry(dynamic_file_list,
3454 num_dynamic_file_list_entries,
3457 num_suffix_list_entries,
3459 add_property_mapping(property_mapping,
3460 num_property_mapping_entries,
3461 base_index, ext1_index, -1, -1,
3462 current_summarized_file_list_entry);
3466 start_pos += len_ext1_suffix;
3472 // ---------- step 2: search for matching second suffix ----------
3474 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3476 char *ext2_suffix = ext2_suffixes[k];
3477 int len_ext2_suffix = strlen(ext2_suffix);
3479 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3481 if (!ext2_suffix_found)
3486 if (start_pos + len_ext2_suffix == len_token) // exact match
3490 add_dynamic_file_list_entry(dynamic_file_list,
3491 num_dynamic_file_list_entries,
3494 num_suffix_list_entries,
3496 add_property_mapping(property_mapping,
3497 num_property_mapping_entries,
3498 base_index, ext1_index, ext2_index, -1,
3499 current_summarized_file_list_entry);
3503 start_pos += len_ext2_suffix;
3509 // ---------- step 3: search for matching third suffix ----------
3511 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3513 char *ext3_suffix = ext3_suffixes[l];
3514 int len_ext3_suffix = strlen(ext3_suffix);
3516 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3518 if (!ext3_suffix_found)
3523 if (start_pos + len_ext3_suffix == len_token) // exact match
3527 add_dynamic_file_list_entry(dynamic_file_list,
3528 num_dynamic_file_list_entries,
3531 num_suffix_list_entries,
3533 add_property_mapping(property_mapping,
3534 num_property_mapping_entries,
3535 base_index, ext1_index, ext2_index, ext3_index,
3536 current_summarized_file_list_entry);
3542 END_HASH_ITERATION(extra_file_hash, itr)
3544 if (artwork_info->num_dynamic_file_list_entries > 0)
3546 artwork_info->dynamic_artwork_list =
3547 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3548 artwork_info->sizeof_artwork_list_entry);
3551 if (options.verbose && IS_PARENT_PROCESS())
3553 SetupFileList *setup_file_list, *list;
3554 boolean dynamic_tokens_found = FALSE;
3555 boolean unknown_tokens_found = FALSE;
3556 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3558 // list may be NULL for empty artwork config files
3559 setup_file_list = loadSetupFileList(filename);
3561 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3563 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3564 dynamic_tokens_found = TRUE;
3566 unknown_tokens_found = TRUE;
3568 END_HASH_ITERATION(extra_file_hash, itr)
3570 if (options.debug && dynamic_tokens_found)
3572 Error(ERR_INFO_LINE, "-");
3573 Error(ERR_INFO, "dynamic token(s) found in config file:");
3574 Error(ERR_INFO, "- config file: '%s'", filename);
3576 for (list = setup_file_list; list != NULL; list = list->next)
3578 char *value = getHashEntry(extra_file_hash, list->token);
3580 if (value != NULL && strEqual(value, known_token_value))
3581 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3584 Error(ERR_INFO_LINE, "-");
3587 if (unknown_tokens_found)
3589 Error(ERR_INFO_LINE, "-");
3590 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3591 Error(ERR_INFO, "- config file: '%s'", filename);
3593 for (list = setup_file_list; list != NULL; list = list->next)
3595 char *value = getHashEntry(extra_file_hash, list->token);
3597 if (value != NULL && !strEqual(value, known_token_value))
3598 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3601 Error(ERR_INFO_LINE, "-");
3604 if (undefined_values_found)
3606 Error(ERR_INFO_LINE, "-");
3607 Error(ERR_INFO, "warning: undefined values found in config file:");
3608 Error(ERR_INFO, "- config file: '%s'", filename);
3610 for (list = setup_file_list; list != NULL; list = list->next)
3612 char *value = getHashEntry(empty_file_hash, list->token);
3615 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3618 Error(ERR_INFO_LINE, "-");
3621 freeSetupFileList(setup_file_list);
3624 freeSetupFileHash(extra_file_hash);
3625 freeSetupFileHash(empty_file_hash);
3628 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3630 struct FileInfo *file_list = artwork_info->file_list;
3631 int num_file_list_entries = artwork_info->num_file_list_entries;
3632 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3633 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3636 DrawInitText("Loading artwork config", 120, FC_GREEN);
3637 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3639 // always start with reliable default values
3640 for (i = 0; i < num_file_list_entries; i++)
3642 setString(&file_list[i].filename, file_list[i].default_filename);
3644 for (j = 0; j < num_suffix_list_entries; j++)
3645 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3647 file_list[i].redefined = FALSE;
3648 file_list[i].fallback_to_default = FALSE;
3651 // free previous dynamic artwork file array
3652 if (artwork_info->dynamic_file_list != NULL)
3654 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3656 free(artwork_info->dynamic_file_list[i].token);
3657 free(artwork_info->dynamic_file_list[i].filename);
3658 free(artwork_info->dynamic_file_list[i].parameter);
3661 free(artwork_info->dynamic_file_list);
3662 artwork_info->dynamic_file_list = NULL;
3664 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3665 &artwork_info->num_dynamic_file_list_entries);
3668 // free previous property mapping
3669 if (artwork_info->property_mapping != NULL)
3671 free(artwork_info->property_mapping);
3673 artwork_info->property_mapping = NULL;
3674 artwork_info->num_property_mapping_entries = 0;
3677 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3679 // first look for special artwork configured in level series config
3680 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3682 if (fileExists(filename_base))
3683 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3686 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3688 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3689 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3692 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3693 struct ListNodeInfo **listnode)
3697 char *filename = (*listnode)->source_filename;
3699 if (--(*listnode)->num_references <= 0)
3700 deleteNodeFromList(&artwork_info->content_list, filename,
3701 artwork_info->free_artwork);
3707 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3708 struct ListNodeInfo **listnode,
3709 struct FileInfo *file_list_entry)
3719 char *basename = file_list_entry->filename;
3720 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3722 if (filename == NULL)
3724 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3726 basename = file_list_entry->default_filename;
3728 // fail for cloned default artwork that has no default filename defined
3729 if (file_list_entry->default_is_cloned &&
3730 strEqual(basename, UNDEFINED_FILENAME))
3732 int error_mode = ERR_WARN;
3734 // we can get away without sounds and music, but not without graphics
3735 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3736 error_mode = ERR_EXIT;
3738 Error(error_mode, "token '%s' was cloned and has no default filename",
3739 file_list_entry->token);
3744 // dynamic artwork has no default filename / skip empty default artwork
3745 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3748 file_list_entry->fallback_to_default = TRUE;
3750 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3752 filename = getCustomArtworkFilename(basename, artwork_info->type);
3754 if (filename == NULL)
3756 int error_mode = ERR_WARN;
3758 // we can get away without sounds and music, but not without graphics
3759 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3760 error_mode = ERR_EXIT;
3762 Error(error_mode, "cannot find default artwork file '%s'", basename);
3768 // check if the old and the new artwork file are the same
3769 if (*listnode && strEqual((*listnode)->source_filename, filename))
3771 // The old and new artwork are the same (have the same filename and path).
3772 // This usually means that this artwork does not exist in this artwork set
3773 // and a fallback to the existing artwork is done.
3778 // delete existing artwork file entry
3779 deleteArtworkListEntry(artwork_info, listnode);
3781 // check if the new artwork file already exists in the list of artwork
3782 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3784 *listnode = (struct ListNodeInfo *)node->content;
3785 (*listnode)->num_references++;
3790 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3791 DrawInitText(basename, 150, FC_YELLOW);
3793 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3795 // add new artwork file entry to the list of artwork files
3796 (*listnode)->num_references = 1;
3797 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3802 int error_mode = ERR_WARN;
3804 // we can get away without sounds and music, but not without graphics
3805 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3806 error_mode = ERR_EXIT;
3808 Error(error_mode, "cannot load artwork file '%s'", basename);
3814 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3815 struct ListNodeInfo **listnode,
3816 struct FileInfo *file_list_entry)
3818 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3820 deleteArtworkListEntry(artwork_info, listnode);
3825 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3828 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3830 struct FileInfo *file_list = artwork_info->file_list;
3831 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3832 int num_file_list_entries = artwork_info->num_file_list_entries;
3833 int num_dynamic_file_list_entries =
3834 artwork_info->num_dynamic_file_list_entries;
3837 print_timestamp_init("ReloadCustomArtworkList");
3839 for (i = 0; i < num_file_list_entries; i++)
3840 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3843 for (i = 0; i < num_dynamic_file_list_entries; i++)
3844 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3845 &dynamic_file_list[i]);
3847 print_timestamp_done("ReloadCustomArtworkList");
3850 dumpList(artwork_info->content_list);
3854 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3855 struct ListNodeInfo ***list,
3856 int *num_list_entries)
3863 for (i = 0; i < *num_list_entries; i++)
3864 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3868 *num_list_entries = 0;
3871 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3873 if (artwork_info == NULL)
3876 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3877 &artwork_info->num_file_list_entries);
3879 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3880 &artwork_info->num_dynamic_file_list_entries);
3884 // ----------------------------------------------------------------------------
3885 // functions only needed for non-Unix (non-command-line) systems
3886 // (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")
3887 // (now also added for Windows, to create files in user data directory)
3888 // ----------------------------------------------------------------------------
3890 char *getLogFilename(char *basename)
3892 return getPath2(getUserGameDataDir(), basename);
3895 void OpenLogFiles(void)
3899 InitUserDataDirectory();
3901 for (i = 0; i < NUM_LOGS; i++)
3903 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3906 program.log_file[i] = program.log_file_default[i]; // reset to default
3908 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3909 program.log_filename[i], strerror(errno));
3912 // output should be unbuffered so it is not truncated in a crash
3913 setbuf(program.log_file[i], NULL);
3917 void CloseLogFiles(void)
3921 for (i = 0; i < NUM_LOGS; i++)
3922 if (program.log_file[i] != program.log_file_default[i])
3923 fclose(program.log_file[i]);
3926 void DumpLogFile(int nr)
3928 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3930 if (log_file == NULL)
3933 while (!feof(log_file))
3934 fputc(fgetc(log_file), stdout);
3939 void NotifyUserAboutErrorFile(void)
3941 #if defined(PLATFORM_WIN32)
3942 char *title_text = getStringCat2(program.program_title, " Error Message");
3943 char *error_text = getStringCat2("The program was aborted due to an error; "
3944 "for details, see the following error file:"
3946 program.log_filename[LOG_ERR_ID]);
3948 MessageBox(NULL, error_text, title_text, MB_OK);
3953 // ----------------------------------------------------------------------------
3954 // the following is only for debugging purpose and normally not used
3955 // ----------------------------------------------------------------------------
3959 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3960 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3962 #define DEBUG_NUM_TIMESTAMPS 10
3963 #define DEBUG_TIME_IN_MICROSECONDS 0
3965 #if DEBUG_TIME_IN_MICROSECONDS
3966 static double Counter_Microseconds(void)
3968 static struct timeval base_time = { 0, 0 };
3969 struct timeval current_time;
3972 gettimeofday(¤t_time, NULL);
3974 // reset base time in case of wrap-around
3975 if (current_time.tv_sec < base_time.tv_sec)
3976 base_time = current_time;
3979 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3980 ((double)(current_time.tv_usec - base_time.tv_usec));
3982 return counter; // return microseconds since last init
3986 static char *debug_print_timestamp_get_padding(int padding_size)
3988 static char *padding = NULL;
3989 int max_padding_size = 100;
3991 if (padding == NULL)
3993 padding = checked_calloc(max_padding_size + 1);
3994 memset(padding, ' ', max_padding_size);
3997 return &padding[MAX(0, max_padding_size - padding_size)];
4000 void debug_print_timestamp(int counter_nr, char *message)
4002 int indent_size = 8;
4003 int padding_size = 40;
4004 float timestamp_interval;
4007 Error(ERR_EXIT, "debugging: invalid negative counter");
4008 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
4009 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
4011 #if DEBUG_TIME_IN_MICROSECONDS
4012 static double counter[DEBUG_NUM_TIMESTAMPS][2];
4015 counter[counter_nr][0] = Counter_Microseconds();
4017 static int counter[DEBUG_NUM_TIMESTAMPS][2];
4020 counter[counter_nr][0] = Counter();
4023 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
4024 counter[counter_nr][1] = counter[counter_nr][0];
4027 Error(ERR_DEBUG, "%s%s%s %.3f %s",
4028 debug_print_timestamp_get_padding(counter_nr * indent_size),
4030 debug_print_timestamp_get_padding(padding_size - strlen(message)),
4031 timestamp_interval / 1000,
4036 static void debug_print_parent_only(char *format, ...)
4038 if (!IS_PARENT_PROCESS())
4045 va_start(ap, format);
4046 vprintf(format, ap);
4056 static void print_timestamp_ext(char *message, char *mode)
4058 #if DEBUG_PRINT_INIT_TIMESTAMPS
4059 static char *debug_message = NULL;
4060 static char *last_message = NULL;
4061 static int counter_nr = 0;
4062 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
4064 checked_free(debug_message);
4065 debug_message = getStringCat3(mode, " ", message);
4067 if (strEqual(mode, "INIT"))
4069 debug_print_timestamp(counter_nr, NULL);
4071 if (counter_nr + 1 < max_depth)
4072 debug_print_timestamp(counter_nr, debug_message);
4076 debug_print_timestamp(counter_nr, NULL);
4078 else if (strEqual(mode, "DONE"))
4082 if (counter_nr + 1 < max_depth ||
4083 (counter_nr == 0 && max_depth == 1))
4085 last_message = message;
4087 if (counter_nr == 0 && max_depth == 1)
4089 checked_free(debug_message);
4090 debug_message = getStringCat3("TIME", " ", message);
4093 debug_print_timestamp(counter_nr, debug_message);
4096 else if (!strEqual(mode, "TIME") ||
4097 !strEqual(message, last_message))
4099 if (counter_nr < max_depth)
4100 debug_print_timestamp(counter_nr, debug_message);
4105 void print_timestamp_init(char *message)
4107 print_timestamp_ext(message, "INIT");
4110 void print_timestamp_time(char *message)
4112 print_timestamp_ext(message, "TIME");
4115 void print_timestamp_done(char *message)
4117 print_timestamp_ext(message, "DONE");