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 PrintLine(char *line_chars, int line_length)
229 for (i = 0; i < line_length; i++)
235 void PrintLineWithPrefix(char *prefix, char *line_chars, int line_length)
238 PrintLine(line_chars, line_length);
242 /* ------------------------------------------------------------------------- */
243 /* string functions */
244 /* ------------------------------------------------------------------------- */
246 /* int2str() returns a number converted to a string;
247 the used memory is static, but will be overwritten by later calls,
248 so if you want to save the result, copy it to a private string buffer;
249 there can be 10 local calls of int2str() without buffering the result --
250 the 11th call will then destroy the result from the first call and so on.
253 char *int2str(int number, int size)
255 static char shift_array[10][40];
256 static int shift_counter = 0;
257 char *s = shift_array[shift_counter];
259 shift_counter = (shift_counter + 1) % 10;
266 sprintf(s, " %09d", number);
267 return &s[strlen(s) - size];
271 sprintf(s, "%d", number);
277 /* something similar to "int2str()" above, but allocates its own memory
278 and has a different interface; we cannot use "itoa()", because this
279 seems to be already defined when cross-compiling to the win32 target */
281 char *i_to_a(unsigned int i)
283 static char *a = NULL;
287 if (i > 2147483647) /* yes, this is a kludge */
290 a = checked_malloc(10 + 1);
298 /* calculate base-2 logarithm of argument (rounded down to integer;
299 this function returns the number of the highest bit set in argument) */
301 int log_2(unsigned int x)
307 x -= (1 << e); /* for rounding down (rounding up: remove this line) */
314 boolean getTokenValueFromString(char *string, char **token, char **value)
316 return getTokenValueFromSetupLine(string, token, value);
320 /* ------------------------------------------------------------------------- */
321 /* counter functions */
322 /* ------------------------------------------------------------------------- */
324 /* maximal allowed length of a command line option */
325 #define MAX_OPTION_LEN 256
327 static unsigned int getCurrentMS()
329 return SDL_GetTicks();
332 static unsigned int mainCounter(int mode)
334 static unsigned int base_ms = 0;
335 unsigned int current_ms;
337 /* get current system milliseconds */
338 current_ms = getCurrentMS();
340 /* reset base timestamp in case of counter reset or wrap-around */
341 if (mode == INIT_COUNTER || current_ms < base_ms)
342 base_ms = current_ms;
344 /* return milliseconds since last counter reset */
345 return current_ms - base_ms;
348 void InitCounter() /* set counter back to zero */
350 mainCounter(INIT_COUNTER);
353 unsigned int Counter() /* get milliseconds since last call of InitCounter() */
355 return mainCounter(READ_COUNTER);
358 static void sleep_milliseconds(unsigned int milliseconds_delay)
360 SDL_Delay(milliseconds_delay);
363 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
365 sleep_milliseconds(delay);
368 boolean DelayReachedExt(unsigned int *counter_var, unsigned int delay,
369 unsigned int actual_counter)
371 if (actual_counter >= *counter_var &&
372 actual_counter < *counter_var + delay)
375 *counter_var = actual_counter;
380 boolean FrameReached(unsigned int *frame_counter_var, unsigned int frame_delay)
382 return DelayReachedExt(frame_counter_var, frame_delay, FrameCounter);
385 boolean DelayReached(unsigned int *counter_var, unsigned int delay)
387 return DelayReachedExt(counter_var, delay, Counter());
390 void ResetDelayCounterExt(unsigned int *counter_var,
391 unsigned int actual_counter)
393 DelayReachedExt(counter_var, 0, actual_counter);
396 void ResetFrameCounter(unsigned int *frame_counter_var)
398 FrameReached(frame_counter_var, 0);
401 void ResetDelayCounter(unsigned int *counter_var)
403 DelayReached(counter_var, 0);
406 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
408 unsigned int actual_counter;
413 actual_counter = Counter();
415 if (actual_counter >= *counter_var &&
416 actual_counter < *counter_var + delay)
417 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
422 if (*counter_var != 0 &&
424 actual_counter >= *counter_var + delay)
426 int lag = actual_counter - (*counter_var + delay);
427 int delay2 = (delay + 1) / 2;
430 skip_frames = (lag + delay2) / delay;
433 *counter_var = actual_counter;
438 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
439 int *loop_var, int last_loop_value)
441 int skip_frames = WaitUntilDelayReached(counter_var, delay);
445 printf("::: %d: %d ms", *loop_var, delay);
447 printf(" -> SKIP %d FRAME(S) [%d ms]", skip_frames, skip_frames * delay);
452 if (skip_frames == 0)
455 // when skipping frames, make sure to never skip the last frame, as
456 // this may be needed for animations to reach a defined end state;
457 // furthermore, we assume that this function is called at the end
458 // of a "for" loop, which continues by incrementing the loop variable
459 // by one before checking the loop condition again; therefore we have
460 // to check against the last loop value minus one here
464 if (*loop_var < last_loop_value) // never skip the last frame
466 *loop_var += skip_frames;
468 if (*loop_var > last_loop_value) // never skip the last frame
469 *loop_var = last_loop_value;
474 /* ------------------------------------------------------------------------- */
475 /* random generator functions */
476 /* ------------------------------------------------------------------------- */
478 unsigned int init_random_number(int nr, int seed)
480 if (seed == NEW_RANDOMIZE)
482 /* default random seed */
483 seed = (int)time(NULL); // seconds since the epoch
485 #if !defined(PLATFORM_WIN32)
486 /* add some more randomness */
487 struct timeval current_time;
489 gettimeofday(¤t_time, NULL);
491 seed += (int)current_time.tv_usec; // microseconds since the epoch
494 /* add some more randomness */
495 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
497 /* add some more randomness */
498 seed += GetSimpleRandom(1000000);
501 srandom_linux_libc(nr, (unsigned int) seed);
503 return (unsigned int) seed;
506 unsigned int get_random_number(int nr, int max)
508 return (max > 0 ? random_linux_libc(nr) % max : 0);
512 /* ------------------------------------------------------------------------- */
513 /* system info functions */
514 /* ------------------------------------------------------------------------- */
516 #if !defined(PLATFORM_ANDROID)
517 static char *get_corrected_real_name(char *real_name)
519 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
520 char *from_ptr = real_name;
521 char *to_ptr = real_name_new;
523 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
524 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
526 /* the name field read from "passwd" file may also contain additional
527 user information, separated by commas, which will be removed here */
528 if (*from_ptr == ',')
531 /* the user's real name may contain 'german sharp s' characters,
532 which have no equivalent in upper case letters (used by our fonts) */
533 if (*from_ptr == CHAR_BYTE_SHARP_S)
540 *to_ptr++ = *from_ptr++;
545 return real_name_new;
551 static char *login_name = NULL;
553 #if defined(PLATFORM_WIN32)
554 if (login_name == NULL)
556 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
557 login_name = checked_malloc(buffer_size);
559 if (GetUserName(login_name, &buffer_size) == 0)
560 strcpy(login_name, ANONYMOUS_NAME);
563 if (login_name == NULL)
567 if ((pwd = getpwuid(getuid())) == NULL)
568 login_name = ANONYMOUS_NAME;
570 login_name = getStringCopy(pwd->pw_name);
579 static char *real_name = NULL;
581 #if defined(PLATFORM_WIN32)
582 if (real_name == NULL)
584 static char buffer[MAX_USERNAME_LEN + 1];
585 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
587 if (GetUserName(buffer, &buffer_size) != 0)
588 real_name = get_corrected_real_name(buffer);
590 real_name = ANONYMOUS_NAME;
592 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
593 if (real_name == NULL)
597 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
598 real_name = get_corrected_real_name(pwd->pw_gecos);
600 real_name = ANONYMOUS_NAME;
603 real_name = ANONYMOUS_NAME;
609 time_t getFileTimestampEpochSeconds(char *filename)
611 struct stat file_status;
613 if (stat(filename, &file_status) != 0) /* cannot stat file */
616 return file_status.st_mtime;
620 /* ------------------------------------------------------------------------- */
621 /* path manipulation functions */
622 /* ------------------------------------------------------------------------- */
624 static char *getLastPathSeparatorPtr(char *filename)
626 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
628 if (last_separator == NULL) /* also try DOS/Windows variant */
629 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
631 return last_separator;
634 char *getBaseNamePtr(char *filename)
636 char *last_separator = getLastPathSeparatorPtr(filename);
638 if (last_separator != NULL)
639 return last_separator + 1; /* separator found: strip base path */
641 return filename; /* no separator found: filename has no path */
644 char *getBaseName(char *filename)
646 return getStringCopy(getBaseNamePtr(filename));
649 char *getBaseNameNoSuffix(char *filename)
651 char *basename = getStringCopy(getBaseNamePtr(filename));
653 // remove trailing suffix (separated by dot or hyphen)
654 if (basename[0] != '.' && basename[0] != '-')
656 if (strchr(basename, '.') != NULL)
657 *strchr(basename, '.') = '\0';
659 if (strchr(basename, '-') != NULL)
660 *strchr(basename, '-') = '\0';
666 char *getBasePath(char *filename)
668 char *basepath = getStringCopy(filename);
669 char *last_separator = getLastPathSeparatorPtr(basepath);
671 if (last_separator != NULL)
672 *last_separator = '\0'; /* separator found: strip basename */
674 basepath = "."; /* no separator found: use current path */
679 static char *getProgramMainDataPath()
681 char *main_data_path = getStringCopy(program.command_basepath);
683 #if defined(PLATFORM_MACOSX)
684 static char *main_data_binary_subdir = NULL;
686 if (main_data_binary_subdir == NULL)
688 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
690 strlen(MAC_APP_BINARY_SUBDIR) + 1);
692 sprintf(main_data_binary_subdir, "%s.app/%s",
693 program.program_title, MAC_APP_BINARY_SUBDIR);
696 // cut relative path to Mac OS X application binary directory from path
697 if (strSuffix(main_data_path, main_data_binary_subdir))
698 main_data_path[strlen(main_data_path) -
699 strlen(main_data_binary_subdir)] = '\0';
701 // cut trailing path separator from path (but not if path is root directory)
702 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
703 main_data_path[strlen(main_data_path) - 1] = '\0';
706 return main_data_path;
710 /* ------------------------------------------------------------------------- */
711 /* various string functions */
712 /* ------------------------------------------------------------------------- */
714 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
716 if (s1 == NULL || s2 == NULL || sep == NULL)
719 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
722 sprintf(complete_string, "%s%s%s", s1, sep, s2);
724 return complete_string;
727 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
729 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
732 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
733 strlen(s2) + strlen(sep) +
736 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
738 return complete_string;
741 char *getStringCat2(char *s1, char *s2)
743 return getStringCat2WithSeparator(s1, s2, "");
746 char *getStringCat3(char *s1, char *s2, char *s3)
748 return getStringCat3WithSeparator(s1, s2, s3, "");
751 char *getPath2(char *path1, char *path2)
753 #if defined(PLATFORM_ANDROID)
754 // workaround for reading from assets directory -- skip "." subdirs in path
755 if (strEqual(path1, "."))
756 return getStringCopy(path2);
757 else if (strEqual(path2, "."))
758 return getStringCopy(path1);
761 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
764 char *getPath3(char *path1, char *path2, char *path3)
766 #if defined(PLATFORM_ANDROID)
767 // workaround for reading from assets directory -- skip "." subdirs in path
768 if (strEqual(path1, "."))
769 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
770 else if (strEqual(path2, "."))
771 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
772 else if (strEqual(path3, "."))
773 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
776 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
779 static char *getPngOrPcxIfNotExists(char *filename)
781 // switch from PNG to PCX file and vice versa, if file does not exist
782 // (backwards compatibility with PCX files used in previous versions)
784 if (!fileExists(filename) && strSuffix(filename, ".png"))
785 strcpy(&filename[strlen(filename) - 3], "pcx");
786 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
787 strcpy(&filename[strlen(filename) - 3], "png");
792 char *getImg2(char *path1, char *path2)
794 return getPngOrPcxIfNotExists(getPath2(path1, path2));
797 char *getImg3(char *path1, char *path2, char *path3)
799 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
802 char *getStringCopy(const char *s)
809 s_copy = checked_malloc(strlen(s) + 1);
815 char *getStringCopyN(const char *s, int n)
818 int s_len = MAX(0, n);
823 s_copy = checked_malloc(s_len + 1);
824 strncpy(s_copy, s, s_len);
825 s_copy[s_len] = '\0';
830 char *getStringCopyNStatic(const char *s, int n)
832 static char *s_copy = NULL;
834 checked_free(s_copy);
836 s_copy = getStringCopyN(s, n);
841 char *getStringToLower(const char *s)
843 char *s_copy = checked_malloc(strlen(s) + 1);
844 char *s_ptr = s_copy;
847 *s_ptr++ = tolower(*s++);
853 void setString(char **old_value, char *new_value)
855 checked_free(*old_value);
857 *old_value = getStringCopy(new_value);
860 boolean strEqual(char *s1, char *s2)
862 return (s1 == NULL && s2 == NULL ? TRUE :
863 s1 == NULL && s2 != NULL ? FALSE :
864 s1 != NULL && s2 == NULL ? FALSE :
865 strcmp(s1, s2) == 0);
868 boolean strEqualN(char *s1, char *s2, int n)
870 return (s1 == NULL && s2 == NULL ? TRUE :
871 s1 == NULL && s2 != NULL ? FALSE :
872 s1 != NULL && s2 == NULL ? FALSE :
873 strncmp(s1, s2, n) == 0);
876 boolean strPrefix(char *s, char *prefix)
878 return (s == NULL && prefix == NULL ? TRUE :
879 s == NULL && prefix != NULL ? FALSE :
880 s != NULL && prefix == NULL ? FALSE :
881 strncmp(s, prefix, strlen(prefix)) == 0);
884 boolean strSuffix(char *s, char *suffix)
886 return (s == NULL && suffix == NULL ? TRUE :
887 s == NULL && suffix != NULL ? FALSE :
888 s != NULL && suffix == NULL ? FALSE :
889 strlen(s) < strlen(suffix) ? FALSE :
890 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
893 boolean strPrefixLower(char *s, char *prefix)
895 char *s_lower = getStringToLower(s);
896 boolean match = strPrefix(s_lower, prefix);
903 boolean strSuffixLower(char *s, char *suffix)
905 char *s_lower = getStringToLower(s);
906 boolean match = strSuffix(s_lower, suffix);
914 /* ------------------------------------------------------------------------- */
915 /* command line option handling functions */
916 /* ------------------------------------------------------------------------- */
918 void GetOptions(int argc, char *argv[],
919 void (*print_usage_function)(void),
920 void (*print_version_function)(void))
922 char *ro_base_path = RO_BASE_PATH;
923 char *rw_base_path = RW_BASE_PATH;
924 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
925 char **options_left = &argvplus[1];
927 /* replace original "argv" with null-terminated array of string pointers */
929 argvplus[argc] = argv[argc];
931 /* if the program is configured to start from current directory (default),
932 determine program package directory from program binary (some versions
933 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
934 set the current working directory to the program package directory) */
936 if (strEqual(ro_base_path, "."))
937 ro_base_path = getProgramMainDataPath();
938 if (strEqual(rw_base_path, "."))
939 rw_base_path = getProgramMainDataPath();
941 /* initialize global program options */
942 options.server_host = NULL;
943 options.server_port = 0;
945 options.ro_base_directory = ro_base_path;
946 options.rw_base_directory = rw_base_path;
947 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
948 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
949 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
950 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
951 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
953 options.execute_command = NULL;
954 options.special_flags = NULL;
956 options.serveronly = FALSE;
957 options.network = FALSE;
958 options.verbose = FALSE;
959 options.debug = FALSE;
962 options.verbose = TRUE;
964 #if !defined(PLATFORM_UNIX)
965 if (*options_left == NULL) /* no options given -- enable verbose mode */
966 options.verbose = TRUE;
970 while (*options_left)
972 char option_str[MAX_OPTION_LEN];
973 char *option = options_left[0];
974 char *next_option = options_left[1];
975 char *option_arg = NULL;
976 int option_len = strlen(option);
978 if (option_len >= MAX_OPTION_LEN)
979 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
981 strcpy(option_str, option); /* copy argument into buffer */
984 if (strEqual(option, "--")) /* stop scanning arguments */
987 if (strPrefix(option, "--")) /* treat '--' like '-' */
990 option_arg = strchr(option, '=');
991 if (option_arg == NULL) /* no '=' in option */
992 option_arg = next_option;
995 *option_arg++ = '\0'; /* cut argument from option */
996 if (*option_arg == '\0') /* no argument after '=' */
997 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
1000 option_len = strlen(option);
1002 if (strEqual(option, "-"))
1004 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1006 else if (strncmp(option, "-help", option_len) == 0)
1008 print_usage_function();
1012 else if (strncmp(option, "-basepath", option_len) == 0)
1014 if (option_arg == NULL)
1015 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1017 /* this should be extended to separate options for ro and rw data */
1018 options.ro_base_directory = ro_base_path = option_arg;
1019 options.rw_base_directory = rw_base_path = option_arg;
1020 if (option_arg == next_option)
1023 /* adjust paths for sub-directories in base directory accordingly */
1024 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1025 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1026 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1027 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1028 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1030 else if (strncmp(option, "-levels", option_len) == 0)
1032 if (option_arg == NULL)
1033 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1035 options.level_directory = option_arg;
1036 if (option_arg == next_option)
1039 else if (strncmp(option, "-graphics", option_len) == 0)
1041 if (option_arg == NULL)
1042 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1044 options.graphics_directory = option_arg;
1045 if (option_arg == next_option)
1048 else if (strncmp(option, "-sounds", option_len) == 0)
1050 if (option_arg == NULL)
1051 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1053 options.sounds_directory = option_arg;
1054 if (option_arg == next_option)
1057 else if (strncmp(option, "-music", option_len) == 0)
1059 if (option_arg == NULL)
1060 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1062 options.music_directory = option_arg;
1063 if (option_arg == next_option)
1066 else if (strncmp(option, "-network", option_len) == 0)
1068 options.network = TRUE;
1070 else if (strncmp(option, "-serveronly", option_len) == 0)
1072 options.serveronly = TRUE;
1074 else if (strncmp(option, "-debug", option_len) == 0)
1076 options.debug = TRUE;
1078 else if (strncmp(option, "-verbose", option_len) == 0)
1080 options.verbose = TRUE;
1082 else if (strncmp(option, "-version", option_len) == 0 ||
1083 strncmp(option, "-V", option_len) == 0)
1085 print_version_function();
1089 else if (strPrefix(option, "-D"))
1091 options.special_flags = getStringCopy(&option[2]);
1093 else if (strncmp(option, "-execute", option_len) == 0)
1095 if (option_arg == NULL)
1096 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1098 options.execute_command = option_arg;
1099 if (option_arg == next_option)
1102 /* when doing batch processing, always enable verbose mode (warnings) */
1103 options.verbose = TRUE;
1105 #if defined(PLATFORM_MACOSX)
1106 else if (strPrefix(option, "-psn"))
1108 /* ignore process serial number when launched via GUI on Mac OS X */
1111 else if (*option == '-')
1113 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1115 else if (options.server_host == NULL)
1117 options.server_host = *options_left;
1119 else if (options.server_port == 0)
1121 options.server_port = atoi(*options_left);
1122 if (options.server_port < 1024)
1123 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1126 Error(ERR_EXIT_HELP, "too many arguments");
1133 /* ------------------------------------------------------------------------- */
1134 /* error handling functions */
1135 /* ------------------------------------------------------------------------- */
1137 #define MAX_INTERNAL_ERROR_SIZE 1024
1139 /* used by SetError() and GetError() to store internal error messages */
1140 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1142 void SetError(char *format, ...)
1146 va_start(ap, format);
1147 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1153 return internal_error;
1156 void Error(int mode, char *format, ...)
1158 static boolean last_line_was_separator = FALSE;
1159 char *process_name = "";
1161 if (program.log_file[LOG_ERR_ID] == NULL)
1164 #if defined(PLATFORM_ANDROID)
1165 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1166 mode & ERR_INFO ? ANDROID_LOG_INFO :
1167 mode & ERR_WARN ? ANDROID_LOG_WARN :
1168 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1169 ANDROID_LOG_UNKNOWN);
1172 /* display warnings only when running in verbose mode */
1173 if (mode & ERR_WARN && !options.verbose)
1176 if (mode == ERR_INFO_LINE)
1178 if (!last_line_was_separator)
1179 printf_log_line(format, 79);
1181 last_line_was_separator = TRUE;
1186 last_line_was_separator = FALSE;
1188 if (mode & ERR_SOUND_SERVER)
1189 process_name = " sound server";
1190 else if (mode & ERR_NETWORK_SERVER)
1191 process_name = " network server";
1192 else if (mode & ERR_NETWORK_CLIENT)
1193 process_name = " network client **";
1197 #if !defined(PLATFORM_ANDROID)
1198 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1201 if (mode & ERR_WARN)
1202 printf_log_nonewline("warning: ");
1204 if (mode & ERR_EXIT)
1205 printf_log_nonewline("fatal error: ");
1209 va_start(ap, format);
1210 vprintf_log(format, ap);
1213 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1215 va_start(ap, format);
1216 program.exit_message_function(format, ap);
1221 if (mode & ERR_HELP)
1222 printf_log("%s: Try option '--help' for more information.",
1223 program.command_basename);
1225 if (mode & ERR_EXIT)
1226 printf_log("%s%s: aborting", program.command_basename, process_name);
1228 if (mode & ERR_EXIT)
1230 if (mode & ERR_FROM_SERVER)
1231 exit(1); /* child process: normal exit */
1233 program.exit_function(1); /* main process: clean up stuff */
1238 /* ------------------------------------------------------------------------- */
1239 /* checked memory allocation and freeing functions */
1240 /* ------------------------------------------------------------------------- */
1242 void *checked_malloc(unsigned int size)
1249 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1254 void *checked_calloc(unsigned int size)
1258 ptr = calloc(1, size);
1261 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1266 void *checked_realloc(void *ptr, unsigned int size)
1268 ptr = realloc(ptr, size);
1271 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1276 void checked_free(void *ptr)
1278 if (ptr != NULL) /* this check should be done by free() anyway */
1282 void clear_mem(void *ptr, unsigned int size)
1284 #if defined(PLATFORM_WIN32)
1285 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1286 char *cptr = (char *)ptr;
1291 memset(ptr, 0, size);
1296 /* ------------------------------------------------------------------------- */
1297 /* various helper functions */
1298 /* ------------------------------------------------------------------------- */
1300 void swap_numbers(int *i1, int *i2)
1308 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1320 /* the "put" variants of the following file access functions check for the file
1321 pointer being != NULL and return the number of bytes they have or would have
1322 written; this allows for chunk writing functions to first determine the size
1323 of the (not yet written) chunk, write the correct chunk size and finally
1324 write the chunk itself */
1326 int getFile8BitInteger(File *file)
1328 return getByteFromFile(file);
1331 int putFile8BitInteger(FILE *file, int value)
1339 int getFile16BitInteger(File *file, int byte_order)
1341 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1342 return ((getByteFromFile(file) << 8) |
1343 (getByteFromFile(file) << 0));
1344 else /* BYTE_ORDER_LITTLE_ENDIAN */
1345 return ((getByteFromFile(file) << 0) |
1346 (getByteFromFile(file) << 8));
1349 int putFile16BitInteger(FILE *file, int value, int byte_order)
1353 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1355 fputc((value >> 8) & 0xff, file);
1356 fputc((value >> 0) & 0xff, file);
1358 else /* BYTE_ORDER_LITTLE_ENDIAN */
1360 fputc((value >> 0) & 0xff, file);
1361 fputc((value >> 8) & 0xff, file);
1368 int getFile32BitInteger(File *file, int byte_order)
1370 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1371 return ((getByteFromFile(file) << 24) |
1372 (getByteFromFile(file) << 16) |
1373 (getByteFromFile(file) << 8) |
1374 (getByteFromFile(file) << 0));
1375 else /* BYTE_ORDER_LITTLE_ENDIAN */
1376 return ((getByteFromFile(file) << 0) |
1377 (getByteFromFile(file) << 8) |
1378 (getByteFromFile(file) << 16) |
1379 (getByteFromFile(file) << 24));
1382 int putFile32BitInteger(FILE *file, int value, int byte_order)
1386 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1388 fputc((value >> 24) & 0xff, file);
1389 fputc((value >> 16) & 0xff, file);
1390 fputc((value >> 8) & 0xff, file);
1391 fputc((value >> 0) & 0xff, file);
1393 else /* BYTE_ORDER_LITTLE_ENDIAN */
1395 fputc((value >> 0) & 0xff, file);
1396 fputc((value >> 8) & 0xff, file);
1397 fputc((value >> 16) & 0xff, file);
1398 fputc((value >> 24) & 0xff, file);
1405 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1408 const int chunk_name_length = 4;
1410 /* read chunk name */
1411 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1414 if (chunk_size != NULL)
1416 /* read chunk size */
1417 *chunk_size = getFile32BitInteger(file, byte_order);
1420 return (checkEndOfFile(file) ? FALSE : TRUE);
1423 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1428 /* write chunk name */
1430 fputs(chunk_name, file);
1432 num_bytes += strlen(chunk_name);
1434 if (chunk_size >= 0)
1436 /* write chunk size */
1438 putFile32BitInteger(file, chunk_size, byte_order);
1446 int getFileVersion(File *file)
1448 int version_major = getByteFromFile(file);
1449 int version_minor = getByteFromFile(file);
1450 int version_patch = getByteFromFile(file);
1451 int version_build = getByteFromFile(file);
1453 return VERSION_IDENT(version_major, version_minor, version_patch,
1457 int putFileVersion(FILE *file, int version)
1461 int version_major = VERSION_MAJOR(version);
1462 int version_minor = VERSION_MINOR(version);
1463 int version_patch = VERSION_PATCH(version);
1464 int version_build = VERSION_BUILD(version);
1466 fputc(version_major, file);
1467 fputc(version_minor, file);
1468 fputc(version_patch, file);
1469 fputc(version_build, file);
1475 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1479 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1480 buffer[i] = getByteFromFile(file);
1483 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1487 for(i = 0; i < bytes; i++)
1488 fputc(buffer[i], file);
1491 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1493 while (bytes-- && !checkEndOfFile(file))
1494 getByteFromFile(file);
1497 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1504 /* ------------------------------------------------------------------------- */
1505 /* functions to translate key identifiers between different format */
1506 /* ------------------------------------------------------------------------- */
1508 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1509 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1510 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1511 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1513 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1522 /* normal cursor keys */
1523 { KSYM_Left, "XK_Left", "cursor left" },
1524 { KSYM_Right, "XK_Right", "cursor right" },
1525 { KSYM_Up, "XK_Up", "cursor up" },
1526 { KSYM_Down, "XK_Down", "cursor down" },
1528 /* keypad cursor keys */
1530 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1531 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1532 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1533 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1536 /* other keypad keys */
1537 #ifdef KSYM_KP_Enter
1538 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1539 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1540 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1541 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1542 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1543 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1547 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1548 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1549 { KSYM_Control_L, "XK_Control_L", "left control" },
1550 { KSYM_Control_R, "XK_Control_R", "right control" },
1551 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1552 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1553 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1554 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1555 #if !defined(TARGET_SDL2)
1556 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1557 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1559 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1560 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1562 /* some special keys */
1563 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1564 { KSYM_Delete, "XK_Delete", "delete" },
1565 { KSYM_Insert, "XK_Insert", "insert" },
1566 { KSYM_Tab, "XK_Tab", "tab" },
1567 { KSYM_Home, "XK_Home", "home" },
1568 { KSYM_End, "XK_End", "end" },
1569 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1570 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1572 #if defined(TARGET_SDL2)
1573 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1574 { KSYM_Back, "XK_Back", "back" }, /* back key */
1577 /* ASCII 0x20 to 0x40 keys (except numbers) */
1578 { KSYM_space, "XK_space", "space" },
1579 { KSYM_exclam, "XK_exclam", "!" },
1580 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1581 { KSYM_numbersign, "XK_numbersign", "#" },
1582 { KSYM_dollar, "XK_dollar", "$" },
1583 { KSYM_percent, "XK_percent", "%" },
1584 { KSYM_ampersand, "XK_ampersand", "&" },
1585 { KSYM_apostrophe, "XK_apostrophe", "'" },
1586 { KSYM_parenleft, "XK_parenleft", "(" },
1587 { KSYM_parenright, "XK_parenright", ")" },
1588 { KSYM_asterisk, "XK_asterisk", "*" },
1589 { KSYM_plus, "XK_plus", "+" },
1590 { KSYM_comma, "XK_comma", "," },
1591 { KSYM_minus, "XK_minus", "-" },
1592 { KSYM_period, "XK_period", "." },
1593 { KSYM_slash, "XK_slash", "/" },
1594 { KSYM_colon, "XK_colon", ":" },
1595 { KSYM_semicolon, "XK_semicolon", ";" },
1596 { KSYM_less, "XK_less", "<" },
1597 { KSYM_equal, "XK_equal", "=" },
1598 { KSYM_greater, "XK_greater", ">" },
1599 { KSYM_question, "XK_question", "?" },
1600 { KSYM_at, "XK_at", "@" },
1602 /* more ASCII keys */
1603 { KSYM_bracketleft, "XK_bracketleft", "[" },
1604 { KSYM_backslash, "XK_backslash", "\\" },
1605 { KSYM_bracketright,"XK_bracketright", "]" },
1606 { KSYM_asciicircum, "XK_asciicircum", "^" },
1607 { KSYM_underscore, "XK_underscore", "_" },
1608 { KSYM_grave, "XK_grave", "grave" },
1609 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1610 { KSYM_braceleft, "XK_braceleft", "brace left" },
1611 { KSYM_bar, "XK_bar", "bar" },
1612 { KSYM_braceright, "XK_braceright", "brace right" },
1613 { KSYM_asciitilde, "XK_asciitilde", "~" },
1615 /* special (non-ASCII) keys */
1616 { KSYM_degree, "XK_degree", "degree" },
1617 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1618 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1619 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1620 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1621 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1622 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1623 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1625 #if defined(TARGET_SDL2)
1626 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1627 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1628 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1629 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1630 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1631 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1632 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1633 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1634 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1636 /* other keys (for reverse mapping only) */
1637 { KSYM_space, "XK_space", " " },
1640 #if defined(TARGET_SDL2)
1641 /* keypad keys are not in numerical order in SDL2 */
1642 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1643 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1644 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1645 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1646 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1647 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1648 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1649 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1650 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1651 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1654 /* end-of-array identifier */
1660 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1662 static char name_buffer[30];
1665 if (key >= KSYM_A && key <= KSYM_Z)
1666 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1667 else if (key >= KSYM_a && key <= KSYM_z)
1668 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1669 else if (key >= KSYM_0 && key <= KSYM_9)
1670 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1671 #if !defined(TARGET_SDL2)
1672 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1673 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1675 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1676 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1677 else if (key == KSYM_UNDEFINED)
1678 strcpy(name_buffer, "(undefined)");
1685 if (key == translate_key[i].key)
1687 strcpy(name_buffer, translate_key[i].name);
1691 while (translate_key[++i].name);
1693 if (!translate_key[i].name)
1694 strcpy(name_buffer, "(unknown)");
1697 *name = name_buffer;
1699 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1701 static char name_buffer[30];
1704 if (key >= KSYM_A && key <= KSYM_Z)
1705 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1706 else if (key >= KSYM_a && key <= KSYM_z)
1707 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1708 else if (key >= KSYM_0 && key <= KSYM_9)
1709 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1710 #if !defined(TARGET_SDL2)
1711 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1712 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1714 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1715 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1716 else if (key == KSYM_UNDEFINED)
1717 strcpy(name_buffer, "[undefined]");
1724 if (key == translate_key[i].key)
1726 strcpy(name_buffer, translate_key[i].x11name);
1730 while (translate_key[++i].x11name);
1732 if (!translate_key[i].x11name)
1733 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1736 *x11name = name_buffer;
1738 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1740 Key key = KSYM_UNDEFINED;
1741 char *name_ptr = *name;
1743 if (strlen(*name) == 1)
1745 char c = name_ptr[0];
1747 if (c >= 'A' && c <= 'Z')
1748 key = KSYM_A + (Key)(c - 'A');
1749 else if (c >= 'a' && c <= 'z')
1750 key = KSYM_a + (Key)(c - 'a');
1751 else if (c >= '0' && c <= '9')
1752 key = KSYM_0 + (Key)(c - '0');
1755 if (key == KSYM_UNDEFINED)
1761 if (strEqual(translate_key[i].name, *name))
1763 key = translate_key[i].key;
1767 while (translate_key[++i].x11name);
1770 if (key == KSYM_UNDEFINED)
1771 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1775 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1777 Key key = KSYM_UNDEFINED;
1778 char *name_ptr = *x11name;
1780 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1782 char c = name_ptr[3];
1784 if (c >= 'A' && c <= 'Z')
1785 key = KSYM_A + (Key)(c - 'A');
1786 else if (c >= 'a' && c <= 'z')
1787 key = KSYM_a + (Key)(c - 'a');
1788 else if (c >= '0' && c <= '9')
1789 key = KSYM_0 + (Key)(c - '0');
1791 #if !defined(TARGET_SDL2)
1792 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1794 char c = name_ptr[6];
1796 if (c >= '0' && c <= '9')
1797 key = KSYM_KP_0 + (Key)(c - '0');
1800 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1802 char c1 = name_ptr[4];
1803 char c2 = name_ptr[5];
1806 if ((c1 >= '0' && c1 <= '9') &&
1807 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1808 d = atoi(&name_ptr[4]);
1810 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1811 key = KSYM_F1 + (Key)(d - 1);
1813 else if (strPrefix(name_ptr, "XK_"))
1819 if (strEqual(name_ptr, translate_key[i].x11name))
1821 key = translate_key[i].key;
1825 while (translate_key[++i].x11name);
1827 else if (strPrefix(name_ptr, "0x"))
1829 unsigned int value = 0;
1835 char c = *name_ptr++;
1838 if (c >= '0' && c <= '9')
1840 else if (c >= 'a' && c <= 'f')
1841 d = (int)(c - 'a' + 10);
1842 else if (c >= 'A' && c <= 'F')
1843 d = (int)(c - 'A' + 10);
1851 value = value * 16 + d;
1862 char *getKeyNameFromKey(Key key)
1866 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1870 char *getX11KeyNameFromKey(Key key)
1874 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1878 Key getKeyFromKeyName(char *name)
1882 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1886 Key getKeyFromX11KeyName(char *x11name)
1890 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1894 char getCharFromKey(Key key)
1900 } translate_key_char[] =
1902 /* special (non-ASCII) keys (ISO-8859-1) */
1903 { KSYM_degree, CHAR_BYTE_DEGREE },
1904 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1905 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1906 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1907 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1908 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1909 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1910 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1912 /* end-of-array identifier */
1916 char *keyname = getKeyNameFromKey(key);
1919 if (strlen(keyname) == 1)
1921 else if (strEqual(keyname, "space"))
1929 if (key == translate_key_char[i].key)
1931 c = translate_key_char[i].key_char;
1936 while (translate_key_char[++i].key_char);
1942 char getValidConfigValueChar(char c)
1944 if (c == '#' || /* used to mark comments */
1945 c == '\\') /* used to mark continued lines */
1952 /* ------------------------------------------------------------------------- */
1953 /* functions to translate string identifiers to integer or boolean value */
1954 /* ------------------------------------------------------------------------- */
1956 int get_integer_from_string(char *s)
1958 static char *number_text[][3] =
1960 { "0", "zero", "null", },
1961 { "1", "one", "first" },
1962 { "2", "two", "second" },
1963 { "3", "three", "third" },
1964 { "4", "four", "fourth" },
1965 { "5", "five", "fifth" },
1966 { "6", "six", "sixth" },
1967 { "7", "seven", "seventh" },
1968 { "8", "eight", "eighth" },
1969 { "9", "nine", "ninth" },
1970 { "10", "ten", "tenth" },
1971 { "11", "eleven", "eleventh" },
1972 { "12", "twelve", "twelfth" },
1974 { NULL, NULL, NULL },
1978 char *s_lower = getStringToLower(s);
1981 for (i = 0; number_text[i][0] != NULL; i++)
1982 for (j = 0; j < 3; j++)
1983 if (strEqual(s_lower, number_text[i][j]))
1988 if (strEqual(s_lower, "false") ||
1989 strEqual(s_lower, "no") ||
1990 strEqual(s_lower, "off"))
1992 else if (strEqual(s_lower, "true") ||
1993 strEqual(s_lower, "yes") ||
1994 strEqual(s_lower, "on"))
2005 boolean get_boolean_from_string(char *s)
2007 char *s_lower = getStringToLower(s);
2008 boolean result = FALSE;
2010 if (strEqual(s_lower, "true") ||
2011 strEqual(s_lower, "yes") ||
2012 strEqual(s_lower, "on") ||
2013 get_integer_from_string(s) == 1)
2021 int get_switch3_from_string(char *s)
2023 char *s_lower = getStringToLower(s);
2026 if (strEqual(s_lower, "true") ||
2027 strEqual(s_lower, "yes") ||
2028 strEqual(s_lower, "on") ||
2029 get_integer_from_string(s) == 1)
2031 else if (strEqual(s_lower, "auto"))
2040 /* ------------------------------------------------------------------------- */
2041 /* functions for generic lists */
2042 /* ------------------------------------------------------------------------- */
2044 ListNode *newListNode()
2046 return checked_calloc(sizeof(ListNode));
2049 void addNodeToList(ListNode **node_first, char *key, void *content)
2051 ListNode *node_new = newListNode();
2053 node_new->key = getStringCopy(key);
2054 node_new->content = content;
2055 node_new->next = *node_first;
2058 (*node_first)->prev = node_new;
2060 *node_first = node_new;
2063 void deleteNodeFromList(ListNode **node_first, char *key,
2064 void (*destructor_function)(void *))
2066 if (node_first == NULL || *node_first == NULL)
2069 if (strEqual((*node_first)->key, key))
2071 // after first recursion, (*node_first)->prev->next == *node_first,
2072 // so *node_first would be overwritten with (*node_first)->next
2073 // => use a copy of *node_first (and later of (*node_first)->next)
2074 ListNode *node = *node_first;
2075 ListNode *node_next = node->next;
2077 checked_free(node->key);
2079 if (destructor_function)
2080 destructor_function(node->content);
2083 node->prev->next = node->next;
2086 node->next->prev = node->prev;
2090 // after removing node, set list pointer to next valid list node
2091 // (this is important if the first node of the list was deleted)
2092 *node_first = node_next;
2096 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2100 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2102 if (node_first == NULL)
2105 if (strEqual(node_first->key, key))
2108 return getNodeFromKey(node_first->next, key);
2111 int getNumNodes(ListNode *node_first)
2113 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2116 void dumpList(ListNode *node_first)
2118 ListNode *node = node_first;
2122 printf("['%s' (%d)]\n", node->key,
2123 ((struct ListNodeInfo *)node->content)->num_references);
2127 printf("[%d nodes]\n", getNumNodes(node_first));
2131 /* ------------------------------------------------------------------------- */
2132 /* functions for file handling */
2133 /* ------------------------------------------------------------------------- */
2135 File *openFile(char *filename, char *mode)
2137 File *file = checked_calloc(sizeof(File));
2139 file->file = fopen(filename, mode);
2141 if (file->file != NULL)
2143 file->filename = getStringCopy(filename);
2148 #if defined(PLATFORM_ANDROID)
2149 file->asset_file = SDL_RWFromFile(filename, mode);
2151 if (file->asset_file != NULL)
2153 file->file_is_asset = TRUE;
2154 file->filename = getStringCopy(filename);
2165 int closeFile(File *file)
2172 #if defined(PLATFORM_ANDROID)
2173 if (file->asset_file)
2174 result = SDL_RWclose(file->asset_file);
2178 result = fclose(file->file);
2180 checked_free(file->filename);
2186 int checkEndOfFile(File *file)
2188 #if defined(PLATFORM_ANDROID)
2189 if (file->file_is_asset)
2190 return file->end_of_file;
2193 return feof(file->file);
2196 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2198 #if defined(PLATFORM_ANDROID)
2199 if (file->file_is_asset)
2201 if (file->end_of_file)
2204 size_t num_items_read =
2205 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2207 if (num_items_read < num_items)
2208 file->end_of_file = TRUE;
2210 return num_items_read;
2214 return fread(buffer, item_size, num_items, file->file);
2217 int seekFile(File *file, long offset, int whence)
2219 #if defined(PLATFORM_ANDROID)
2220 if (file->file_is_asset)
2222 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2223 whence == SEEK_CUR ? RW_SEEK_CUR :
2224 whence == SEEK_END ? RW_SEEK_END : 0);
2226 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2230 return fseek(file->file, offset, whence);
2233 int getByteFromFile(File *file)
2235 #if defined(PLATFORM_ANDROID)
2236 if (file->file_is_asset)
2238 if (file->end_of_file)
2242 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2244 if (num_bytes_read < 1)
2245 file->end_of_file = TRUE;
2247 return (file->end_of_file ? EOF : (int)c);
2251 return fgetc(file->file);
2254 char *getStringFromFile(File *file, char *line, int size)
2256 #if defined(PLATFORM_ANDROID)
2257 if (file->file_is_asset)
2259 if (file->end_of_file)
2262 char *line_ptr = line;
2263 int num_bytes_read = 0;
2265 while (num_bytes_read < size - 1 &&
2266 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2267 *line_ptr++ != '\n')
2272 if (strlen(line) == 0)
2274 file->end_of_file = TRUE;
2283 return fgets(line, size, file->file);
2287 /* ------------------------------------------------------------------------- */
2288 /* functions for directory handling */
2289 /* ------------------------------------------------------------------------- */
2291 Directory *openDirectory(char *dir_name)
2293 Directory *dir = checked_calloc(sizeof(Directory));
2295 dir->dir = opendir(dir_name);
2297 if (dir->dir != NULL)
2299 dir->filename = getStringCopy(dir_name);
2304 #if defined(PLATFORM_ANDROID)
2305 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2307 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2309 checked_free(asset_toc_filename);
2311 if (dir->asset_toc_file != NULL)
2313 dir->directory_is_asset = TRUE;
2314 dir->filename = getStringCopy(dir_name);
2325 int closeDirectory(Directory *dir)
2332 #if defined(PLATFORM_ANDROID)
2333 if (dir->asset_toc_file)
2334 result = SDL_RWclose(dir->asset_toc_file);
2338 result = closedir(dir->dir);
2341 freeDirectoryEntry(dir->dir_entry);
2343 checked_free(dir->filename);
2349 DirectoryEntry *readDirectory(Directory *dir)
2352 freeDirectoryEntry(dir->dir_entry);
2354 dir->dir_entry = NULL;
2356 #if defined(PLATFORM_ANDROID)
2357 if (dir->directory_is_asset)
2359 char line[MAX_LINE_LEN];
2360 char *line_ptr = line;
2361 int num_bytes_read = 0;
2363 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2364 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2373 if (strlen(line) == 0)
2376 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2378 dir->dir_entry->is_directory = FALSE;
2379 if (line[strlen(line) - 1] == '/')
2381 dir->dir_entry->is_directory = TRUE;
2383 line[strlen(line) - 1] = '\0';
2386 dir->dir_entry->basename = getStringCopy(line);
2387 dir->dir_entry->filename = getPath2(dir->filename, line);
2389 return dir->dir_entry;
2393 struct dirent *dir_entry = readdir(dir->dir);
2395 if (dir_entry == NULL)
2398 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2400 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2401 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2403 struct stat file_status;
2405 dir->dir_entry->is_directory =
2406 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2407 S_ISDIR(file_status.st_mode));
2409 return dir->dir_entry;
2412 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2414 if (dir_entry == NULL)
2417 checked_free(dir_entry->basename);
2418 checked_free(dir_entry->filename);
2419 checked_free(dir_entry);
2423 /* ------------------------------------------------------------------------- */
2424 /* functions for checking files and filenames */
2425 /* ------------------------------------------------------------------------- */
2427 boolean directoryExists(char *dir_name)
2429 if (dir_name == NULL)
2432 struct stat file_status;
2433 boolean success = (stat(dir_name, &file_status) == 0 &&
2434 S_ISDIR(file_status.st_mode));
2436 #if defined(PLATFORM_ANDROID)
2439 // this might be an asset directory; check by trying to open toc file
2440 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2441 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2443 checked_free(asset_toc_filename);
2445 success = (file != NULL);
2455 boolean fileExists(char *filename)
2457 if (filename == NULL)
2460 boolean success = (access(filename, F_OK) == 0);
2462 #if defined(PLATFORM_ANDROID)
2465 // this might be an asset file; check by trying to open it
2466 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2468 success = (file != NULL);
2478 boolean fileHasPrefix(char *basename, char *prefix)
2480 static char *basename_lower = NULL;
2481 int basename_length, prefix_length;
2483 checked_free(basename_lower);
2485 if (basename == NULL || prefix == NULL)
2488 basename_lower = getStringToLower(basename);
2489 basename_length = strlen(basename_lower);
2490 prefix_length = strlen(prefix);
2492 if (basename_length > prefix_length + 1 &&
2493 basename_lower[prefix_length] == '.' &&
2494 strncmp(basename_lower, prefix, prefix_length) == 0)
2500 boolean fileHasSuffix(char *basename, char *suffix)
2502 static char *basename_lower = NULL;
2503 int basename_length, suffix_length;
2505 checked_free(basename_lower);
2507 if (basename == NULL || suffix == NULL)
2510 basename_lower = getStringToLower(basename);
2511 basename_length = strlen(basename_lower);
2512 suffix_length = strlen(suffix);
2514 if (basename_length > suffix_length + 1 &&
2515 basename_lower[basename_length - suffix_length - 1] == '.' &&
2516 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2522 static boolean FileCouldBeArtwork(char *filename)
2524 char *basename = getBaseNamePtr(filename);
2526 return (!strEqual(basename, ".") &&
2527 !strEqual(basename, "..") &&
2528 !fileHasSuffix(basename, "txt") &&
2529 !fileHasSuffix(basename, "conf") &&
2530 !directoryExists(filename));
2533 boolean FileIsGraphic(char *filename)
2535 return FileCouldBeArtwork(filename);
2538 boolean FileIsSound(char *filename)
2540 return FileCouldBeArtwork(filename);
2543 boolean FileIsMusic(char *filename)
2545 return FileCouldBeArtwork(filename);
2548 boolean FileIsArtworkType(char *filename, int type)
2550 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2551 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2552 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2558 /* ------------------------------------------------------------------------- */
2559 /* functions for loading artwork configuration information */
2560 /* ------------------------------------------------------------------------- */
2562 char *get_mapped_token(char *token)
2564 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2565 static char *map_token_prefix[][2] =
2567 { "char_procent", "char_percent" },
2572 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2574 int len_token_prefix = strlen(map_token_prefix[i][0]);
2576 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2577 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2580 // change tokens containing ".gfx" by moving the "gfx" part to the very left
2581 char *gfx_substring = ".gfx";
2582 char *gfx_prefix = "gfx.";
2583 if (strstr(token, gfx_substring) != NULL)
2585 char *token_prefix = getStringCopy(token);
2586 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
2587 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
2590 // cut off token string at ".gfx" substring position
2591 *token_gfx_pos = '\0';
2593 // put together prefix "gfx." and token prefix and suffix without ".gfx"
2594 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
2598 return mapped_token;
2604 char *get_special_base_token(struct ArtworkListInfo *artwork_info, char *token)
2606 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2607 static struct ConfigTypeInfo prefix_list[] =
2609 { "global.anim_1" },
2610 { "global.anim_2" },
2611 { "global.anim_3" },
2612 { "global.anim_4" },
2613 { "global.anim_5" },
2614 { "global.anim_6" },
2615 { "global.anim_7" },
2616 { "global.anim_8" },
2620 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2621 boolean prefix_found = FALSE;
2625 /* search for prefix to check if base token has to be created */
2626 for (i = 0; prefix_list[i].token != NULL; i++)
2627 if (strPrefix(token, prefix_list[i].token))
2628 prefix_found = TRUE;
2633 /* search for suffix (parameter) to determine base token length */
2634 for (i = 0; suffix_list[i].token != NULL; i++)
2635 if (strSuffix(token, suffix_list[i].token))
2636 len_suffix = strlen(suffix_list[i].token);
2638 return getStringCopyN(token, strlen(token) - len_suffix);
2641 /* This function checks if a string <s> of the format "string1, string2, ..."
2642 exactly contains a string <s_contained>. */
2644 static boolean string_has_parameter(char *s, char *s_contained)
2648 if (s == NULL || s_contained == NULL)
2651 if (strlen(s_contained) > strlen(s))
2654 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2656 char next_char = s[strlen(s_contained)];
2658 /* check if next character is delimiter or whitespace */
2659 return (next_char == ',' || next_char == '\0' ||
2660 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2663 /* check if string contains another parameter string after a comma */
2664 substring = strchr(s, ',');
2665 if (substring == NULL) /* string does not contain a comma */
2668 /* advance string pointer to next character after the comma */
2671 /* skip potential whitespaces after the comma */
2672 while (*substring == ' ' || *substring == '\t')
2675 return string_has_parameter(substring, s_contained);
2678 int get_parameter_value(char *value_raw, char *suffix, int type)
2680 char *value = getStringToLower(value_raw);
2681 int result = 0; /* probably a save default value */
2683 if (strEqual(suffix, ".direction"))
2685 result = (strEqual(value, "left") ? MV_LEFT :
2686 strEqual(value, "right") ? MV_RIGHT :
2687 strEqual(value, "up") ? MV_UP :
2688 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2690 else if (strEqual(suffix, ".position"))
2692 result = (strEqual(value, "left") ? POS_LEFT :
2693 strEqual(value, "right") ? POS_RIGHT :
2694 strEqual(value, "top") ? POS_TOP :
2695 strEqual(value, "upper") ? POS_UPPER :
2696 strEqual(value, "middle") ? POS_MIDDLE :
2697 strEqual(value, "lower") ? POS_LOWER :
2698 strEqual(value, "bottom") ? POS_BOTTOM :
2699 strEqual(value, "any") ? POS_ANY : POS_UNDEFINED);
2701 else if (strEqual(suffix, ".align"))
2703 result = (strEqual(value, "left") ? ALIGN_LEFT :
2704 strEqual(value, "right") ? ALIGN_RIGHT :
2705 strEqual(value, "center") ? ALIGN_CENTER :
2706 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2708 else if (strEqual(suffix, ".valign"))
2710 result = (strEqual(value, "top") ? VALIGN_TOP :
2711 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2712 strEqual(value, "middle") ? VALIGN_MIDDLE :
2713 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2715 else if (strEqual(suffix, ".anim_mode"))
2717 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2718 string_has_parameter(value, "loop") ? ANIM_LOOP :
2719 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2720 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2721 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2722 string_has_parameter(value, "random") ? ANIM_RANDOM :
2723 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2724 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2725 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2726 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2727 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2728 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2729 string_has_parameter(value, "all") ? ANIM_ALL :
2732 if (string_has_parameter(value, "once"))
2733 result |= ANIM_ONCE;
2735 if (string_has_parameter(value, "reverse"))
2736 result |= ANIM_REVERSE;
2738 if (string_has_parameter(value, "opaque_player"))
2739 result |= ANIM_OPAQUE_PLAYER;
2741 if (string_has_parameter(value, "static_panel"))
2742 result |= ANIM_STATIC_PANEL;
2744 else if (strEqual(suffix, ".class"))
2746 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2747 get_hash_from_key(value));
2749 else if (strEqual(suffix, ".style"))
2751 result = STYLE_DEFAULT;
2753 if (string_has_parameter(value, "accurate_borders"))
2754 result |= STYLE_ACCURATE_BORDERS;
2756 if (string_has_parameter(value, "inner_corners"))
2757 result |= STYLE_INNER_CORNERS;
2759 else if (strEqual(suffix, ".fade_mode"))
2761 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2762 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2763 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2764 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2765 string_has_parameter(value, "curtain") ? FADE_MODE_CURTAIN :
2768 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2770 result = gfx.get_font_from_token_function(value);
2772 else /* generic parameter of type integer or boolean */
2774 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2775 type == TYPE_INTEGER ? get_integer_from_string(value) :
2776 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2777 ARG_UNDEFINED_VALUE);
2785 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2786 struct ListNodeInfo ***, int *);
2788 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2789 struct ConfigTypeInfo *suffix_list,
2790 char **ignore_tokens,
2791 int num_file_list_entries)
2793 struct FileInfo *file_list;
2794 int num_file_list_entries_found = 0;
2795 int num_suffix_list_entries = 0;
2799 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2801 for (i = 0; suffix_list[i].token != NULL; i++)
2802 num_suffix_list_entries++;
2804 /* always start with reliable default values */
2805 for (i = 0; i < num_file_list_entries; i++)
2807 file_list[i].token = NULL;
2809 file_list[i].default_filename = NULL;
2810 file_list[i].filename = NULL;
2812 if (num_suffix_list_entries > 0)
2814 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2816 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2817 file_list[i].parameter = checked_calloc(parameter_array_size);
2819 for (j = 0; j < num_suffix_list_entries; j++)
2821 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2822 setString(&file_list[i].parameter[j], suffix_list[j].value);
2825 file_list[i].redefined = FALSE;
2826 file_list[i].fallback_to_default = FALSE;
2827 file_list[i].default_is_cloned = FALSE;
2833 for (i = 0; config_list[i].token != NULL; i++)
2835 int len_config_token = strlen(config_list[i].token);
2836 boolean is_file_entry = TRUE;
2838 for (j = 0; suffix_list[j].token != NULL; j++)
2840 int len_suffix = strlen(suffix_list[j].token);
2842 if (len_suffix < len_config_token &&
2843 strEqual(&config_list[i].token[len_config_token - len_suffix],
2844 suffix_list[j].token))
2846 setString(&file_list[list_pos].default_parameter[j],
2847 config_list[i].value);
2849 is_file_entry = FALSE;
2855 /* the following tokens are no file definitions, but other config tokens */
2856 for (j = 0; ignore_tokens[j] != NULL; j++)
2857 if (strEqual(config_list[i].token, ignore_tokens[j]))
2858 is_file_entry = FALSE;
2865 if (list_pos >= num_file_list_entries)
2868 file_list[list_pos].token = config_list[i].token;
2869 file_list[list_pos].default_filename = config_list[i].value;
2872 if (strSuffix(config_list[i].token, ".clone_from"))
2873 file_list[list_pos].default_is_cloned = TRUE;
2876 num_file_list_entries_found = list_pos + 1;
2877 if (num_file_list_entries_found != num_file_list_entries)
2879 Error(ERR_INFO_LINE, "-");
2880 Error(ERR_INFO, "inconsistant config list information:");
2881 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2882 num_file_list_entries);
2883 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2884 num_file_list_entries_found);
2885 Error(ERR_EXIT, "please fix");
2891 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2893 int len_token = strlen(token);
2894 int len_suffix = strlen(suffix);
2896 if (start_pos < 0) /* compare suffix from end of string */
2897 start_pos += len_token;
2899 if (start_pos < 0 || start_pos + len_suffix > len_token)
2902 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2905 if (token[start_pos + len_suffix] == '\0')
2908 if (token[start_pos + len_suffix] == '.')
2914 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2916 static void read_token_parameters(SetupFileHash *setup_file_hash,
2917 struct ConfigTypeInfo *suffix_list,
2918 struct FileInfo *file_list_entry)
2920 /* check for config token that is the base token without any suffixes */
2921 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2922 char *known_token_value = KNOWN_TOKEN_VALUE;
2925 if (filename != NULL)
2927 setString(&file_list_entry->filename, filename);
2929 /* when file definition found, set all parameters to default values */
2930 for (i = 0; suffix_list[i].token != NULL; i++)
2931 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2933 file_list_entry->redefined = TRUE;
2935 /* mark config file token as well known from default config */
2936 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2939 /* check for config tokens that can be build by base token and suffixes */
2940 for (i = 0; suffix_list[i].token != NULL; i++)
2942 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2943 char *value = getHashEntry(setup_file_hash, token);
2947 setString(&file_list_entry->parameter[i], value);
2949 /* mark config file token as well known from default config */
2950 setHashEntry(setup_file_hash, token, known_token_value);
2957 static void add_dynamic_file_list_entry(struct FileInfo **list,
2958 int *num_list_entries,
2959 SetupFileHash *extra_file_hash,
2960 struct ConfigTypeInfo *suffix_list,
2961 int num_suffix_list_entries,
2964 struct FileInfo *new_list_entry;
2965 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2967 (*num_list_entries)++;
2968 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2969 new_list_entry = &(*list)[*num_list_entries - 1];
2971 new_list_entry->token = getStringCopy(token);
2972 new_list_entry->default_filename = NULL;
2973 new_list_entry->filename = NULL;
2974 new_list_entry->parameter = checked_calloc(parameter_array_size);
2976 new_list_entry->redefined = FALSE;
2977 new_list_entry->fallback_to_default = FALSE;
2978 new_list_entry->default_is_cloned = FALSE;
2980 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2983 static void add_property_mapping(struct PropertyMapping **list,
2984 int *num_list_entries,
2985 int base_index, int ext1_index,
2986 int ext2_index, int ext3_index,
2989 struct PropertyMapping *new_list_entry;
2991 (*num_list_entries)++;
2992 *list = checked_realloc(*list,
2993 *num_list_entries * sizeof(struct PropertyMapping));
2994 new_list_entry = &(*list)[*num_list_entries - 1];
2996 new_list_entry->base_index = base_index;
2997 new_list_entry->ext1_index = ext1_index;
2998 new_list_entry->ext2_index = ext2_index;
2999 new_list_entry->ext3_index = ext3_index;
3001 new_list_entry->artwork_index = artwork_index;
3004 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3007 struct FileInfo *file_list = artwork_info->file_list;
3008 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3009 char **base_prefixes = artwork_info->base_prefixes;
3010 char **ext1_suffixes = artwork_info->ext1_suffixes;
3011 char **ext2_suffixes = artwork_info->ext2_suffixes;
3012 char **ext3_suffixes = artwork_info->ext3_suffixes;
3013 char **ignore_tokens = artwork_info->ignore_tokens;
3014 int num_file_list_entries = artwork_info->num_file_list_entries;
3015 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3016 int num_base_prefixes = artwork_info->num_base_prefixes;
3017 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3018 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3019 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3020 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3021 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3022 SetupFileHash *extra_file_hash, *empty_file_hash;
3023 char *known_token_value = KNOWN_TOKEN_VALUE;
3024 char *base_token_value = UNDEFINED_FILENAME;
3027 if (filename == NULL)
3030 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3033 /* separate valid (defined) from empty (undefined) config token values */
3034 valid_file_hash = newSetupFileHash();
3035 empty_file_hash = newSetupFileHash();
3036 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3038 char *value = HASH_ITERATION_VALUE(itr);
3040 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3041 HASH_ITERATION_TOKEN(itr), value);
3043 END_HASH_ITERATION(setup_file_hash, itr)
3045 /* at this point, we do not need the setup file hash anymore -- free it */
3046 freeSetupFileHash(setup_file_hash);
3048 /* prevent changing hash while iterating over it by using a temporary copy */
3049 valid_file_hash_tmp = newSetupFileHash();
3050 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3052 setHashEntry(valid_file_hash_tmp,
3053 HASH_ITERATION_TOKEN(itr),
3054 HASH_ITERATION_VALUE(itr));
3056 END_HASH_ITERATION(valid_file_hash, itr)
3058 /* (iterate over same temporary hash, as modifications are independent) */
3060 /* map deprecated to current tokens (using prefix match and replace) */
3061 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3063 char *token = HASH_ITERATION_TOKEN(itr);
3064 char *mapped_token = get_mapped_token(token);
3066 if (mapped_token != NULL)
3068 char *value = HASH_ITERATION_VALUE(itr);
3070 /* add mapped token */
3071 setHashEntry(valid_file_hash, mapped_token, value);
3073 /* ignore old token (by setting it to "known" keyword) */
3074 setHashEntry(valid_file_hash, token, known_token_value);
3079 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3081 /* add special base tokens (using prefix match and replace) */
3082 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3084 char *token = HASH_ITERATION_TOKEN(itr);
3085 char *base_token = get_special_base_token(artwork_info, token);
3087 if (base_token != NULL)
3089 /* add base token only if it does not already exist */
3090 if (getHashEntry(valid_file_hash, base_token) == NULL)
3091 setHashEntry(valid_file_hash, base_token, base_token_value);
3096 END_HASH_ITERATION(valid_file_hash_tmp, itr)
3098 /* free temporary hash used for iteration */
3099 freeSetupFileHash(valid_file_hash_tmp);
3101 /* read parameters for all known config file tokens */
3102 for (i = 0; i < num_file_list_entries; i++)
3103 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3105 /* set all tokens that can be ignored here to "known" keyword */
3106 for (i = 0; i < num_ignore_tokens; i++)
3107 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3109 /* copy all unknown config file tokens to extra config hash */
3110 extra_file_hash = newSetupFileHash();
3111 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3113 char *value = HASH_ITERATION_VALUE(itr);
3115 if (!strEqual(value, known_token_value))
3116 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3118 END_HASH_ITERATION(valid_file_hash, itr)
3120 /* at this point, we do not need the valid file hash anymore -- free it */
3121 freeSetupFileHash(valid_file_hash);
3123 /* now try to determine valid, dynamically defined config tokens */
3125 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3127 struct FileInfo **dynamic_file_list =
3128 &artwork_info->dynamic_file_list;
3129 int *num_dynamic_file_list_entries =
3130 &artwork_info->num_dynamic_file_list_entries;
3131 struct PropertyMapping **property_mapping =
3132 &artwork_info->property_mapping;
3133 int *num_property_mapping_entries =
3134 &artwork_info->num_property_mapping_entries;
3135 int current_summarized_file_list_entry =
3136 artwork_info->num_file_list_entries +
3137 artwork_info->num_dynamic_file_list_entries;
3138 char *token = HASH_ITERATION_TOKEN(itr);
3139 int len_token = strlen(token);
3141 boolean base_prefix_found = FALSE;
3142 boolean parameter_suffix_found = FALSE;
3144 /* skip all parameter definitions (handled by read_token_parameters()) */
3145 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3147 int len_suffix = strlen(suffix_list[i].token);
3149 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3150 parameter_suffix_found = TRUE;
3153 if (parameter_suffix_found)
3156 /* ---------- step 0: search for matching base prefix ---------- */
3159 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3161 char *base_prefix = base_prefixes[i];
3162 int len_base_prefix = strlen(base_prefix);
3163 boolean ext1_suffix_found = FALSE;
3164 boolean ext2_suffix_found = FALSE;
3165 boolean ext3_suffix_found = FALSE;
3166 boolean exact_match = FALSE;
3167 int base_index = -1;
3168 int ext1_index = -1;
3169 int ext2_index = -1;
3170 int ext3_index = -1;
3172 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3174 if (!base_prefix_found)
3179 if (start_pos + len_base_prefix == len_token) /* exact match */
3183 add_dynamic_file_list_entry(dynamic_file_list,
3184 num_dynamic_file_list_entries,
3187 num_suffix_list_entries,
3189 add_property_mapping(property_mapping,
3190 num_property_mapping_entries,
3191 base_index, -1, -1, -1,
3192 current_summarized_file_list_entry);
3196 /* ---------- step 1: search for matching first suffix ---------- */
3198 start_pos += len_base_prefix;
3199 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3201 char *ext1_suffix = ext1_suffixes[j];
3202 int len_ext1_suffix = strlen(ext1_suffix);
3204 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3206 if (!ext1_suffix_found)
3211 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3215 add_dynamic_file_list_entry(dynamic_file_list,
3216 num_dynamic_file_list_entries,
3219 num_suffix_list_entries,
3221 add_property_mapping(property_mapping,
3222 num_property_mapping_entries,
3223 base_index, ext1_index, -1, -1,
3224 current_summarized_file_list_entry);
3228 start_pos += len_ext1_suffix;
3234 /* ---------- step 2: search for matching second suffix ---------- */
3236 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3238 char *ext2_suffix = ext2_suffixes[k];
3239 int len_ext2_suffix = strlen(ext2_suffix);
3241 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3243 if (!ext2_suffix_found)
3248 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3252 add_dynamic_file_list_entry(dynamic_file_list,
3253 num_dynamic_file_list_entries,
3256 num_suffix_list_entries,
3258 add_property_mapping(property_mapping,
3259 num_property_mapping_entries,
3260 base_index, ext1_index, ext2_index, -1,
3261 current_summarized_file_list_entry);
3265 start_pos += len_ext2_suffix;
3271 /* ---------- step 3: search for matching third suffix ---------- */
3273 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3275 char *ext3_suffix = ext3_suffixes[l];
3276 int len_ext3_suffix = strlen(ext3_suffix);
3278 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3280 if (!ext3_suffix_found)
3285 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3289 add_dynamic_file_list_entry(dynamic_file_list,
3290 num_dynamic_file_list_entries,
3293 num_suffix_list_entries,
3295 add_property_mapping(property_mapping,
3296 num_property_mapping_entries,
3297 base_index, ext1_index, ext2_index, ext3_index,
3298 current_summarized_file_list_entry);
3304 END_HASH_ITERATION(extra_file_hash, itr)
3306 if (artwork_info->num_dynamic_file_list_entries > 0)
3308 artwork_info->dynamic_artwork_list =
3309 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3310 artwork_info->sizeof_artwork_list_entry);
3313 if (options.verbose && IS_PARENT_PROCESS())
3315 SetupFileList *setup_file_list, *list;
3316 boolean dynamic_tokens_found = FALSE;
3317 boolean unknown_tokens_found = FALSE;
3318 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3320 /* list may be NULL for empty artwork config files */
3321 setup_file_list = loadSetupFileList(filename);
3323 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3325 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3326 dynamic_tokens_found = TRUE;
3328 unknown_tokens_found = TRUE;
3330 END_HASH_ITERATION(extra_file_hash, itr)
3332 if (options.debug && dynamic_tokens_found)
3334 Error(ERR_INFO_LINE, "-");
3335 Error(ERR_INFO, "dynamic token(s) found in config file:");
3336 Error(ERR_INFO, "- config file: '%s'", filename);
3338 for (list = setup_file_list; list != NULL; list = list->next)
3340 char *value = getHashEntry(extra_file_hash, list->token);
3342 if (value != NULL && strEqual(value, known_token_value))
3343 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3346 Error(ERR_INFO_LINE, "-");
3349 if (unknown_tokens_found)
3351 Error(ERR_INFO_LINE, "-");
3352 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3353 Error(ERR_INFO, "- config file: '%s'", filename);
3355 for (list = setup_file_list; list != NULL; list = list->next)
3357 char *value = getHashEntry(extra_file_hash, list->token);
3359 if (value != NULL && !strEqual(value, known_token_value))
3360 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3363 Error(ERR_INFO_LINE, "-");
3366 if (undefined_values_found)
3368 Error(ERR_INFO_LINE, "-");
3369 Error(ERR_INFO, "warning: undefined values found in config file:");
3370 Error(ERR_INFO, "- config file: '%s'", filename);
3372 for (list = setup_file_list; list != NULL; list = list->next)
3374 char *value = getHashEntry(empty_file_hash, list->token);
3377 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3380 Error(ERR_INFO_LINE, "-");
3383 freeSetupFileList(setup_file_list);
3386 freeSetupFileHash(extra_file_hash);
3387 freeSetupFileHash(empty_file_hash);
3390 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3392 struct FileInfo *file_list = artwork_info->file_list;
3393 int num_file_list_entries = artwork_info->num_file_list_entries;
3394 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3395 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3398 DrawInitText("Loading artwork config", 120, FC_GREEN);
3399 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3401 /* always start with reliable default values */
3402 for (i = 0; i < num_file_list_entries; i++)
3404 setString(&file_list[i].filename, file_list[i].default_filename);
3406 for (j = 0; j < num_suffix_list_entries; j++)
3407 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3409 file_list[i].redefined = FALSE;
3410 file_list[i].fallback_to_default = FALSE;
3413 /* free previous dynamic artwork file array */
3414 if (artwork_info->dynamic_file_list != NULL)
3416 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3418 free(artwork_info->dynamic_file_list[i].token);
3419 free(artwork_info->dynamic_file_list[i].filename);
3420 free(artwork_info->dynamic_file_list[i].parameter);
3423 free(artwork_info->dynamic_file_list);
3424 artwork_info->dynamic_file_list = NULL;
3426 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3427 &artwork_info->num_dynamic_file_list_entries);
3430 /* free previous property mapping */
3431 if (artwork_info->property_mapping != NULL)
3433 free(artwork_info->property_mapping);
3435 artwork_info->property_mapping = NULL;
3436 artwork_info->num_property_mapping_entries = 0;
3439 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3441 /* first look for special artwork configured in level series config */
3442 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3444 if (fileExists(filename_base))
3445 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3448 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3450 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3451 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3454 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3455 struct ListNodeInfo **listnode)
3459 char *filename = (*listnode)->source_filename;
3461 if (--(*listnode)->num_references <= 0)
3462 deleteNodeFromList(&artwork_info->content_list, filename,
3463 artwork_info->free_artwork);
3469 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3470 struct ListNodeInfo **listnode,
3471 struct FileInfo *file_list_entry)
3481 char *basename = file_list_entry->filename;
3482 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3484 if (filename == NULL)
3486 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3488 basename = file_list_entry->default_filename;
3490 /* fail for cloned default artwork that has no default filename defined */
3491 if (file_list_entry->default_is_cloned &&
3492 strEqual(basename, UNDEFINED_FILENAME))
3494 int error_mode = ERR_WARN;
3496 /* we can get away without sounds and music, but not without graphics */
3497 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3498 error_mode = ERR_EXIT;
3500 Error(error_mode, "token '%s' was cloned and has no default filename",
3501 file_list_entry->token);
3506 /* dynamic artwork has no default filename / skip empty default artwork */
3507 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3510 file_list_entry->fallback_to_default = TRUE;
3512 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3514 filename = getCustomArtworkFilename(basename, artwork_info->type);
3516 if (filename == NULL)
3518 int error_mode = ERR_WARN;
3520 /* we can get away without sounds and music, but not without graphics */
3521 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3522 error_mode = ERR_EXIT;
3524 Error(error_mode, "cannot find default artwork file '%s'", basename);
3530 /* check if the old and the new artwork file are the same */
3531 if (*listnode && strEqual((*listnode)->source_filename, filename))
3533 /* The old and new artwork are the same (have the same filename and path).
3534 This usually means that this artwork does not exist in this artwork set
3535 and a fallback to the existing artwork is done. */
3540 /* delete existing artwork file entry */
3541 deleteArtworkListEntry(artwork_info, listnode);
3543 /* check if the new artwork file already exists in the list of artwork */
3544 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3546 *listnode = (struct ListNodeInfo *)node->content;
3547 (*listnode)->num_references++;
3552 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3553 DrawInitText(basename, 150, FC_YELLOW);
3555 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3557 /* add new artwork file entry to the list of artwork files */
3558 (*listnode)->num_references = 1;
3559 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3564 int error_mode = ERR_WARN;
3566 /* we can get away without sounds and music, but not without graphics */
3567 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3568 error_mode = ERR_EXIT;
3570 Error(error_mode, "cannot load artwork file '%s'", basename);
3576 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3577 struct ListNodeInfo **listnode,
3578 struct FileInfo *file_list_entry)
3580 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3582 deleteArtworkListEntry(artwork_info, listnode);
3587 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3590 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3592 struct FileInfo *file_list = artwork_info->file_list;
3593 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3594 int num_file_list_entries = artwork_info->num_file_list_entries;
3595 int num_dynamic_file_list_entries =
3596 artwork_info->num_dynamic_file_list_entries;
3599 print_timestamp_init("ReloadCustomArtworkList");
3601 for (i = 0; i < num_file_list_entries; i++)
3602 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3605 for (i = 0; i < num_dynamic_file_list_entries; i++)
3606 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3607 &dynamic_file_list[i]);
3609 print_timestamp_done("ReloadCustomArtworkList");
3612 dumpList(artwork_info->content_list);
3616 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3617 struct ListNodeInfo ***list,
3618 int *num_list_entries)
3625 for (i = 0; i < *num_list_entries; i++)
3626 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3630 *num_list_entries = 0;
3633 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3635 if (artwork_info == NULL)
3638 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3639 &artwork_info->num_file_list_entries);
3641 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3642 &artwork_info->num_dynamic_file_list_entries);
3646 /* ------------------------------------------------------------------------- */
3647 /* functions only needed for non-Unix (non-command-line) systems */
3648 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3649 /* (now also added for Windows, to create files in user data directory) */
3650 /* ------------------------------------------------------------------------- */
3652 char *getLogFilename(char *basename)
3654 return getPath2(getUserGameDataDir(), basename);
3661 InitUserDataDirectory();
3663 for (i = 0; i < NUM_LOGS; i++)
3665 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3668 program.log_file[i] = program.log_file_default[i]; // reset to default
3670 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3671 program.log_filename[i], strerror(errno));
3674 /* output should be unbuffered so it is not truncated in a crash */
3675 setbuf(program.log_file[i], NULL);
3679 void CloseLogFiles()
3683 for (i = 0; i < NUM_LOGS; i++)
3684 if (program.log_file[i] != program.log_file_default[i])
3685 fclose(program.log_file[i]);
3688 void DumpLogFile(int nr)
3690 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3692 if (log_file == NULL)
3695 while (!feof(log_file))
3696 fputc(fgetc(log_file), stdout);
3701 void NotifyUserAboutErrorFile()
3703 #if defined(PLATFORM_WIN32)
3704 char *title_text = getStringCat2(program.program_title, " Error Message");
3705 char *error_text = getStringCat2("The program was aborted due to an error; "
3706 "for details, see the following error file:"
3708 program.log_filename[LOG_ERR_ID]);
3710 MessageBox(NULL, error_text, title_text, MB_OK);
3715 /* ------------------------------------------------------------------------- */
3716 /* the following is only for debugging purpose and normally not used */
3717 /* ------------------------------------------------------------------------- */
3721 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3722 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3724 #define DEBUG_NUM_TIMESTAMPS 10
3725 #define DEBUG_TIME_IN_MICROSECONDS 0
3727 #if DEBUG_TIME_IN_MICROSECONDS
3728 static double Counter_Microseconds()
3730 static struct timeval base_time = { 0, 0 };
3731 struct timeval current_time;
3734 gettimeofday(¤t_time, NULL);
3736 /* reset base time in case of wrap-around */
3737 if (current_time.tv_sec < base_time.tv_sec)
3738 base_time = current_time;
3741 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3742 ((double)(current_time.tv_usec - base_time.tv_usec));
3744 return counter; /* return microseconds since last init */
3748 char *debug_print_timestamp_get_padding(int padding_size)
3750 static char *padding = NULL;
3751 int max_padding_size = 100;
3753 if (padding == NULL)
3755 padding = checked_calloc(max_padding_size + 1);
3756 memset(padding, ' ', max_padding_size);
3759 return &padding[MAX(0, max_padding_size - padding_size)];
3762 void debug_print_timestamp(int counter_nr, char *message)
3764 int indent_size = 8;
3765 int padding_size = 40;
3766 float timestamp_interval;
3769 Error(ERR_EXIT, "debugging: invalid negative counter");
3770 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3771 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3773 #if DEBUG_TIME_IN_MICROSECONDS
3774 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3777 counter[counter_nr][0] = Counter_Microseconds();
3779 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3782 counter[counter_nr][0] = Counter();
3785 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3786 counter[counter_nr][1] = counter[counter_nr][0];
3789 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3790 debug_print_timestamp_get_padding(counter_nr * indent_size),
3792 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3793 timestamp_interval / 1000,
3797 void debug_print_parent_only(char *format, ...)
3799 if (!IS_PARENT_PROCESS())
3806 va_start(ap, format);
3807 vprintf(format, ap);
3816 void print_timestamp_ext(char *message, char *mode)
3818 #if DEBUG_PRINT_INIT_TIMESTAMPS
3819 static char *debug_message = NULL;
3820 static char *last_message = NULL;
3821 static int counter_nr = 0;
3822 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3824 checked_free(debug_message);
3825 debug_message = getStringCat3(mode, " ", message);
3827 if (strEqual(mode, "INIT"))
3829 debug_print_timestamp(counter_nr, NULL);
3831 if (counter_nr + 1 < max_depth)
3832 debug_print_timestamp(counter_nr, debug_message);
3836 debug_print_timestamp(counter_nr, NULL);
3838 else if (strEqual(mode, "DONE"))
3842 if (counter_nr + 1 < max_depth ||
3843 (counter_nr == 0 && max_depth == 1))
3845 last_message = message;
3847 if (counter_nr == 0 && max_depth == 1)
3849 checked_free(debug_message);
3850 debug_message = getStringCat3("TIME", " ", message);
3853 debug_print_timestamp(counter_nr, debug_message);
3856 else if (!strEqual(mode, "TIME") ||
3857 !strEqual(message, last_message))
3859 if (counter_nr < max_depth)
3860 debug_print_timestamp(counter_nr, debug_message);
3865 void print_timestamp_init(char *message)
3867 print_timestamp_ext(message, "INIT");
3870 void print_timestamp_time(char *message)
3872 print_timestamp_ext(message, "TIME");
3875 void print_timestamp_done(char *message)
3877 print_timestamp_ext(message, "DONE");