1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
14 #include <sys/types.h>
24 #if !defined(PLATFORM_WIN32)
26 #include <sys/param.h>
36 /* ========================================================================= */
37 /* some generic helper functions */
38 /* ========================================================================= */
40 /* ------------------------------------------------------------------------- */
41 /* logging functions */
42 /* ------------------------------------------------------------------------- */
44 #define DUPLICATE_LOG_OUT_TO_STDOUT TRUE
45 #define DUPLICATE_LOG_ERR_TO_STDERR TRUE
48 #if defined(PLATFORM_ANDROID)
49 static int android_log_prio = ANDROID_LOG_INFO;
50 static char *android_log_buffer = NULL;
52 static void append_to_android_log_buffer(char *format, va_list ap)
54 char text_new[MAX_OUTPUT_LINESIZE];
56 // print text to temporary string
57 vsnprintf(text_new, MAX_OUTPUT_LINESIZE, format, ap);
59 if (android_log_buffer == NULL)
61 android_log_buffer = getStringCopy(text_new);
65 char *android_log_buffer_old = android_log_buffer;
67 // append new text to existing text
68 android_log_buffer = getStringCat2(android_log_buffer, text_new);
70 checked_free(android_log_buffer_old);
74 static void vprintf_log_nonewline(char *format, va_list ap)
76 // add log output to buffer until text with newline is printed
77 append_to_android_log_buffer(format, ap);
80 static void vprintf_log(char *format, va_list ap)
82 // add log output to buffer
83 append_to_android_log_buffer(format, ap);
85 // __android_log_vprint(android_log_prio, program.program_title, format, ap);
86 __android_log_write(android_log_prio, program.program_title,
89 checked_free(android_log_buffer);
90 android_log_buffer = NULL;
95 static void vprintf_log_nonewline(char *format, va_list ap)
97 FILE *file = program.log_file[LOG_ERR_ID];
99 #if DUPLICATE_LOG_ERR_TO_STDERR
100 if (file != program.log_file_default[LOG_ERR_ID])
105 vfprintf(program.log_file_default[LOG_ERR_ID], format, ap2);
111 vfprintf(file, format, ap);
114 static void vprintf_log(char *format, va_list ap)
116 FILE *file = program.log_file[LOG_ERR_ID];
117 char *newline = STRING_NEWLINE;
119 #if DUPLICATE_LOG_ERR_TO_STDERR
120 if (file != program.log_file_default[LOG_ERR_ID])
125 vfprintf(program.log_file_default[LOG_ERR_ID], format, ap2);
126 fprintf(program.log_file_default[LOG_ERR_ID], "%s", newline);
132 vfprintf(file, format, ap);
133 fprintf(file, "%s", newline);
137 static void printf_log_nonewline(char *format, ...)
141 va_start(ap, format);
142 vprintf_log_nonewline(format, ap);
146 static void printf_log(char *format, ...)
150 va_start(ap, format);
151 vprintf_log(format, ap);
155 static void printf_log_line(char *line_chars, int line_length)
159 for (i = 0; i < line_length; i++)
160 printf_log_nonewline("%s", line_chars);
166 /* ------------------------------------------------------------------------- */
167 /* platform independent wrappers for printf() et al. */
168 /* ------------------------------------------------------------------------- */
170 void fprintf_line(FILE *file, char *line_chars, int line_length)
174 for (i = 0; i < line_length; i++)
175 fprintf(file, "%s", line_chars);
180 void fprintf_line_with_prefix(FILE *file, char *prefix, char *line_chars,
183 fprintf(file, "%s", prefix);
184 fprintf_line(file, line_chars, line_length);
187 void printf_line(char *line_chars, int line_length)
189 fprintf_line(stdout, line_chars, line_length);
192 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
194 fprintf_line_with_prefix(stdout, prefix, line_chars, line_length);
197 static void vPrint(char *format, va_list ap)
199 FILE *file = program.log_file[LOG_OUT_ID];
201 #if DUPLICATE_LOG_OUT_TO_STDOUT
202 if (file != program.log_file_default[LOG_OUT_ID])
207 vfprintf(program.log_file_default[LOG_OUT_ID], format, ap2);
213 vfprintf(file, format, ap);
216 void Print(char *format, ...)
220 va_start(ap, format);
225 void PrintNoLog(char *format, ...)
227 FILE *file = program.log_file_default[LOG_OUT_ID];
230 va_start(ap, format);
231 vfprintf(file, format, ap);
237 void PrintLine(char *line_chars, int line_length)
241 for (i = 0; i < line_length; i++)
247 void PrintLineWithPrefix(char *prefix, char *line_chars, int line_length)
250 PrintLine(line_chars, line_length);
254 /* ------------------------------------------------------------------------- */
255 /* string functions */
256 /* ------------------------------------------------------------------------- */
258 /* int2str() returns a number converted to a string;
259 the used memory is static, but will be overwritten by later calls,
260 so if you want to save the result, copy it to a private string buffer;
261 there can be 10 local calls of int2str() without buffering the result --
262 the 11th call will then destroy the result from the first call and so on.
265 char *int2str(int number, int size)
267 static char shift_array[10][40];
268 static int shift_counter = 0;
269 char *s = shift_array[shift_counter];
271 shift_counter = (shift_counter + 1) % 10;
278 sprintf(s, " %09d", number);
279 return &s[strlen(s) - size];
283 sprintf(s, "%d", number);
289 /* something similar to "int2str()" above, but allocates its own memory
290 and has a different interface; we cannot use "itoa()", because this
291 seems to be already defined when cross-compiling to the win32 target */
293 char *i_to_a(unsigned int i)
295 static char *a = NULL;
299 if (i > 2147483647) /* yes, this is a kludge */
302 a = checked_malloc(10 + 1);
310 /* calculate base-2 logarithm of argument (rounded down to integer;
311 this function returns the number of the highest bit set in argument) */
313 int log_2(unsigned int x)
319 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
326 boolean getTokenValueFromString(char *string, char **token, char **value)
328 return getTokenValueFromSetupLine(string, token, value);
332 /* ------------------------------------------------------------------------- */
333 /* counter functions */
334 /* ------------------------------------------------------------------------- */
336 /* maximal allowed length of a command line option */
337 #define MAX_OPTION_LEN 256
339 static unsigned int getCurrentMS()
341 return SDL_GetTicks();
344 static unsigned int mainCounter(int mode)
346 static unsigned int base_ms = 0;
347 unsigned int current_ms;
349 /* get current system milliseconds */
350 current_ms = getCurrentMS();
352 /* reset base timestamp in case of counter reset or wrap-around */
353 if (mode == INIT_COUNTER || current_ms < base_ms)
354 base_ms = current_ms;
356 /* return milliseconds since last counter reset */
357 return current_ms - base_ms;
360 void InitCounter() /* set counter back to zero */
362 mainCounter(INIT_COUNTER);
365 unsigned int Counter() /* get milliseconds since last call of InitCounter() */
367 return mainCounter(READ_COUNTER);
370 static void sleep_milliseconds(unsigned int milliseconds_delay)
372 SDL_Delay(milliseconds_delay);
375 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
377 sleep_milliseconds(delay);
380 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
381 unsigned int actual_counter)
383 if (actual_counter >= *counter_var &&
384 actual_counter < *counter_var + delay)
387 *counter_var = actual_counter;
392 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
394 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
397 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
399 return DelayReachedExt(counter_var, delay, Counter());
402 void ResetDelayCounterExt(unsigned int *counter_var,
403 unsigned int actual_counter)
405 DelayReachedExt(counter_var, 0, actual_counter);
408 void ResetFrameCounter(unsigned int *frame_counter_var)
410 FrameReached(frame_counter_var, 0);
413 void ResetDelayCounter(unsigned int *counter_var)
415 DelayReached(counter_var, 0);
418 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
420 unsigned int actual_counter;
425 actual_counter = Counter();
427 if (actual_counter >= *counter_var &&
428 actual_counter < *counter_var + delay)
429 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
434 if (*counter_var != 0 &&
436 actual_counter >= *counter_var + delay)
438 int lag = actual_counter - (*counter_var + delay);
439 int delay2 = (delay + 1) / 2;
442 skip_frames = (lag + delay2) / delay;
445 *counter_var = actual_counter;
450 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
451 int *loop_var, int last_loop_value)
453 int skip_frames = WaitUntilDelayReached(counter_var, delay);
457 printf("::: %d: %d ms", *loop_var, delay);
459 printf(" -> SKIP %d FRAME(S) [%d ms]", skip_frames, skip_frames * delay);
464 if (skip_frames == 0)
467 // when skipping frames, make sure to never skip the last frame, as
468 // this may be needed for animations to reach a defined end state;
469 // furthermore, we assume that this function is called at the end
470 // of a "for" loop, which continues by incrementing the loop variable
471 // by one before checking the loop condition again; therefore we have
472 // to check against the last loop value minus one here
476 if (*loop_var < last_loop_value) // never skip the last frame
478 *loop_var += skip_frames;
480 if (*loop_var > last_loop_value) // never skip the last frame
481 *loop_var = last_loop_value;
486 /* ------------------------------------------------------------------------- */
487 /* random generator functions */
488 /* ------------------------------------------------------------------------- */
490 unsigned int init_random_number(int nr, int seed)
492 if (seed == NEW_RANDOMIZE)
494 /* default random seed */
495 seed = (int)time(NULL); // seconds since the epoch
497 #if !defined(PLATFORM_WIN32)
498 /* add some more randomness */
499 struct timeval current_time;
501 gettimeofday(¤t_time, NULL);
503 seed += (int)current_time.tv_usec; // microseconds since the epoch
506 /* add some more randomness */
507 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
509 /* add some more randomness */
510 seed += GetSimpleRandom(1000000);
513 srandom_linux_libc(nr, (unsigned int) seed);
515 return (unsigned int) seed;
518 unsigned int get_random_number(int nr, int max)
520 return (max > 0 ? random_linux_libc(nr) % max : 0);
524 /* ------------------------------------------------------------------------- */
525 /* system info functions */
526 /* ------------------------------------------------------------------------- */
528 #if !defined(PLATFORM_ANDROID)
529 static char *get_corrected_real_name(char *real_name)
531 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
532 char *from_ptr = real_name;
533 char *to_ptr = real_name_new;
535 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
536 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
538 /* the name field read from "passwd" file may also contain additional
539 user information, separated by commas, which will be removed here */
540 if (*from_ptr == ',')
543 /* the user's real name may contain 'german sharp s' characters,
544 which have no equivalent in upper case letters (used by our fonts) */
545 if (*from_ptr == CHAR_BYTE_SHARP_S)
552 *to_ptr++ = *from_ptr++;
557 return real_name_new;
563 static char *login_name = NULL;
565 #if defined(PLATFORM_WIN32)
566 if (login_name == NULL)
568 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
569 login_name = checked_malloc(buffer_size);
571 if (GetUserName(login_name, &buffer_size) == 0)
572 strcpy(login_name, ANONYMOUS_NAME);
574 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
575 if (login_name == NULL)
579 if ((pwd = getpwuid(getuid())) == NULL)
580 login_name = ANONYMOUS_NAME;
582 login_name = getStringCopy(pwd->pw_name);
585 login_name = ANONYMOUS_NAME;
593 static char *real_name = NULL;
595 #if defined(PLATFORM_WIN32)
596 if (real_name == NULL)
598 static char buffer[MAX_USERNAME_LEN + 1];
599 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
601 if (GetUserName(buffer, &buffer_size) != 0)
602 real_name = get_corrected_real_name(buffer);
604 real_name = ANONYMOUS_NAME;
606 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
607 if (real_name == NULL)
611 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
612 real_name = get_corrected_real_name(pwd->pw_gecos);
614 real_name = ANONYMOUS_NAME;
617 real_name = ANONYMOUS_NAME;
623 time_t getFileTimestampEpochSeconds(char *filename)
625 struct stat file_status;
627 if (stat(filename, &file_status) != 0) /* cannot stat file */
630 return file_status.st_mtime;
634 /* ------------------------------------------------------------------------- */
635 /* path manipulation functions */
636 /* ------------------------------------------------------------------------- */
638 static char *getLastPathSeparatorPtr(char *filename)
640 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
642 if (last_separator == NULL) /* also try DOS/Windows variant */
643 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
645 return last_separator;
648 char *getBaseNamePtr(char *filename)
650 char *last_separator = getLastPathSeparatorPtr(filename);
652 if (last_separator != NULL)
653 return last_separator + 1; /* separator found: strip base path */
655 return filename; /* no separator found: filename has no path */
658 char *getBaseName(char *filename)
660 return getStringCopy(getBaseNamePtr(filename));
663 char *getBaseNameNoSuffix(char *filename)
665 char *basename = getStringCopy(getBaseNamePtr(filename));
667 // remove trailing suffix (separated by dot or hyphen)
668 if (basename[0] != '.' && basename[0] != '-')
670 if (strchr(basename, '.') != NULL)
671 *strchr(basename, '.') = '\0';
673 if (strchr(basename, '-') != NULL)
674 *strchr(basename, '-') = '\0';
680 char *getBasePath(char *filename)
682 char *basepath = getStringCopy(filename);
683 char *last_separator = getLastPathSeparatorPtr(basepath);
685 /* if no separator was found, use current directory */
686 if (last_separator == NULL)
690 return getStringCopy(".");
693 /* separator found: strip basename */
694 *last_separator = '\0';
700 /* ------------------------------------------------------------------------- */
701 /* various string functions */
702 /* ------------------------------------------------------------------------- */
704 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
706 if (s1 == NULL || s2 == NULL || sep == NULL)
709 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
712 sprintf(complete_string, "%s%s%s", s1, sep, s2);
714 return complete_string;
717 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
719 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
722 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
723 strlen(s2) + strlen(sep) +
726 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
728 return complete_string;
731 char *getStringCat2(char *s1, char *s2)
733 return getStringCat2WithSeparator(s1, s2, "");
736 char *getStringCat3(char *s1, char *s2, char *s3)
738 return getStringCat3WithSeparator(s1, s2, s3, "");
741 char *getPath2(char *path1, char *path2)
743 #if defined(PLATFORM_ANDROID)
744 // workaround for reading from assets directory -- skip "." subdirs in path
745 if (strEqual(path1, "."))
746 return getStringCopy(path2);
747 else if (strEqual(path2, "."))
748 return getStringCopy(path1);
751 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
754 char *getPath3(char *path1, char *path2, char *path3)
756 #if defined(PLATFORM_ANDROID)
757 // workaround for reading from assets directory -- skip "." subdirs in path
758 if (strEqual(path1, "."))
759 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
760 else if (strEqual(path2, "."))
761 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
762 else if (strEqual(path3, "."))
763 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
766 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
769 static char *getPngOrPcxIfNotExists(char *filename)
771 // switch from PNG to PCX file and vice versa, if file does not exist
772 // (backwards compatibility with PCX files used in previous versions)
774 if (!fileExists(filename) && strSuffix(filename, ".png"))
775 strcpy(&filename[strlen(filename) - 3], "pcx");
776 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
777 strcpy(&filename[strlen(filename) - 3], "png");
782 char *getImg2(char *path1, char *path2)
784 return getPngOrPcxIfNotExists(getPath2(path1, path2));
787 char *getImg3(char *path1, char *path2, char *path3)
789 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
792 char *getStringCopy(const char *s)
799 s_copy = checked_malloc(strlen(s) + 1);
805 char *getStringCopyN(const char *s, int n)
808 int s_len = MAX(0, n);
813 s_copy = checked_malloc(s_len + 1);
814 strncpy(s_copy, s, s_len);
815 s_copy[s_len] = '\0';
820 char *getStringCopyNStatic(const char *s, int n)
822 static char *s_copy = NULL;
824 checked_free(s_copy);
826 s_copy = getStringCopyN(s, n);
831 char *getStringToLower(const char *s)
833 char *s_copy = checked_malloc(strlen(s) + 1);
834 char *s_ptr = s_copy;
837 *s_ptr++ = tolower(*s++);
843 void setString(char **old_value, char *new_value)
845 checked_free(*old_value);
847 *old_value = getStringCopy(new_value);
850 boolean strEqual(char *s1, char *s2)
852 return (s1 == NULL && s2 == NULL ? TRUE :
853 s1 == NULL && s2 != NULL ? FALSE :
854 s1 != NULL && s2 == NULL ? FALSE :
855 strcmp(s1, s2) == 0);
858 boolean strEqualN(char *s1, char *s2, int n)
860 return (s1 == NULL && s2 == NULL ? TRUE :
861 s1 == NULL && s2 != NULL ? FALSE :
862 s1 != NULL && s2 == NULL ? FALSE :
863 strncmp(s1, s2, n) == 0);
866 boolean strPrefix(char *s, char *prefix)
868 return (s == NULL && prefix == NULL ? TRUE :
869 s == NULL && prefix != NULL ? FALSE :
870 s != NULL && prefix == NULL ? FALSE :
871 strncmp(s, prefix, strlen(prefix)) == 0);
874 boolean strSuffix(char *s, char *suffix)
876 return (s == NULL && suffix == NULL ? TRUE :
877 s == NULL && suffix != NULL ? FALSE :
878 s != NULL && suffix == NULL ? FALSE :
879 strlen(s) < strlen(suffix) ? FALSE :
880 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
883 boolean strPrefixLower(char *s, char *prefix)
885 char *s_lower = getStringToLower(s);
886 boolean match = strPrefix(s_lower, prefix);
893 boolean strSuffixLower(char *s, char *suffix)
895 char *s_lower = getStringToLower(s);
896 boolean match = strSuffix(s_lower, suffix);
904 /* ------------------------------------------------------------------------- */
905 /* command line option handling functions */
906 /* ------------------------------------------------------------------------- */
908 void GetOptions(int argc, char *argv[],
909 void (*print_usage_function)(void),
910 void (*print_version_function)(void))
912 char *ro_base_path = getProgramMainDataPath(argv[0], RO_BASE_PATH);
913 char *rw_base_path = getProgramMainDataPath(argv[0], RW_BASE_PATH);
914 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
915 char **options_left = &argvplus[1];
917 /* replace original "argv" with null-terminated array of string pointers */
919 argvplus[argc] = argv[argc];
921 /* initialize global program options */
922 options.server_host = NULL;
923 options.server_port = 0;
925 options.ro_base_directory = ro_base_path;
926 options.rw_base_directory = rw_base_path;
927 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
928 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
929 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
930 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
931 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
932 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
934 options.execute_command = NULL;
935 options.special_flags = NULL;
937 options.mytapes = FALSE;
938 options.serveronly = FALSE;
939 options.network = FALSE;
940 options.verbose = FALSE;
941 options.debug = FALSE;
944 options.verbose = TRUE;
946 #if !defined(PLATFORM_UNIX)
947 if (*options_left == NULL) /* no options given -- enable verbose mode */
948 options.verbose = TRUE;
953 #if defined(PLATFORM_ANDROID)
954 options.debug = TRUE;
958 while (*options_left)
960 char option_str[MAX_OPTION_LEN];
961 char *option = options_left[0];
962 char *next_option = options_left[1];
963 char *option_arg = NULL;
964 int option_len = strlen(option);
966 if (option_len >= MAX_OPTION_LEN)
967 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
969 strcpy(option_str, option); /* copy argument into buffer */
972 if (strEqual(option, "--")) /* stop scanning arguments */
975 if (strPrefix(option, "--")) /* treat '--' like '-' */
978 option_arg = strchr(option, '=');
979 if (option_arg == NULL) /* no '=' in option */
980 option_arg = next_option;
983 *option_arg++ = '\0'; /* cut argument from option */
984 if (*option_arg == '\0') /* no argument after '=' */
985 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
988 option_len = strlen(option);
990 if (strEqual(option, "-"))
992 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
994 else if (strncmp(option, "-help", option_len) == 0)
996 print_usage_function();
1000 else if (strncmp(option, "-basepath", option_len) == 0)
1002 if (option_arg == NULL)
1003 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1005 /* this should be extended to separate options for ro and rw data */
1006 options.ro_base_directory = ro_base_path = option_arg;
1007 options.rw_base_directory = rw_base_path = option_arg;
1008 if (option_arg == next_option)
1011 /* adjust paths for sub-directories in base directory accordingly */
1012 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1013 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1014 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1015 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1016 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1017 options.conf_directory = getPath2(ro_base_path, CONF_DIRECTORY);
1019 else if (strncmp(option, "-levels", option_len) == 0)
1021 if (option_arg == NULL)
1022 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1024 options.level_directory = option_arg;
1025 if (option_arg == next_option)
1028 else if (strncmp(option, "-graphics", option_len) == 0)
1030 if (option_arg == NULL)
1031 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1033 options.graphics_directory = option_arg;
1034 if (option_arg == next_option)
1037 else if (strncmp(option, "-sounds", option_len) == 0)
1039 if (option_arg == NULL)
1040 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1042 options.sounds_directory = option_arg;
1043 if (option_arg == next_option)
1046 else if (strncmp(option, "-music", option_len) == 0)
1048 if (option_arg == NULL)
1049 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1051 options.music_directory = option_arg;
1052 if (option_arg == next_option)
1055 else if (strncmp(option, "-mytapes", option_len) == 0)
1057 options.mytapes = TRUE;
1059 else if (strncmp(option, "-network", option_len) == 0)
1061 options.network = TRUE;
1063 else if (strncmp(option, "-serveronly", option_len) == 0)
1065 options.serveronly = TRUE;
1067 else if (strncmp(option, "-debug", option_len) == 0)
1069 options.debug = TRUE;
1071 else if (strncmp(option, "-verbose", option_len) == 0)
1073 options.verbose = TRUE;
1075 else if (strncmp(option, "-version", option_len) == 0 ||
1076 strncmp(option, "-V", option_len) == 0)
1078 print_version_function();
1082 else if (strPrefix(option, "-D"))
1084 options.special_flags = getStringCopy(&option[2]);
1086 else if (strncmp(option, "-execute", option_len) == 0)
1088 if (option_arg == NULL)
1089 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1091 options.execute_command = option_arg;
1092 if (option_arg == next_option)
1095 /* when doing batch processing, always enable verbose mode (warnings) */
1096 options.verbose = TRUE;
1098 #if defined(PLATFORM_MACOSX)
1099 else if (strPrefix(option, "-psn"))
1101 /* ignore process serial number when launched via GUI on Mac OS X */
1104 else if (*option == '-')
1106 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1108 else if (options.server_host == NULL)
1110 options.server_host = *options_left;
1112 else if (options.server_port == 0)
1114 options.server_port = atoi(*options_left);
1115 if (options.server_port < 1024)
1116 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1119 Error(ERR_EXIT_HELP, "too many arguments");
1126 /* ------------------------------------------------------------------------- */
1127 /* error handling functions */
1128 /* ------------------------------------------------------------------------- */
1130 #define MAX_INTERNAL_ERROR_SIZE 1024
1132 /* used by SetError() and GetError() to store internal error messages */
1133 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1135 void SetError(char *format, ...)
1139 va_start(ap, format);
1140 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1146 return internal_error;
1149 void Error(int mode, char *format, ...)
1151 static boolean last_line_was_separator = FALSE;
1152 char *process_name = "";
1154 if (program.log_file[LOG_ERR_ID] == NULL)
1157 #if defined(PLATFORM_ANDROID)
1158 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1159 mode & ERR_INFO ? ANDROID_LOG_INFO :
1160 mode & ERR_WARN ? ANDROID_LOG_WARN :
1161 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1162 ANDROID_LOG_UNKNOWN);
1165 /* display debug messages only when running in debug mode */
1166 if (mode & ERR_DEBUG && !options.debug)
1169 /* display warnings only when running in verbose mode */
1170 if (mode & ERR_WARN && !options.verbose)
1173 if (mode == ERR_INFO_LINE)
1175 if (!last_line_was_separator)
1176 printf_log_line(format, 79);
1178 last_line_was_separator = TRUE;
1183 last_line_was_separator = FALSE;
1185 if (mode & ERR_SOUND_SERVER)
1186 process_name = " sound server";
1187 else if (mode & ERR_NETWORK_SERVER)
1188 process_name = " network server";
1189 else if (mode & ERR_NETWORK_CLIENT)
1190 process_name = " network client **";
1194 #if !defined(PLATFORM_ANDROID)
1195 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1198 if (mode & ERR_WARN)
1199 printf_log_nonewline("warning: ");
1201 if (mode & ERR_EXIT)
1202 printf_log_nonewline("fatal error: ");
1206 va_start(ap, format);
1207 vprintf_log(format, ap);
1210 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1212 va_start(ap, format);
1213 program.exit_message_function(format, ap);
1218 if (mode & ERR_HELP)
1219 printf_log("%s: Try option '--help' for more information.",
1220 program.command_basename);
1222 if (mode & ERR_EXIT)
1223 printf_log("%s%s: aborting", program.command_basename, process_name);
1225 if (mode & ERR_EXIT)
1227 if (mode & ERR_FROM_SERVER)
1228 exit(1); /* child process: normal exit */
1230 program.exit_function(1); /* main process: clean up stuff */
1235 /* ------------------------------------------------------------------------- */
1236 /* checked memory allocation and freeing functions */
1237 /* ------------------------------------------------------------------------- */
1239 void *checked_malloc(unsigned int size)
1246 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1251 void *checked_calloc(unsigned int size)
1255 ptr = calloc(1, size);
1258 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1263 void *checked_realloc(void *ptr, unsigned int size)
1265 ptr = realloc(ptr, size);
1268 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1273 void checked_free(void *ptr)
1275 if (ptr != NULL) /* this check should be done by free() anyway */
1279 void clear_mem(void *ptr, unsigned int size)
1281 #if defined(PLATFORM_WIN32)
1282 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1283 char *cptr = (char *)ptr;
1288 memset(ptr, 0, size);
1293 /* ------------------------------------------------------------------------- */
1294 /* various helper functions */
1295 /* ------------------------------------------------------------------------- */
1297 void swap_numbers(int *i1, int *i2)
1305 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1317 /* the "put" variants of the following file access functions check for the file
1318 pointer being != NULL and return the number of bytes they have or would have
1319 written; this allows for chunk writing functions to first determine the size
1320 of the (not yet written) chunk, write the correct chunk size and finally
1321 write the chunk itself */
1323 int getFile8BitInteger(File *file)
1325 return getByteFromFile(file);
1328 int putFile8BitInteger(FILE *file, int value)
1336 int getFile16BitInteger(File *file, int byte_order)
1338 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1339 return ((getByteFromFile(file) << 8) |
1340 (getByteFromFile(file) << 0));
1341 else /* BYTE_ORDER_LITTLE_ENDIAN */
1342 return ((getByteFromFile(file) << 0) |
1343 (getByteFromFile(file) << 8));
1346 int putFile16BitInteger(FILE *file, int value, int byte_order)
1350 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1352 fputc((value >> 8) & 0xff, file);
1353 fputc((value >> 0) & 0xff, file);
1355 else /* BYTE_ORDER_LITTLE_ENDIAN */
1357 fputc((value >> 0) & 0xff, file);
1358 fputc((value >> 8) & 0xff, file);
1365 int getFile32BitInteger(File *file, int byte_order)
1367 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1368 return ((getByteFromFile(file) << 24) |
1369 (getByteFromFile(file) << 16) |
1370 (getByteFromFile(file) << 8) |
1371 (getByteFromFile(file) << 0));
1372 else /* BYTE_ORDER_LITTLE_ENDIAN */
1373 return ((getByteFromFile(file) << 0) |
1374 (getByteFromFile(file) << 8) |
1375 (getByteFromFile(file) << 16) |
1376 (getByteFromFile(file) << 24));
1379 int putFile32BitInteger(FILE *file, int value, int byte_order)
1383 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1385 fputc((value >> 24) & 0xff, file);
1386 fputc((value >> 16) & 0xff, file);
1387 fputc((value >> 8) & 0xff, file);
1388 fputc((value >> 0) & 0xff, file);
1390 else /* BYTE_ORDER_LITTLE_ENDIAN */
1392 fputc((value >> 0) & 0xff, file);
1393 fputc((value >> 8) & 0xff, file);
1394 fputc((value >> 16) & 0xff, file);
1395 fputc((value >> 24) & 0xff, file);
1402 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1405 const int chunk_name_length = 4;
1407 /* read chunk name */
1408 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1411 if (chunk_size != NULL)
1413 /* read chunk size */
1414 *chunk_size = getFile32BitInteger(file, byte_order);
1417 return (checkEndOfFile(file) ? FALSE : TRUE);
1420 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1425 /* write chunk name */
1427 fputs(chunk_name, file);
1429 num_bytes += strlen(chunk_name);
1431 if (chunk_size >= 0)
1433 /* write chunk size */
1435 putFile32BitInteger(file, chunk_size, byte_order);
1443 int getFileVersion(File *file)
1445 int version_major = getByteFromFile(file);
1446 int version_minor = getByteFromFile(file);
1447 int version_patch = getByteFromFile(file);
1448 int version_build = getByteFromFile(file);
1450 return VERSION_IDENT(version_major, version_minor, version_patch,
1454 int putFileVersion(FILE *file, int version)
1458 int version_major = VERSION_MAJOR(version);
1459 int version_minor = VERSION_MINOR(version);
1460 int version_patch = VERSION_PATCH(version);
1461 int version_build = VERSION_BUILD(version);
1463 fputc(version_major, file);
1464 fputc(version_minor, file);
1465 fputc(version_patch, file);
1466 fputc(version_build, file);
1472 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1476 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1477 buffer[i] = getByteFromFile(file);
1480 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1484 for(i = 0; i < bytes; i++)
1485 fputc(buffer[i], file);
1488 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1490 while (bytes-- && !checkEndOfFile(file))
1491 getByteFromFile(file);
1494 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1501 /* ------------------------------------------------------------------------- */
1502 /* functions to translate key identifiers between different format */
1503 /* ------------------------------------------------------------------------- */
1505 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1506 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1507 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1508 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1510 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1519 /* normal cursor keys */
1520 { KSYM_Left, "XK_Left", "cursor left" },
1521 { KSYM_Right, "XK_Right", "cursor right" },
1522 { KSYM_Up, "XK_Up", "cursor up" },
1523 { KSYM_Down, "XK_Down", "cursor down" },
1525 /* keypad cursor keys */
1527 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1528 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1529 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1530 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1533 /* other keypad keys */
1534 #ifdef KSYM_KP_Enter
1535 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1536 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1537 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1538 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1539 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1540 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1544 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1545 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1546 { KSYM_Control_L, "XK_Control_L", "left control" },
1547 { KSYM_Control_R, "XK_Control_R", "right control" },
1548 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1549 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1550 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1551 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1552 #if !defined(TARGET_SDL2)
1553 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1554 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1556 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1557 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1559 /* some special keys */
1560 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1561 { KSYM_Delete, "XK_Delete", "delete" },
1562 { KSYM_Insert, "XK_Insert", "insert" },
1563 { KSYM_Tab, "XK_Tab", "tab" },
1564 { KSYM_Home, "XK_Home", "home" },
1565 { KSYM_End, "XK_End", "end" },
1566 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1567 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1569 #if defined(TARGET_SDL2)
1570 { KSYM_Select, "XK_Select", "select" },
1571 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1572 { KSYM_Back, "XK_Back", "back" }, /* back key */
1573 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
1574 #if defined(PLATFORM_ANDROID)
1575 { KSYM_Rewind, "XK_Rewind", "rewind" },
1576 { KSYM_FastForward, "XK_FastForward", "fast forward" },
1580 /* ASCII 0x20 to 0x40 keys (except numbers) */
1581 { KSYM_space, "XK_space", "space" },
1582 { KSYM_exclam, "XK_exclam", "!" },
1583 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1584 { KSYM_numbersign, "XK_numbersign", "#" },
1585 { KSYM_dollar, "XK_dollar", "$" },
1586 { KSYM_percent, "XK_percent", "%" },
1587 { KSYM_ampersand, "XK_ampersand", "&" },
1588 { KSYM_apostrophe, "XK_apostrophe", "'" },
1589 { KSYM_parenleft, "XK_parenleft", "(" },
1590 { KSYM_parenright, "XK_parenright", ")" },
1591 { KSYM_asterisk, "XK_asterisk", "*" },
1592 { KSYM_plus, "XK_plus", "+" },
1593 { KSYM_comma, "XK_comma", "," },
1594 { KSYM_minus, "XK_minus", "-" },
1595 { KSYM_period, "XK_period", "." },
1596 { KSYM_slash, "XK_slash", "/" },
1597 { KSYM_colon, "XK_colon", ":" },
1598 { KSYM_semicolon, "XK_semicolon", ";" },
1599 { KSYM_less, "XK_less", "<" },
1600 { KSYM_equal, "XK_equal", "=" },
1601 { KSYM_greater, "XK_greater", ">" },
1602 { KSYM_question, "XK_question", "?" },
1603 { KSYM_at, "XK_at", "@" },
1605 /* more ASCII keys */
1606 { KSYM_bracketleft, "XK_bracketleft", "[" },
1607 { KSYM_backslash, "XK_backslash", "\\" },
1608 { KSYM_bracketright,"XK_bracketright", "]" },
1609 { KSYM_asciicircum, "XK_asciicircum", "^" },
1610 { KSYM_underscore, "XK_underscore", "_" },
1611 { KSYM_grave, "XK_grave", "grave" },
1612 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1613 { KSYM_braceleft, "XK_braceleft", "brace left" },
1614 { KSYM_bar, "XK_bar", "bar" },
1615 { KSYM_braceright, "XK_braceright", "brace right" },
1616 { KSYM_asciitilde, "XK_asciitilde", "~" },
1618 /* special (non-ASCII) keys */
1619 { KSYM_degree, "XK_degree", "degree" },
1620 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1621 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1622 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1623 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1624 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1625 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1626 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1628 #if defined(TARGET_SDL2)
1629 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1630 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1631 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1632 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1633 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1634 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1635 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1636 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1637 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1639 /* other keys (for reverse mapping only) */
1640 { KSYM_space, "XK_space", " " },
1643 #if defined(TARGET_SDL2)
1644 /* keypad keys are not in numerical order in SDL2 */
1645 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1646 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1647 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1648 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1649 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1650 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1651 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1652 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1653 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1654 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1657 /* end-of-array identifier */
1663 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1665 static char name_buffer[30];
1668 if (key >= KSYM_A && key <= KSYM_Z)
1669 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1670 else if (key >= KSYM_a && key <= KSYM_z)
1671 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1672 else if (key >= KSYM_0 && key <= KSYM_9)
1673 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1674 #if !defined(TARGET_SDL2)
1675 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1676 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1678 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1679 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1680 else if (key == KSYM_UNDEFINED)
1681 strcpy(name_buffer, "(undefined)");
1688 if (key == translate_key[i].key)
1690 strcpy(name_buffer, translate_key[i].name);
1694 while (translate_key[++i].name);
1696 if (!translate_key[i].name)
1697 strcpy(name_buffer, "(unknown)");
1700 *name = name_buffer;
1702 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1704 static char name_buffer[30];
1707 if (key >= KSYM_A && key <= KSYM_Z)
1708 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1709 else if (key >= KSYM_a && key <= KSYM_z)
1710 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1711 else if (key >= KSYM_0 && key <= KSYM_9)
1712 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1713 #if !defined(TARGET_SDL2)
1714 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1715 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1717 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1718 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1719 else if (key == KSYM_UNDEFINED)
1720 strcpy(name_buffer, "[undefined]");
1727 if (key == translate_key[i].key)
1729 strcpy(name_buffer, translate_key[i].x11name);
1733 while (translate_key[++i].x11name);
1735 if (!translate_key[i].x11name)
1736 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1739 *x11name = name_buffer;
1741 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1743 Key key = KSYM_UNDEFINED;
1744 char *name_ptr = *name;
1746 if (strlen(*name) == 1)
1748 char c = name_ptr[0];
1750 if (c >= 'A' && c <= 'Z')
1751 key = KSYM_A + (Key)(c - 'A');
1752 else if (c >= 'a' && c <= 'z')
1753 key = KSYM_a + (Key)(c - 'a');
1754 else if (c >= '0' && c <= '9')
1755 key = KSYM_0 + (Key)(c - '0');
1758 if (key == KSYM_UNDEFINED)
1764 if (strEqual(translate_key[i].name, *name))
1766 key = translate_key[i].key;
1770 while (translate_key[++i].x11name);
1773 if (key == KSYM_UNDEFINED)
1774 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1778 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1780 Key key = KSYM_UNDEFINED;
1781 char *name_ptr = *x11name;
1783 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1785 char c = name_ptr[3];
1787 if (c >= 'A' && c <= 'Z')
1788 key = KSYM_A + (Key)(c - 'A');
1789 else if (c >= 'a' && c <= 'z')
1790 key = KSYM_a + (Key)(c - 'a');
1791 else if (c >= '0' && c <= '9')
1792 key = KSYM_0 + (Key)(c - '0');
1794 #if !defined(TARGET_SDL2)
1795 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1797 char c = name_ptr[6];
1799 if (c >= '0' && c <= '9')
1800 key = KSYM_KP_0 + (Key)(c - '0');
1803 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1805 char c1 = name_ptr[4];
1806 char c2 = name_ptr[5];
1809 if ((c1 >= '0' && c1 <= '9') &&
1810 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1811 d = atoi(&name_ptr[4]);
1813 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1814 key = KSYM_F1 + (Key)(d - 1);
1816 else if (strPrefix(name_ptr, "XK_"))
1822 if (strEqual(name_ptr, translate_key[i].x11name))
1824 key = translate_key[i].key;
1828 while (translate_key[++i].x11name);
1830 else if (strPrefix(name_ptr, "0x"))
1832 unsigned int value = 0;
1838 char c = *name_ptr++;
1841 if (c >= '0' && c <= '9')
1843 else if (c >= 'a' && c <= 'f')
1844 d = (int)(c - 'a' + 10);
1845 else if (c >= 'A' && c <= 'F')
1846 d = (int)(c - 'A' + 10);
1854 value = value * 16 + d;
1865 char *getKeyNameFromKey(Key key)
1869 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1873 char *getX11KeyNameFromKey(Key key)
1877 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1881 Key getKeyFromKeyName(char *name)
1885 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1889 Key getKeyFromX11KeyName(char *x11name)
1893 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1897 char getCharFromKey(Key key)
1903 } translate_key_char[] =
1905 /* special (non-ASCII) keys (ISO-8859-1) */
1906 { KSYM_degree, CHAR_BYTE_DEGREE },
1907 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1908 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1909 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1910 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1911 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1912 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1913 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1915 /* end-of-array identifier */
1919 char *keyname = getKeyNameFromKey(key);
1922 if (strlen(keyname) == 1)
1924 else if (strEqual(keyname, "space"))
1932 if (key == translate_key_char[i].key)
1934 c = translate_key_char[i].key_char;
1939 while (translate_key_char[++i].key_char);
1945 char getValidConfigValueChar(char c)
1947 if (c == '#' || /* used to mark comments */
1948 c == '\\') /* used to mark continued lines */
1955 /* ------------------------------------------------------------------------- */
1956 /* functions to translate string identifiers to integer or boolean value */
1957 /* ------------------------------------------------------------------------- */
1959 int get_integer_from_string(char *s)
1961 static char *number_text[][3] =
1963 { "0", "zero", "null", },
1964 { "1", "one", "first" },
1965 { "2", "two", "second" },
1966 { "3", "three", "third" },
1967 { "4", "four", "fourth" },
1968 { "5", "five", "fifth" },
1969 { "6", "six", "sixth" },
1970 { "7", "seven", "seventh" },
1971 { "8", "eight", "eighth" },
1972 { "9", "nine", "ninth" },
1973 { "10", "ten", "tenth" },
1974 { "11", "eleven", "eleventh" },
1975 { "12", "twelve", "twelfth" },
1977 { NULL, NULL, NULL },
1981 char *s_lower = getStringToLower(s);
1984 for (i = 0; number_text[i][0] != NULL; i++)
1985 for (j = 0; j < 3; j++)
1986 if (strEqual(s_lower, number_text[i][j]))
1991 if (strEqual(s_lower, "false") ||
1992 strEqual(s_lower, "no") ||
1993 strEqual(s_lower, "off"))
1995 else if (strEqual(s_lower, "true") ||
1996 strEqual(s_lower, "yes") ||
1997 strEqual(s_lower, "on"))
2008 boolean get_boolean_from_string(char *s)
2010 char *s_lower = getStringToLower(s);
2011 boolean result = FALSE;
2013 if (strEqual(s_lower, "true") ||
2014 strEqual(s_lower, "yes") ||
2015 strEqual(s_lower, "on") ||
2016 get_integer_from_string(s) == 1)
2024 int get_switch3_from_string(char *s)
2026 char *s_lower = getStringToLower(s);
2029 if (strEqual(s_lower, "true") ||
2030 strEqual(s_lower, "yes") ||
2031 strEqual(s_lower, "on") ||
2032 get_integer_from_string(s) == 1)
2034 else if (strEqual(s_lower, "auto"))
2043 /* ------------------------------------------------------------------------- */
2044 /* functions for generic lists */
2045 /* ------------------------------------------------------------------------- */
2047 ListNode *newListNode()
2049 return checked_calloc(sizeof(ListNode));
2052 void addNodeToList(ListNode **node_first, char *key, void *content)
2054 ListNode *node_new = newListNode();
2056 node_new->key = getStringCopy(key);
2057 node_new->content = content;
2058 node_new->next = *node_first;
2061 (*node_first)->prev = node_new;
2063 *node_first = node_new;
2066 void deleteNodeFromList(ListNode **node_first, char *key,
2067 void (*destructor_function)(void *))
2069 if (node_first == NULL || *node_first == NULL)
2072 if (strEqual((*node_first)->key, key))
2074 // after first recursion, (*node_first)->prev->next == *node_first,
2075 // so *node_first would be overwritten with (*node_first)->next
2076 // => use a copy of *node_first (and later of (*node_first)->next)
2077 ListNode *node = *node_first;
2078 ListNode *node_next = node->next;
2080 checked_free(node->key);
2082 if (destructor_function)
2083 destructor_function(node->content);
2086 node->prev->next = node->next;
2089 node->next->prev = node->prev;
2093 // after removing node, set list pointer to next valid list node
2094 // (this is important if the first node of the list was deleted)
2095 *node_first = node_next;
2099 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2103 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2105 if (node_first == NULL)
2108 if (strEqual(node_first->key, key))
2111 return getNodeFromKey(node_first->next, key);
2114 int getNumNodes(ListNode *node_first)
2116 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2119 void dumpList(ListNode *node_first)
2121 ListNode *node = node_first;
2125 printf("['%s' (%d)]\n", node->key,
2126 ((struct ListNodeInfo *)node->content)->num_references);
2130 printf("[%d nodes]\n", getNumNodes(node_first));
2134 /* ------------------------------------------------------------------------- */
2135 /* functions for file handling */
2136 /* ------------------------------------------------------------------------- */
2138 File *openFile(char *filename, char *mode)
2140 File *file = checked_calloc(sizeof(File));
2142 file->file = fopen(filename, mode);
2144 if (file->file != NULL)
2146 file->filename = getStringCopy(filename);
2151 #if defined(PLATFORM_ANDROID)
2152 file->asset_file = SDL_RWFromFile(filename, mode);
2154 if (file->asset_file != NULL)
2156 file->file_is_asset = TRUE;
2157 file->filename = getStringCopy(filename);
2168 int closeFile(File *file)
2175 #if defined(PLATFORM_ANDROID)
2176 if (file->asset_file)
2177 result = SDL_RWclose(file->asset_file);
2181 result = fclose(file->file);
2183 checked_free(file->filename);
2189 int checkEndOfFile(File *file)
2191 #if defined(PLATFORM_ANDROID)
2192 if (file->file_is_asset)
2193 return file->end_of_file;
2196 return feof(file->file);
2199 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2201 #if defined(PLATFORM_ANDROID)
2202 if (file->file_is_asset)
2204 if (file->end_of_file)
2207 size_t num_items_read =
2208 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2210 if (num_items_read < num_items)
2211 file->end_of_file = TRUE;
2213 return num_items_read;
2217 return fread(buffer, item_size, num_items, file->file);
2220 int seekFile(File *file, long offset, int whence)
2222 #if defined(PLATFORM_ANDROID)
2223 if (file->file_is_asset)
2225 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2226 whence == SEEK_CUR ? RW_SEEK_CUR :
2227 whence == SEEK_END ? RW_SEEK_END : 0);
2229 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2233 return fseek(file->file, offset, whence);
2236 int getByteFromFile(File *file)
2238 #if defined(PLATFORM_ANDROID)
2239 if (file->file_is_asset)
2241 if (file->end_of_file)
2245 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2247 if (num_bytes_read < 1)
2248 file->end_of_file = TRUE;
2250 return (file->end_of_file ? EOF : (int)c);
2254 return fgetc(file->file);
2257 char *getStringFromFile(File *file, char *line, int size)
2259 #if defined(PLATFORM_ANDROID)
2260 if (file->file_is_asset)
2262 if (file->end_of_file)
2265 char *line_ptr = line;
2266 int num_bytes_read = 0;
2268 while (num_bytes_read < size - 1 &&
2269 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2270 *line_ptr++ != '\n')
2275 if (strlen(line) == 0)
2277 file->end_of_file = TRUE;
2286 return fgets(line, size, file->file);
2290 /* ------------------------------------------------------------------------- */
2291 /* functions for directory handling */
2292 /* ------------------------------------------------------------------------- */
2294 Directory *openDirectory(char *dir_name)
2296 Directory *dir = checked_calloc(sizeof(Directory));
2298 dir->dir = opendir(dir_name);
2300 if (dir->dir != NULL)
2302 dir->filename = getStringCopy(dir_name);
2307 #if defined(PLATFORM_ANDROID)
2308 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2310 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2312 checked_free(asset_toc_filename);
2314 if (dir->asset_toc_file != NULL)
2316 dir->directory_is_asset = TRUE;
2317 dir->filename = getStringCopy(dir_name);
2328 int closeDirectory(Directory *dir)
2335 #if defined(PLATFORM_ANDROID)
2336 if (dir->asset_toc_file)
2337 result = SDL_RWclose(dir->asset_toc_file);
2341 result = closedir(dir->dir);
2344 freeDirectoryEntry(dir->dir_entry);
2346 checked_free(dir->filename);
2352 DirectoryEntry *readDirectory(Directory *dir)
2355 freeDirectoryEntry(dir->dir_entry);
2357 dir->dir_entry = NULL;
2359 #if defined(PLATFORM_ANDROID)
2360 if (dir->directory_is_asset)
2362 char line[MAX_LINE_LEN];
2363 char *line_ptr = line;
2364 int num_bytes_read = 0;
2366 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2367 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2376 if (strlen(line) == 0)
2379 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2381 dir->dir_entry->is_directory = FALSE;
2382 if (line[strlen(line) - 1] == '/')
2384 dir->dir_entry->is_directory = TRUE;
2386 line[strlen(line) - 1] = '\0';
2389 dir->dir_entry->basename = getStringCopy(line);
2390 dir->dir_entry->filename = getPath2(dir->filename, line);
2392 return dir->dir_entry;
2396 struct dirent *dir_entry = readdir(dir->dir);
2398 if (dir_entry == NULL)
2401 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2403 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2404 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2406 struct stat file_status;
2408 dir->dir_entry->is_directory =
2409 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2410 S_ISDIR(file_status.st_mode));
2412 return dir->dir_entry;
2415 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2417 if (dir_entry == NULL)
2420 checked_free(dir_entry->basename);
2421 checked_free(dir_entry->filename);
2422 checked_free(dir_entry);
2426 /* ------------------------------------------------------------------------- */
2427 /* functions for checking files and filenames */
2428 /* ------------------------------------------------------------------------- */
2430 boolean directoryExists(char *dir_name)
2432 if (dir_name == NULL)
2435 struct stat file_status;
2436 boolean success = (stat(dir_name, &file_status) == 0 &&
2437 S_ISDIR(file_status.st_mode));
2439 #if defined(PLATFORM_ANDROID)
2442 // this might be an asset directory; check by trying to open toc file
2443 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2444 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2446 checked_free(asset_toc_filename);
2448 success = (file != NULL);
2458 boolean fileExists(char *filename)
2460 if (filename == NULL)
2463 boolean success = (access(filename, F_OK) == 0);
2465 #if defined(PLATFORM_ANDROID)
2468 // this might be an asset file; check by trying to open it
2469 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2471 success = (file != NULL);
2481 boolean fileHasPrefix(char *basename, char *prefix)
2483 static char *basename_lower = NULL;
2484 int basename_length, prefix_length;
2486 checked_free(basename_lower);
2488 if (basename == NULL || prefix == NULL)
2491 basename_lower = getStringToLower(basename);
2492 basename_length = strlen(basename_lower);
2493 prefix_length = strlen(prefix);
2495 if (basename_length > prefix_length + 1 &&
2496 basename_lower[prefix_length] == '.' &&
2497 strncmp(basename_lower, prefix, prefix_length) == 0)
2503 boolean fileHasSuffix(char *basename, char *suffix)
2505 static char *basename_lower = NULL;
2506 int basename_length, suffix_length;
2508 checked_free(basename_lower);
2510 if (basename == NULL || suffix == NULL)
2513 basename_lower = getStringToLower(basename);
2514 basename_length = strlen(basename_lower);
2515 suffix_length = strlen(suffix);
2517 if (basename_length > suffix_length + 1 &&
2518 basename_lower[basename_length - suffix_length - 1] == '.' &&
2519 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2525 static boolean FileCouldBeArtwork(char *filename)
2527 char *basename = getBaseNamePtr(filename);
2529 return (!strEqual(basename, ".") &&
2530 !strEqual(basename, "..") &&
2531 !fileHasSuffix(basename, "txt") &&
2532 !fileHasSuffix(basename, "conf") &&
2533 !directoryExists(filename));
2536 boolean FileIsGraphic(char *filename)
2538 return FileCouldBeArtwork(filename);
2541 boolean FileIsSound(char *filename)
2543 return FileCouldBeArtwork(filename);
2546 boolean FileIsMusic(char *filename)
2548 return FileCouldBeArtwork(filename);
2551 boolean FileIsArtworkType(char *filename, int type)
2553 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2554 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2555 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2561 /* ------------------------------------------------------------------------- */
2562 /* functions for loading artwork configuration information */
2563 /* ------------------------------------------------------------------------- */
2565 char *get_mapped_token(char *token)
2567 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2568 static char *map_token_prefix[][2] =
2570 { "char_procent", "char_percent" },
2575 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2577 int len_token_prefix = strlen(map_token_prefix[i][0]);
2579 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2580 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2583 // change tokens containing ".gfx" by moving the "gfx" part to the very left
2584 char *gfx_substring = ".gfx";
2585 char *gfx_prefix = "gfx.";
2586 if (strstr(token, gfx_substring) != NULL)
2588 char *token_prefix = getStringCopy(token);
2589 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
2590 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
2593 // cut off token string at ".gfx" substring position
2594 *token_gfx_pos = '\0';
2596 // put together prefix "gfx." and token prefix and suffix without ".gfx"
2597 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
2601 return mapped_token;
2607 char *get_special_base_token(struct ArtworkListInfo *artwork_info, char *token)
2609 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2610 static struct ConfigTypeInfo prefix_list[] =
2612 { "global.anim_1" },
2613 { "global.anim_2" },
2614 { "global.anim_3" },
2615 { "global.anim_4" },
2616 { "global.anim_5" },
2617 { "global.anim_6" },
2618 { "global.anim_7" },
2619 { "global.anim_8" },
2620 { "global.anim_9" },
2621 { "global.anim_10" },
2622 { "global.anim_11" },
2623 { "global.anim_12" },
2624 { "global.anim_13" },
2625 { "global.anim_14" },
2626 { "global.anim_15" },
2627 { "global.anim_16" },
2628 { "global.anim_17" },
2629 { "global.anim_18" },
2630 { "global.anim_19" },
2631 { "global.anim_20" },
2632 { "global.anim_21" },
2633 { "global.anim_22" },
2634 { "global.anim_23" },
2635 { "global.anim_24" },
2636 { "global.anim_25" },
2637 { "global.anim_26" },
2638 { "global.anim_27" },
2639 { "global.anim_28" },
2640 { "global.anim_29" },
2641 { "global.anim_30" },
2642 { "global.anim_31" },
2643 { "global.anim_32" },
2647 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2648 boolean prefix_found = FALSE;
2652 /* search for prefix to check if base token has to be created */
2653 for (i = 0; prefix_list[i].token != NULL; i++)
2654 if (strPrefix(token, prefix_list[i].token))
2655 prefix_found = TRUE;
2660 /* search for suffix (parameter) to determine base token length */
2661 for (i = 0; suffix_list[i].token != NULL; i++)
2662 if (strSuffix(token, suffix_list[i].token))
2663 len_suffix = strlen(suffix_list[i].token);
2665 return getStringCopyN(token, strlen(token) - len_suffix);
2668 /* This function checks if a string <s> of the format "string1, string2, ..."
2669 exactly contains a string <s_contained>. */
2671 static boolean string_has_parameter(char *s, char *s_contained)
2675 if (s == NULL || s_contained == NULL)
2678 if (strlen(s_contained) > strlen(s))
2681 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2683 char next_char = s[strlen(s_contained)];
2685 /* check if next character is delimiter or whitespace */
2686 return (next_char == ',' || next_char == '\0' ||
2687 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2690 /* check if string contains another parameter string after a comma */
2691 substring = strchr(s, ',');
2692 if (substring == NULL) /* string does not contain a comma */
2695 /* advance string pointer to next character after the comma */
2698 /* skip potential whitespaces after the comma */
2699 while (*substring == ' ' || *substring == '\t')
2702 return string_has_parameter(substring, s_contained);
2705 int get_anim_parameter_value(char *s)
2707 char *pattern_1 = "click:anim_";
2708 char *pattern_2 = ".part_";
2709 char *matching_char = NULL;
2711 int result = ANIM_EVENT_NONE;
2713 matching_char = strstr(s_ptr, pattern_1);
2714 if (matching_char == NULL)
2715 return ANIM_EVENT_NONE;
2717 s_ptr = matching_char + strlen(pattern_1);
2719 // check for main animation number ("anim_X" or "anim_XX")
2720 if (*s_ptr >= '0' && *s_ptr <= '9')
2722 int gic_anim_nr = (*s_ptr++ - '0');
2724 if (*s_ptr >= '0' && *s_ptr <= '9')
2725 gic_anim_nr = 10 * gic_anim_nr + (*s_ptr++ - '0');
2727 if (gic_anim_nr < 1 || gic_anim_nr > MAX_GLOBAL_ANIMS)
2728 return ANIM_EVENT_NONE;
2730 result |= gic_anim_nr << ANIM_EVENT_ANIM_BIT;
2734 // invalid main animation number specified
2736 return ANIM_EVENT_NONE;
2739 // check for animation part number ("part_X" or "part_XX") (optional)
2740 if (strPrefix(s_ptr, pattern_2))
2742 s_ptr += strlen(pattern_2);
2744 if (*s_ptr >= '0' && *s_ptr <= '9')
2746 int gic_part_nr = (*s_ptr++ - '0');
2748 if (*s_ptr >= '0' && *s_ptr <= '9')
2749 gic_part_nr = 10 * gic_part_nr + (*s_ptr++ - '0');
2751 if (gic_part_nr < 1 || gic_part_nr > MAX_GLOBAL_ANIM_PARTS)
2752 return ANIM_EVENT_NONE;
2754 result |= gic_part_nr << ANIM_EVENT_PART_BIT;
2758 // invalid animation part number specified
2760 return ANIM_EVENT_NONE;
2764 /* discard result if next character is neither delimiter nor whitespace */
2765 if (!(*s_ptr == ',' || *s_ptr == '\0' ||
2766 *s_ptr == ' ' || *s_ptr == '\t'))
2767 return ANIM_EVENT_NONE;
2772 int get_parameter_value(char *value_raw, char *suffix, int type)
2774 char *value = getStringToLower(value_raw);
2775 int result = 0; /* probably a save default value */
2777 if (strEqual(suffix, ".direction"))
2779 result = (strEqual(value, "left") ? MV_LEFT :
2780 strEqual(value, "right") ? MV_RIGHT :
2781 strEqual(value, "up") ? MV_UP :
2782 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2784 else if (strEqual(suffix, ".position"))
2786 result = (strEqual(value, "left") ? POS_LEFT :
2787 strEqual(value, "right") ? POS_RIGHT :
2788 strEqual(value, "top") ? POS_TOP :
2789 strEqual(value, "upper") ? POS_UPPER :
2790 strEqual(value, "middle") ? POS_MIDDLE :
2791 strEqual(value, "lower") ? POS_LOWER :
2792 strEqual(value, "bottom") ? POS_BOTTOM :
2793 strEqual(value, "any") ? POS_ANY :
2794 strEqual(value, "last") ? POS_LAST : POS_UNDEFINED);
2796 else if (strEqual(suffix, ".align"))
2798 result = (strEqual(value, "left") ? ALIGN_LEFT :
2799 strEqual(value, "right") ? ALIGN_RIGHT :
2800 strEqual(value, "center") ? ALIGN_CENTER :
2801 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2803 else if (strEqual(suffix, ".valign"))
2805 result = (strEqual(value, "top") ? VALIGN_TOP :
2806 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2807 strEqual(value, "middle") ? VALIGN_MIDDLE :
2808 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2810 else if (strEqual(suffix, ".anim_mode"))
2812 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2813 string_has_parameter(value, "loop") ? ANIM_LOOP :
2814 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2815 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2816 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2817 string_has_parameter(value, "random") ? ANIM_RANDOM :
2818 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2819 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2820 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2821 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2822 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2823 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2824 string_has_parameter(value, "all") ? ANIM_ALL :
2827 if (string_has_parameter(value, "once"))
2828 result |= ANIM_ONCE;
2830 if (string_has_parameter(value, "reverse"))
2831 result |= ANIM_REVERSE;
2833 if (string_has_parameter(value, "opaque_player"))
2834 result |= ANIM_OPAQUE_PLAYER;
2836 if (string_has_parameter(value, "static_panel"))
2837 result |= ANIM_STATIC_PANEL;
2839 else if (strEqual(suffix, ".init_event") ||
2840 strEqual(suffix, ".anim_event"))
2842 result = ANIM_EVENT_DEFAULT;
2844 if (string_has_parameter(value, "any"))
2845 result |= ANIM_EVENT_ANY;
2847 if (string_has_parameter(value, "click"))
2848 result |= ANIM_EVENT_SELF;
2850 // add optional "click:anim_X" or "click:anim_X.part_X" parameter
2851 result |= get_anim_parameter_value(value);
2853 else if (strEqual(suffix, ".class"))
2855 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2856 get_hash_from_key(value));
2858 else if (strEqual(suffix, ".style"))
2860 result = STYLE_DEFAULT;
2862 if (string_has_parameter(value, "accurate_borders"))
2863 result |= STYLE_ACCURATE_BORDERS;
2865 if (string_has_parameter(value, "inner_corners"))
2866 result |= STYLE_INNER_CORNERS;
2868 if (string_has_parameter(value, "reverse"))
2869 result |= STYLE_REVERSE;
2871 else if (strEqual(suffix, ".fade_mode"))
2873 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2874 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2875 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2876 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2877 string_has_parameter(value, "curtain") ? FADE_MODE_CURTAIN :
2880 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2882 result = gfx.get_font_from_token_function(value);
2884 else /* generic parameter of type integer or boolean */
2886 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2887 type == TYPE_INTEGER ? get_integer_from_string(value) :
2888 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2889 ARG_UNDEFINED_VALUE);
2897 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2898 struct ListNodeInfo ***, int *);
2900 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2901 struct ConfigTypeInfo *suffix_list,
2902 char **ignore_tokens,
2903 int num_file_list_entries)
2905 SetupFileHash *ignore_tokens_hash;
2906 struct FileInfo *file_list;
2907 int num_file_list_entries_found = 0;
2908 int num_suffix_list_entries = 0;
2912 /* create hash from list of tokens to be ignored (for quick access) */
2913 ignore_tokens_hash = newSetupFileHash();
2914 for (i = 0; ignore_tokens[i] != NULL; i++)
2915 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
2917 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2919 for (i = 0; suffix_list[i].token != NULL; i++)
2920 num_suffix_list_entries++;
2922 /* always start with reliable default values */
2923 for (i = 0; i < num_file_list_entries; i++)
2925 file_list[i].token = NULL;
2927 file_list[i].default_filename = NULL;
2928 file_list[i].filename = NULL;
2930 if (num_suffix_list_entries > 0)
2932 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2934 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2935 file_list[i].parameter = checked_calloc(parameter_array_size);
2937 for (j = 0; j < num_suffix_list_entries; j++)
2939 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2940 setString(&file_list[i].parameter[j], suffix_list[j].value);
2943 file_list[i].redefined = FALSE;
2944 file_list[i].fallback_to_default = FALSE;
2945 file_list[i].default_is_cloned = FALSE;
2951 for (i = 0; config_list[i].token != NULL; i++)
2953 int len_config_token = strlen(config_list[i].token);
2954 boolean is_file_entry = TRUE;
2956 for (j = 0; suffix_list[j].token != NULL; j++)
2958 int len_suffix = strlen(suffix_list[j].token);
2960 if (len_suffix < len_config_token &&
2961 strEqual(&config_list[i].token[len_config_token - len_suffix],
2962 suffix_list[j].token))
2964 setString(&file_list[list_pos].default_parameter[j],
2965 config_list[i].value);
2967 is_file_entry = FALSE;
2973 /* the following tokens are no file definitions, but other config tokens */
2974 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
2975 is_file_entry = FALSE;
2982 if (list_pos >= num_file_list_entries)
2985 file_list[list_pos].token = config_list[i].token;
2986 file_list[list_pos].default_filename = config_list[i].value;
2989 if (strSuffix(config_list[i].token, ".clone_from"))
2990 file_list[list_pos].default_is_cloned = TRUE;
2993 num_file_list_entries_found = list_pos + 1;
2994 if (num_file_list_entries_found != num_file_list_entries)
2996 Error(ERR_INFO_LINE, "-");
2997 Error(ERR_INFO, "inconsistant config list information:");
2998 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2999 num_file_list_entries);
3000 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
3001 num_file_list_entries_found);
3002 Error(ERR_EXIT, "please fix");
3005 freeSetupFileHash(ignore_tokens_hash);
3010 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3012 int len_token = strlen(token);
3013 int len_suffix = strlen(suffix);
3015 if (start_pos < 0) /* compare suffix from end of string */
3016 start_pos += len_token;
3018 if (start_pos < 0 || start_pos + len_suffix > len_token)
3021 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3024 if (token[start_pos + len_suffix] == '\0')
3027 if (token[start_pos + len_suffix] == '.')
3033 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3035 static void read_token_parameters(SetupFileHash *setup_file_hash,
3036 struct ConfigTypeInfo *suffix_list,
3037 struct FileInfo *file_list_entry)
3039 /* check for config token that is the base token without any suffixes */
3040 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3041 char *known_token_value = KNOWN_TOKEN_VALUE;
3044 if (filename != NULL)
3046 setString(&file_list_entry->filename, filename);
3048 /* when file definition found, set all parameters to default values */
3049 for (i = 0; suffix_list[i].token != NULL; i++)
3050 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3052 file_list_entry->redefined = TRUE;
3054 /* mark config file token as well known from default config */
3055 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3058 /* check for config tokens that can be build by base token and suffixes */
3059 for (i = 0; suffix_list[i].token != NULL; i++)
3061 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3062 char *value = getHashEntry(setup_file_hash, token);
3066 setString(&file_list_entry->parameter[i], value);
3068 /* mark config file token as well known from default config */
3069 setHashEntry(setup_file_hash, token, known_token_value);
3076 static void add_dynamic_file_list_entry(struct FileInfo **list,
3077 int *num_list_entries,
3078 SetupFileHash *extra_file_hash,
3079 struct ConfigTypeInfo *suffix_list,
3080 int num_suffix_list_entries,
3083 struct FileInfo *new_list_entry;
3084 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3086 (*num_list_entries)++;
3087 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3088 new_list_entry = &(*list)[*num_list_entries - 1];
3090 new_list_entry->token = getStringCopy(token);
3091 new_list_entry->default_filename = NULL;
3092 new_list_entry->filename = NULL;
3093 new_list_entry->parameter = checked_calloc(parameter_array_size);
3095 new_list_entry->redefined = FALSE;
3096 new_list_entry->fallback_to_default = FALSE;
3097 new_list_entry->default_is_cloned = FALSE;
3099 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3102 static void add_property_mapping(struct PropertyMapping **list,
3103 int *num_list_entries,
3104 int base_index, int ext1_index,
3105 int ext2_index, int ext3_index,
3108 struct PropertyMapping *new_list_entry;
3110 (*num_list_entries)++;
3111 *list = checked_realloc(*list,
3112 *num_list_entries * sizeof(struct PropertyMapping));
3113 new_list_entry = &(*list)[*num_list_entries - 1];
3115 new_list_entry->base_index = base_index;
3116 new_list_entry->ext1_index = ext1_index;
3117 new_list_entry->ext2_index = ext2_index;
3118 new_list_entry->ext3_index = ext3_index;
3120 new_list_entry->artwork_index = artwork_index;
3123 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3126 struct FileInfo *file_list = artwork_info->file_list;
3127 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3128 char **base_prefixes = artwork_info->base_prefixes;
3129 char **ext1_suffixes = artwork_info->ext1_suffixes;
3130 char **ext2_suffixes = artwork_info->ext2_suffixes;
3131 char **ext3_suffixes = artwork_info->ext3_suffixes;
3132 char **ignore_tokens = artwork_info->ignore_tokens;
3133 int num_file_list_entries = artwork_info->num_file_list_entries;
3134 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3135 int num_base_prefixes = artwork_info->num_base_prefixes;
3136 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3137 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3138 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3139 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3140 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3141 SetupFileHash *extra_file_hash, *empty_file_hash;
3142 char *known_token_value = KNOWN_TOKEN_VALUE;
3143 char *base_token_value = UNDEFINED_FILENAME;
3146 if (filename == NULL)
3149 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3152 /* separate valid (defined) from empty (undefined) config token values */
3153 valid_file_hash = newSetupFileHash();
3154 empty_file_hash = newSetupFileHash();
3155 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3157 char *value = HASH_ITERATION_VALUE(itr);
3159 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3160 HASH_ITERATION_TOKEN(itr), value);
3162 END_HASH_ITERATION(setup_file_hash, itr)
3164 /* at this point, we do not need the setup file hash anymore -- free it */
3165 freeSetupFileHash(setup_file_hash);
3167 /* prevent changing hash while iterating over it by using a temporary copy */
3168 valid_file_hash_tmp = newSetupFileHash();
3169 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3171 setHashEntry(valid_file_hash_tmp,
3172 HASH_ITERATION_TOKEN(itr),
3173 HASH_ITERATION_VALUE(itr));
3175 END_HASH_ITERATION(valid_file_hash, itr)
3177 /* (iterate over same temporary hash, as modifications are independent) */
3179 /* map deprecated to current tokens (using prefix match and replace) */
3180 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3182 char *token = HASH_ITERATION_TOKEN(itr);
3183 char *mapped_token = get_mapped_token(token);
3185 if (mapped_token != NULL)
3187 char *value = HASH_ITERATION_VALUE(itr);
3189 /* add mapped token */
3190 setHashEntry(valid_file_hash, mapped_token, value);
3192 /* ignore old token (by setting it to "known" keyword) */
3193 setHashEntry(valid_file_hash, token, known_token_value);
3198 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3200 /* add special base tokens (using prefix match and replace) */
3201 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3203 char *token = HASH_ITERATION_TOKEN(itr);
3204 char *base_token = get_special_base_token(artwork_info, token);
3206 if (base_token != NULL)
3208 /* add base token only if it does not already exist */
3209 if (getHashEntry(valid_file_hash, base_token) == NULL)
3210 setHashEntry(valid_file_hash, base_token, base_token_value);
3215 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3217 /* free temporary hash used for iteration */
3218 freeSetupFileHash(valid_file_hash_tmp);
3220 /* read parameters for all known config file tokens */
3221 for (i = 0; i < num_file_list_entries; i++)
3222 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3224 /* set all tokens that can be ignored here to "known" keyword */
3225 for (i = 0; i < num_ignore_tokens; i++)
3226 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3228 /* copy all unknown config file tokens to extra config hash */
3229 extra_file_hash = newSetupFileHash();
3230 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3232 char *value = HASH_ITERATION_VALUE(itr);
3234 if (!strEqual(value, known_token_value))
3235 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3237 END_HASH_ITERATION(valid_file_hash, itr)
3239 /* at this point, we do not need the valid file hash anymore -- free it */
3240 freeSetupFileHash(valid_file_hash);
3242 /* now try to determine valid, dynamically defined config tokens */
3244 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3246 struct FileInfo **dynamic_file_list =
3247 &artwork_info->dynamic_file_list;
3248 int *num_dynamic_file_list_entries =
3249 &artwork_info->num_dynamic_file_list_entries;
3250 struct PropertyMapping **property_mapping =
3251 &artwork_info->property_mapping;
3252 int *num_property_mapping_entries =
3253 &artwork_info->num_property_mapping_entries;
3254 int current_summarized_file_list_entry =
3255 artwork_info->num_file_list_entries +
3256 artwork_info->num_dynamic_file_list_entries;
3257 char *token = HASH_ITERATION_TOKEN(itr);
3258 int len_token = strlen(token);
3260 boolean base_prefix_found = FALSE;
3261 boolean parameter_suffix_found = FALSE;
3263 /* skip all parameter definitions (handled by read_token_parameters()) */
3264 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3266 int len_suffix = strlen(suffix_list[i].token);
3268 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3269 parameter_suffix_found = TRUE;
3272 if (parameter_suffix_found)
3275 /* ---------- step 0: search for matching base prefix ---------- */
3278 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3280 char *base_prefix = base_prefixes[i];
3281 int len_base_prefix = strlen(base_prefix);
3282 boolean ext1_suffix_found = FALSE;
3283 boolean ext2_suffix_found = FALSE;
3284 boolean ext3_suffix_found = FALSE;
3285 boolean exact_match = FALSE;
3286 int base_index = -1;
3287 int ext1_index = -1;
3288 int ext2_index = -1;
3289 int ext3_index = -1;
3291 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3293 if (!base_prefix_found)
3298 if (start_pos + len_base_prefix == len_token) /* exact match */
3302 add_dynamic_file_list_entry(dynamic_file_list,
3303 num_dynamic_file_list_entries,
3306 num_suffix_list_entries,
3308 add_property_mapping(property_mapping,
3309 num_property_mapping_entries,
3310 base_index, -1, -1, -1,
3311 current_summarized_file_list_entry);
3315 /* ---------- step 1: search for matching first suffix ---------- */
3317 start_pos += len_base_prefix;
3318 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3320 char *ext1_suffix = ext1_suffixes[j];
3321 int len_ext1_suffix = strlen(ext1_suffix);
3323 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3325 if (!ext1_suffix_found)
3330 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3334 add_dynamic_file_list_entry(dynamic_file_list,
3335 num_dynamic_file_list_entries,
3338 num_suffix_list_entries,
3340 add_property_mapping(property_mapping,
3341 num_property_mapping_entries,
3342 base_index, ext1_index, -1, -1,
3343 current_summarized_file_list_entry);
3347 start_pos += len_ext1_suffix;
3353 /* ---------- step 2: search for matching second suffix ---------- */
3355 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3357 char *ext2_suffix = ext2_suffixes[k];
3358 int len_ext2_suffix = strlen(ext2_suffix);
3360 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3362 if (!ext2_suffix_found)
3367 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3371 add_dynamic_file_list_entry(dynamic_file_list,
3372 num_dynamic_file_list_entries,
3375 num_suffix_list_entries,
3377 add_property_mapping(property_mapping,
3378 num_property_mapping_entries,
3379 base_index, ext1_index, ext2_index, -1,
3380 current_summarized_file_list_entry);
3384 start_pos += len_ext2_suffix;
3390 /* ---------- step 3: search for matching third suffix ---------- */
3392 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3394 char *ext3_suffix = ext3_suffixes[l];
3395 int len_ext3_suffix = strlen(ext3_suffix);
3397 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3399 if (!ext3_suffix_found)
3404 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3408 add_dynamic_file_list_entry(dynamic_file_list,
3409 num_dynamic_file_list_entries,
3412 num_suffix_list_entries,
3414 add_property_mapping(property_mapping,
3415 num_property_mapping_entries,
3416 base_index, ext1_index, ext2_index, ext3_index,
3417 current_summarized_file_list_entry);
3423 END_HASH_ITERATION(extra_file_hash, itr)
3425 if (artwork_info->num_dynamic_file_list_entries > 0)
3427 artwork_info->dynamic_artwork_list =
3428 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3429 artwork_info->sizeof_artwork_list_entry);
3432 if (options.verbose && IS_PARENT_PROCESS())
3434 SetupFileList *setup_file_list, *list;
3435 boolean dynamic_tokens_found = FALSE;
3436 boolean unknown_tokens_found = FALSE;
3437 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3439 /* list may be NULL for empty artwork config files */
3440 setup_file_list = loadSetupFileList(filename);
3442 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3444 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3445 dynamic_tokens_found = TRUE;
3447 unknown_tokens_found = TRUE;
3449 END_HASH_ITERATION(extra_file_hash, itr)
3451 if (options.debug && dynamic_tokens_found)
3453 Error(ERR_INFO_LINE, "-");
3454 Error(ERR_INFO, "dynamic token(s) found in config file:");
3455 Error(ERR_INFO, "- config file: '%s'", filename);
3457 for (list = setup_file_list; list != NULL; list = list->next)
3459 char *value = getHashEntry(extra_file_hash, list->token);
3461 if (value != NULL && strEqual(value, known_token_value))
3462 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3465 Error(ERR_INFO_LINE, "-");
3468 if (unknown_tokens_found)
3470 Error(ERR_INFO_LINE, "-");
3471 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3472 Error(ERR_INFO, "- config file: '%s'", filename);
3474 for (list = setup_file_list; list != NULL; list = list->next)
3476 char *value = getHashEntry(extra_file_hash, list->token);
3478 if (value != NULL && !strEqual(value, known_token_value))
3479 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3482 Error(ERR_INFO_LINE, "-");
3485 if (undefined_values_found)
3487 Error(ERR_INFO_LINE, "-");
3488 Error(ERR_INFO, "warning: undefined values found in config file:");
3489 Error(ERR_INFO, "- config file: '%s'", filename);
3491 for (list = setup_file_list; list != NULL; list = list->next)
3493 char *value = getHashEntry(empty_file_hash, list->token);
3496 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3499 Error(ERR_INFO_LINE, "-");
3502 freeSetupFileList(setup_file_list);
3505 freeSetupFileHash(extra_file_hash);
3506 freeSetupFileHash(empty_file_hash);
3509 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3511 struct FileInfo *file_list = artwork_info->file_list;
3512 int num_file_list_entries = artwork_info->num_file_list_entries;
3513 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3514 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3517 DrawInitText("Loading artwork config", 120, FC_GREEN);
3518 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3520 /* always start with reliable default values */
3521 for (i = 0; i < num_file_list_entries; i++)
3523 setString(&file_list[i].filename, file_list[i].default_filename);
3525 for (j = 0; j < num_suffix_list_entries; j++)
3526 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3528 file_list[i].redefined = FALSE;
3529 file_list[i].fallback_to_default = FALSE;
3532 /* free previous dynamic artwork file array */
3533 if (artwork_info->dynamic_file_list != NULL)
3535 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3537 free(artwork_info->dynamic_file_list[i].token);
3538 free(artwork_info->dynamic_file_list[i].filename);
3539 free(artwork_info->dynamic_file_list[i].parameter);
3542 free(artwork_info->dynamic_file_list);
3543 artwork_info->dynamic_file_list = NULL;
3545 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3546 &artwork_info->num_dynamic_file_list_entries);
3549 /* free previous property mapping */
3550 if (artwork_info->property_mapping != NULL)
3552 free(artwork_info->property_mapping);
3554 artwork_info->property_mapping = NULL;
3555 artwork_info->num_property_mapping_entries = 0;
3558 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3560 /* first look for special artwork configured in level series config */
3561 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3563 if (fileExists(filename_base))
3564 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3567 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3569 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3570 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3573 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3574 struct ListNodeInfo **listnode)
3578 char *filename = (*listnode)->source_filename;
3580 if (--(*listnode)->num_references <= 0)
3581 deleteNodeFromList(&artwork_info->content_list, filename,
3582 artwork_info->free_artwork);
3588 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3589 struct ListNodeInfo **listnode,
3590 struct FileInfo *file_list_entry)
3600 char *basename = file_list_entry->filename;
3601 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3603 if (filename == NULL)
3605 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3607 basename = file_list_entry->default_filename;
3609 /* fail for cloned default artwork that has no default filename defined */
3610 if (file_list_entry->default_is_cloned &&
3611 strEqual(basename, UNDEFINED_FILENAME))
3613 int error_mode = ERR_WARN;
3615 /* we can get away without sounds and music, but not without graphics */
3616 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3617 error_mode = ERR_EXIT;
3619 Error(error_mode, "token '%s' was cloned and has no default filename",
3620 file_list_entry->token);
3625 /* dynamic artwork has no default filename / skip empty default artwork */
3626 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3629 file_list_entry->fallback_to_default = TRUE;
3631 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3633 filename = getCustomArtworkFilename(basename, artwork_info->type);
3635 if (filename == NULL)
3637 int error_mode = ERR_WARN;
3639 /* we can get away without sounds and music, but not without graphics */
3640 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3641 error_mode = ERR_EXIT;
3643 Error(error_mode, "cannot find default artwork file '%s'", basename);
3649 /* check if the old and the new artwork file are the same */
3650 if (*listnode && strEqual((*listnode)->source_filename, filename))
3652 /* The old and new artwork are the same (have the same filename and path).
3653 This usually means that this artwork does not exist in this artwork set
3654 and a fallback to the existing artwork is done. */
3659 /* delete existing artwork file entry */
3660 deleteArtworkListEntry(artwork_info, listnode);
3662 /* check if the new artwork file already exists in the list of artwork */
3663 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3665 *listnode = (struct ListNodeInfo *)node->content;
3666 (*listnode)->num_references++;
3671 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3672 DrawInitText(basename, 150, FC_YELLOW);
3674 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3676 /* add new artwork file entry to the list of artwork files */
3677 (*listnode)->num_references = 1;
3678 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3683 int error_mode = ERR_WARN;
3685 /* we can get away without sounds and music, but not without graphics */
3686 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3687 error_mode = ERR_EXIT;
3689 Error(error_mode, "cannot load artwork file '%s'", basename);
3695 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3696 struct ListNodeInfo **listnode,
3697 struct FileInfo *file_list_entry)
3699 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3701 deleteArtworkListEntry(artwork_info, listnode);
3706 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3709 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3711 struct FileInfo *file_list = artwork_info->file_list;
3712 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3713 int num_file_list_entries = artwork_info->num_file_list_entries;
3714 int num_dynamic_file_list_entries =
3715 artwork_info->num_dynamic_file_list_entries;
3718 print_timestamp_init("ReloadCustomArtworkList");
3720 for (i = 0; i < num_file_list_entries; i++)
3721 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3724 for (i = 0; i < num_dynamic_file_list_entries; i++)
3725 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3726 &dynamic_file_list[i]);
3728 print_timestamp_done("ReloadCustomArtworkList");
3731 dumpList(artwork_info->content_list);
3735 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3736 struct ListNodeInfo ***list,
3737 int *num_list_entries)
3744 for (i = 0; i < *num_list_entries; i++)
3745 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3749 *num_list_entries = 0;
3752 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3754 if (artwork_info == NULL)
3757 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3758 &artwork_info->num_file_list_entries);
3760 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3761 &artwork_info->num_dynamic_file_list_entries);
3765 /* ------------------------------------------------------------------------- */
3766 /* functions only needed for non-Unix (non-command-line) systems */
3767 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3768 /* (now also added for Windows, to create files in user data directory) */
3769 /* ------------------------------------------------------------------------- */
3771 char *getLogFilename(char *basename)
3773 return getPath2(getUserGameDataDir(), basename);
3780 InitUserDataDirectory();
3782 for (i = 0; i < NUM_LOGS; i++)
3784 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3787 program.log_file[i] = program.log_file_default[i]; // reset to default
3789 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3790 program.log_filename[i], strerror(errno));
3793 /* output should be unbuffered so it is not truncated in a crash */
3794 setbuf(program.log_file[i], NULL);
3798 void CloseLogFiles()
3802 for (i = 0; i < NUM_LOGS; i++)
3803 if (program.log_file[i] != program.log_file_default[i])
3804 fclose(program.log_file[i]);
3807 void DumpLogFile(int nr)
3809 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3811 if (log_file == NULL)
3814 while (!feof(log_file))
3815 fputc(fgetc(log_file), stdout);
3820 void NotifyUserAboutErrorFile()
3822 #if defined(PLATFORM_WIN32)
3823 char *title_text = getStringCat2(program.program_title, " Error Message");
3824 char *error_text = getStringCat2("The program was aborted due to an error; "
3825 "for details, see the following error file:"
3827 program.log_filename[LOG_ERR_ID]);
3829 MessageBox(NULL, error_text, title_text, MB_OK);
3834 /* ------------------------------------------------------------------------- */
3835 /* the following is only for debugging purpose and normally not used */
3836 /* ------------------------------------------------------------------------- */
3840 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3841 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3843 #define DEBUG_NUM_TIMESTAMPS 10
3844 #define DEBUG_TIME_IN_MICROSECONDS 0
3846 #if DEBUG_TIME_IN_MICROSECONDS
3847 static double Counter_Microseconds()
3849 static struct timeval base_time = { 0, 0 };
3850 struct timeval current_time;
3853 gettimeofday(¤t_time, NULL);
3855 /* reset base time in case of wrap-around */
3856 if (current_time.tv_sec < base_time.tv_sec)
3857 base_time = current_time;
3860 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3861 ((double)(current_time.tv_usec - base_time.tv_usec));
3863 return counter; /* return microseconds since last init */
3867 char *debug_print_timestamp_get_padding(int padding_size)
3869 static char *padding = NULL;
3870 int max_padding_size = 100;
3872 if (padding == NULL)
3874 padding = checked_calloc(max_padding_size + 1);
3875 memset(padding, ' ', max_padding_size);
3878 return &padding[MAX(0, max_padding_size - padding_size)];
3881 void debug_print_timestamp(int counter_nr, char *message)
3883 int indent_size = 8;
3884 int padding_size = 40;
3885 float timestamp_interval;
3888 Error(ERR_EXIT, "debugging: invalid negative counter");
3889 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3890 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3892 #if DEBUG_TIME_IN_MICROSECONDS
3893 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3896 counter[counter_nr][0] = Counter_Microseconds();
3898 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3901 counter[counter_nr][0] = Counter();
3904 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3905 counter[counter_nr][1] = counter[counter_nr][0];
3908 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3909 debug_print_timestamp_get_padding(counter_nr * indent_size),
3911 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3912 timestamp_interval / 1000,
3916 void debug_print_parent_only(char *format, ...)
3918 if (!IS_PARENT_PROCESS())
3925 va_start(ap, format);
3926 vprintf(format, ap);
3935 void print_timestamp_ext(char *message, char *mode)
3937 #if DEBUG_PRINT_INIT_TIMESTAMPS
3938 static char *debug_message = NULL;
3939 static char *last_message = NULL;
3940 static int counter_nr = 0;
3941 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3943 checked_free(debug_message);
3944 debug_message = getStringCat3(mode, " ", message);
3946 if (strEqual(mode, "INIT"))
3948 debug_print_timestamp(counter_nr, NULL);
3950 if (counter_nr + 1 < max_depth)
3951 debug_print_timestamp(counter_nr, debug_message);
3955 debug_print_timestamp(counter_nr, NULL);
3957 else if (strEqual(mode, "DONE"))
3961 if (counter_nr + 1 < max_depth ||
3962 (counter_nr == 0 && max_depth == 1))
3964 last_message = message;
3966 if (counter_nr == 0 && max_depth == 1)
3968 checked_free(debug_message);
3969 debug_message = getStringCat3("TIME", " ", message);
3972 debug_print_timestamp(counter_nr, debug_message);
3975 else if (!strEqual(mode, "TIME") ||
3976 !strEqual(message, last_message))
3978 if (counter_nr < max_depth)
3979 debug_print_timestamp(counter_nr, debug_message);
3984 void print_timestamp_init(char *message)
3986 print_timestamp_ext(message, "INIT");
3989 void print_timestamp_time(char *message)
3991 print_timestamp_ext(message, "TIME");
3994 void print_timestamp_done(char *message)
3996 print_timestamp_ext(message, "DONE");