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 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
364 /* we want to wait only a few ms -- if we assume that we have a
365 kernel timer resolution of 10 ms, we would wait far too long;
366 therefore it's better to do a short interval of busy waiting
367 to get our sleeping time more accurate */
369 unsigned int base_counter = Counter(), actual_counter = Counter();
371 while (actual_counter < base_counter + milliseconds_delay &&
372 actual_counter >= base_counter)
373 actual_counter = Counter();
377 SDL_Delay(milliseconds_delay);
381 void Delay(unsigned int delay) /* Sleep specified number of milliseconds */
383 sleep_milliseconds(delay);
386 boolean FrameReached(unsigned int *frame_counter_var,
387 unsigned int frame_delay)
389 unsigned int actual_frame_counter = FrameCounter;
391 if (actual_frame_counter >= *frame_counter_var &&
392 actual_frame_counter < *frame_counter_var + frame_delay)
395 *frame_counter_var = actual_frame_counter;
400 boolean DelayReached(unsigned int *counter_var,
403 unsigned int actual_counter = Counter();
405 if (actual_counter >= *counter_var &&
406 actual_counter < *counter_var + delay)
409 *counter_var = actual_counter;
414 int WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
416 unsigned int actual_counter;
421 actual_counter = Counter();
423 if (actual_counter >= *counter_var &&
424 actual_counter < *counter_var + delay)
425 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
430 if (*counter_var != 0 &&
432 actual_counter >= *counter_var + delay)
434 int lag = actual_counter - (*counter_var + delay);
435 int delay2 = (delay + 1) / 2;
438 skip_frames = (lag + delay2) / delay;
441 *counter_var = actual_counter;
446 void SkipUntilDelayReached(unsigned int *counter_var, unsigned int delay,
447 int *loop_var, int last_loop_value)
449 int skip_frames = WaitUntilDelayReached(counter_var, delay);
453 printf("::: %d: %d ms", *loop_var, delay);
455 printf(" -> SKIP %d FRAME(S) [%d ms]", skip_frames, skip_frames * delay);
460 if (skip_frames == 0)
463 // when skipping frames, make sure to never skip the last frame, as
464 // this may be needed for animations to reach a defined end state;
465 // furthermore, we assume that this function is called at the end
466 // of a "for" loop, which continues by incrementing the loop variable
467 // by one before checking the loop condition again; therefore we have
468 // to check against the last loop value minus one here
472 if (*loop_var < last_loop_value) // never skip the last frame
474 *loop_var += skip_frames;
476 if (*loop_var > last_loop_value) // never skip the last frame
477 *loop_var = last_loop_value;
482 /* ------------------------------------------------------------------------- */
483 /* random generator functions */
484 /* ------------------------------------------------------------------------- */
486 unsigned int init_random_number(int nr, int seed)
488 if (seed == NEW_RANDOMIZE)
490 /* default random seed */
491 seed = (int)time(NULL); // seconds since the epoch
493 #if !defined(PLATFORM_WIN32)
494 /* add some more randomness */
495 struct timeval current_time;
497 gettimeofday(¤t_time, NULL);
499 seed += (int)current_time.tv_usec; // microseconds since the epoch
502 /* add some more randomness */
503 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
505 /* add some more randomness */
506 seed += GetSimpleRandom(1000000);
509 srandom_linux_libc(nr, (unsigned int) seed);
511 return (unsigned int) seed;
514 unsigned int get_random_number(int nr, int max)
516 return (max > 0 ? random_linux_libc(nr) % max : 0);
520 /* ------------------------------------------------------------------------- */
521 /* system info functions */
522 /* ------------------------------------------------------------------------- */
524 #if !defined(PLATFORM_ANDROID)
525 static char *get_corrected_real_name(char *real_name)
527 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
528 char *from_ptr = real_name;
529 char *to_ptr = real_name_new;
531 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
532 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
534 /* the name field read from "passwd" file may also contain additional
535 user information, separated by commas, which will be removed here */
536 if (*from_ptr == ',')
539 /* the user's real name may contain 'german sharp s' characters,
540 which have no equivalent in upper case letters (used by our fonts) */
541 if (*from_ptr == CHAR_BYTE_SHARP_S)
548 *to_ptr++ = *from_ptr++;
553 return real_name_new;
559 static char *login_name = NULL;
561 #if defined(PLATFORM_WIN32)
562 if (login_name == NULL)
564 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
565 login_name = checked_malloc(buffer_size);
567 if (GetUserName(login_name, &buffer_size) == 0)
568 strcpy(login_name, ANONYMOUS_NAME);
571 if (login_name == NULL)
575 if ((pwd = getpwuid(getuid())) == NULL)
576 login_name = ANONYMOUS_NAME;
578 login_name = getStringCopy(pwd->pw_name);
587 static char *real_name = NULL;
589 #if defined(PLATFORM_WIN32)
590 if (real_name == NULL)
592 static char buffer[MAX_USERNAME_LEN + 1];
593 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
595 if (GetUserName(buffer, &buffer_size) != 0)
596 real_name = get_corrected_real_name(buffer);
598 real_name = ANONYMOUS_NAME;
600 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
601 if (real_name == NULL)
605 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
606 real_name = get_corrected_real_name(pwd->pw_gecos);
608 real_name = ANONYMOUS_NAME;
611 real_name = ANONYMOUS_NAME;
617 time_t getFileTimestampEpochSeconds(char *filename)
619 struct stat file_status;
621 if (stat(filename, &file_status) != 0) /* cannot stat file */
624 return file_status.st_mtime;
628 /* ------------------------------------------------------------------------- */
629 /* path manipulation functions */
630 /* ------------------------------------------------------------------------- */
632 static char *getLastPathSeparatorPtr(char *filename)
634 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
636 if (last_separator == NULL) /* also try DOS/Windows variant */
637 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
639 return last_separator;
642 char *getBaseNamePtr(char *filename)
644 char *last_separator = getLastPathSeparatorPtr(filename);
646 if (last_separator != NULL)
647 return last_separator + 1; /* separator found: strip base path */
649 return filename; /* no separator found: filename has no path */
652 char *getBaseName(char *filename)
654 return getStringCopy(getBaseNamePtr(filename));
657 char *getBaseNameNoSuffix(char *filename)
659 char *basename = getStringCopy(getBaseNamePtr(filename));
661 // remove trailing suffix (separated by dot or hyphen)
662 if (basename[0] != '.' && basename[0] != '-')
664 if (strchr(basename, '.') != NULL)
665 *strchr(basename, '.') = '\0';
667 if (strchr(basename, '-') != NULL)
668 *strchr(basename, '-') = '\0';
674 char *getBasePath(char *filename)
676 char *basepath = getStringCopy(filename);
677 char *last_separator = getLastPathSeparatorPtr(basepath);
679 if (last_separator != NULL)
680 *last_separator = '\0'; /* separator found: strip basename */
682 basepath = "."; /* no separator found: use current path */
687 static char *getProgramMainDataPath()
689 char *main_data_path = getStringCopy(program.command_basepath);
691 #if defined(PLATFORM_MACOSX)
692 static char *main_data_binary_subdir = NULL;
694 if (main_data_binary_subdir == NULL)
696 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
698 strlen(MAC_APP_BINARY_SUBDIR) + 1);
700 sprintf(main_data_binary_subdir, "%s.app/%s",
701 program.program_title, MAC_APP_BINARY_SUBDIR);
704 // cut relative path to Mac OS X application binary directory from path
705 if (strSuffix(main_data_path, main_data_binary_subdir))
706 main_data_path[strlen(main_data_path) -
707 strlen(main_data_binary_subdir)] = '\0';
709 // cut trailing path separator from path (but not if path is root directory)
710 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
711 main_data_path[strlen(main_data_path) - 1] = '\0';
714 return main_data_path;
718 /* ------------------------------------------------------------------------- */
719 /* various string functions */
720 /* ------------------------------------------------------------------------- */
722 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
724 if (s1 == NULL || s2 == NULL || sep == NULL)
727 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
730 sprintf(complete_string, "%s%s%s", s1, sep, s2);
732 return complete_string;
735 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
737 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
740 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
741 strlen(s2) + strlen(sep) +
744 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
746 return complete_string;
749 char *getStringCat2(char *s1, char *s2)
751 return getStringCat2WithSeparator(s1, s2, "");
754 char *getStringCat3(char *s1, char *s2, char *s3)
756 return getStringCat3WithSeparator(s1, s2, s3, "");
759 char *getPath2(char *path1, char *path2)
761 #if defined(PLATFORM_ANDROID)
762 // workaround for reading from assets directory -- skip "." subdirs in path
763 if (strEqual(path1, "."))
764 return getStringCopy(path2);
765 else if (strEqual(path2, "."))
766 return getStringCopy(path1);
769 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
772 char *getPath3(char *path1, char *path2, char *path3)
774 #if defined(PLATFORM_ANDROID)
775 // workaround for reading from assets directory -- skip "." subdirs in path
776 if (strEqual(path1, "."))
777 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
778 else if (strEqual(path2, "."))
779 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
780 else if (strEqual(path3, "."))
781 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
784 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
787 char *getImg2(char *path1, char *path2)
789 char *filename = getPath2(path1, path2);
791 if (!fileExists(filename) && strSuffix(path2, ".png"))
793 // backward compatibility: if PNG file not found, check for PCX file
794 char *path2pcx = getStringCopy(path2);
796 strcpy(&path2pcx[strlen(path2pcx) - 3], "pcx");
800 filename = getPath2(path1, path2pcx);
808 char *getImg3(char *path1, char *path2, char *path3)
810 char *filename = getPath3(path1, path2, path3);
812 if (!fileExists(filename) && strSuffix(path3, ".png"))
814 // backward compatibility: if PNG file not found, check for PCX file
815 char *path3pcx = getStringCopy(path3);
817 strcpy(&path3pcx[strlen(path3pcx) - 3], "pcx");
821 filename = getPath3(path1, path2, path3pcx);
829 char *getStringCopy(const char *s)
836 s_copy = checked_malloc(strlen(s) + 1);
842 char *getStringCopyN(const char *s, int n)
845 int s_len = MAX(0, n);
850 s_copy = checked_malloc(s_len + 1);
851 strncpy(s_copy, s, s_len);
852 s_copy[s_len] = '\0';
857 char *getStringCopyNStatic(const char *s, int n)
859 static char *s_copy = NULL;
861 checked_free(s_copy);
863 s_copy = getStringCopyN(s, n);
868 char *getStringToLower(const char *s)
870 char *s_copy = checked_malloc(strlen(s) + 1);
871 char *s_ptr = s_copy;
874 *s_ptr++ = tolower(*s++);
880 void setString(char **old_value, char *new_value)
882 checked_free(*old_value);
884 *old_value = getStringCopy(new_value);
887 boolean strEqual(char *s1, char *s2)
889 return (s1 == NULL && s2 == NULL ? TRUE :
890 s1 == NULL && s2 != NULL ? FALSE :
891 s1 != NULL && s2 == NULL ? FALSE :
892 strcmp(s1, s2) == 0);
895 boolean strEqualN(char *s1, char *s2, int n)
897 return (s1 == NULL && s2 == NULL ? TRUE :
898 s1 == NULL && s2 != NULL ? FALSE :
899 s1 != NULL && s2 == NULL ? FALSE :
900 strncmp(s1, s2, n) == 0);
903 boolean strPrefix(char *s, char *prefix)
905 return (s == NULL && prefix == NULL ? TRUE :
906 s == NULL && prefix != NULL ? FALSE :
907 s != NULL && prefix == NULL ? FALSE :
908 strncmp(s, prefix, strlen(prefix)) == 0);
911 boolean strSuffix(char *s, char *suffix)
913 return (s == NULL && suffix == NULL ? TRUE :
914 s == NULL && suffix != NULL ? FALSE :
915 s != NULL && suffix == NULL ? FALSE :
916 strlen(s) < strlen(suffix) ? FALSE :
917 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
920 boolean strPrefixLower(char *s, char *prefix)
922 char *s_lower = getStringToLower(s);
923 boolean match = strPrefix(s_lower, prefix);
930 boolean strSuffixLower(char *s, char *suffix)
932 char *s_lower = getStringToLower(s);
933 boolean match = strSuffix(s_lower, suffix);
941 /* ------------------------------------------------------------------------- */
942 /* command line option handling functions */
943 /* ------------------------------------------------------------------------- */
945 void GetOptions(int argc, char *argv[],
946 void (*print_usage_function)(void),
947 void (*print_version_function)(void))
949 char *ro_base_path = RO_BASE_PATH;
950 char *rw_base_path = RW_BASE_PATH;
951 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
952 char **options_left = &argvplus[1];
954 /* replace original "argv" with null-terminated array of string pointers */
956 argvplus[argc] = argv[argc];
958 /* if the program is configured to start from current directory (default),
959 determine program package directory from program binary (some versions
960 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
961 set the current working directory to the program package directory) */
963 if (strEqual(ro_base_path, "."))
964 ro_base_path = getProgramMainDataPath();
965 if (strEqual(rw_base_path, "."))
966 rw_base_path = getProgramMainDataPath();
968 /* initialize global program options */
969 options.display_name = NULL;
970 options.server_host = NULL;
971 options.server_port = 0;
973 options.ro_base_directory = ro_base_path;
974 options.rw_base_directory = rw_base_path;
975 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
976 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
977 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
978 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
979 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
981 options.execute_command = NULL;
982 options.special_flags = NULL;
984 options.serveronly = FALSE;
985 options.network = FALSE;
986 options.verbose = FALSE;
987 options.debug = FALSE;
990 options.verbose = TRUE;
992 #if !defined(PLATFORM_UNIX)
993 if (*options_left == NULL) /* no options given -- enable verbose mode */
994 options.verbose = TRUE;
998 while (*options_left)
1000 char option_str[MAX_OPTION_LEN];
1001 char *option = options_left[0];
1002 char *next_option = options_left[1];
1003 char *option_arg = NULL;
1004 int option_len = strlen(option);
1006 if (option_len >= MAX_OPTION_LEN)
1007 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1009 strcpy(option_str, option); /* copy argument into buffer */
1010 option = option_str;
1012 if (strEqual(option, "--")) /* stop scanning arguments */
1015 if (strPrefix(option, "--")) /* treat '--' like '-' */
1018 option_arg = strchr(option, '=');
1019 if (option_arg == NULL) /* no '=' in option */
1020 option_arg = next_option;
1023 *option_arg++ = '\0'; /* cut argument from option */
1024 if (*option_arg == '\0') /* no argument after '=' */
1025 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
1028 option_len = strlen(option);
1030 if (strEqual(option, "-"))
1032 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1034 else if (strncmp(option, "-help", option_len) == 0)
1036 print_usage_function();
1040 else if (strncmp(option, "-display", option_len) == 0)
1042 if (option_arg == NULL)
1043 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1045 options.display_name = option_arg;
1046 if (option_arg == next_option)
1049 else if (strncmp(option, "-basepath", option_len) == 0)
1051 if (option_arg == NULL)
1052 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1054 /* this should be extended to separate options for ro and rw data */
1055 options.ro_base_directory = ro_base_path = option_arg;
1056 options.rw_base_directory = rw_base_path = option_arg;
1057 if (option_arg == next_option)
1060 /* adjust paths for sub-directories in base directory accordingly */
1061 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1062 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1063 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1064 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1065 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1067 else if (strncmp(option, "-levels", option_len) == 0)
1069 if (option_arg == NULL)
1070 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1072 options.level_directory = option_arg;
1073 if (option_arg == next_option)
1076 else if (strncmp(option, "-graphics", option_len) == 0)
1078 if (option_arg == NULL)
1079 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1081 options.graphics_directory = option_arg;
1082 if (option_arg == next_option)
1085 else if (strncmp(option, "-sounds", option_len) == 0)
1087 if (option_arg == NULL)
1088 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1090 options.sounds_directory = option_arg;
1091 if (option_arg == next_option)
1094 else if (strncmp(option, "-music", option_len) == 0)
1096 if (option_arg == NULL)
1097 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1099 options.music_directory = option_arg;
1100 if (option_arg == next_option)
1103 else if (strncmp(option, "-network", option_len) == 0)
1105 options.network = TRUE;
1107 else if (strncmp(option, "-serveronly", option_len) == 0)
1109 options.serveronly = TRUE;
1111 else if (strncmp(option, "-debug", option_len) == 0)
1113 options.debug = TRUE;
1115 else if (strncmp(option, "-verbose", option_len) == 0)
1117 options.verbose = TRUE;
1119 else if (strncmp(option, "-version", option_len) == 0 ||
1120 strncmp(option, "-V", option_len) == 0)
1122 print_version_function();
1126 else if (strPrefix(option, "-D"))
1128 options.special_flags = getStringCopy(&option[2]);
1130 else if (strncmp(option, "-execute", option_len) == 0)
1132 if (option_arg == NULL)
1133 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1135 options.execute_command = option_arg;
1136 if (option_arg == next_option)
1139 /* when doing batch processing, always enable verbose mode (warnings) */
1140 options.verbose = TRUE;
1142 else if (*option == '-')
1144 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1146 else if (options.server_host == NULL)
1148 options.server_host = *options_left;
1150 else if (options.server_port == 0)
1152 options.server_port = atoi(*options_left);
1153 if (options.server_port < 1024)
1154 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1157 Error(ERR_EXIT_HELP, "too many arguments");
1164 /* ------------------------------------------------------------------------- */
1165 /* error handling functions */
1166 /* ------------------------------------------------------------------------- */
1168 #define MAX_INTERNAL_ERROR_SIZE 1024
1170 /* used by SetError() and GetError() to store internal error messages */
1171 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1173 void SetError(char *format, ...)
1177 va_start(ap, format);
1178 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1184 return internal_error;
1187 void Error(int mode, char *format, ...)
1189 static boolean last_line_was_separator = FALSE;
1190 char *process_name = "";
1192 if (program.log_file[LOG_ERR_ID] == NULL)
1195 #if defined(PLATFORM_ANDROID)
1196 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1197 mode & ERR_INFO ? ANDROID_LOG_INFO :
1198 mode & ERR_WARN ? ANDROID_LOG_WARN :
1199 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1200 ANDROID_LOG_UNKNOWN);
1203 /* display warnings only when running in verbose mode */
1204 if (mode & ERR_WARN && !options.verbose)
1207 if (mode == ERR_INFO_LINE)
1209 if (!last_line_was_separator)
1210 printf_log_line(format, 79);
1212 last_line_was_separator = TRUE;
1217 last_line_was_separator = FALSE;
1219 if (mode & ERR_SOUND_SERVER)
1220 process_name = " sound server";
1221 else if (mode & ERR_NETWORK_SERVER)
1222 process_name = " network server";
1223 else if (mode & ERR_NETWORK_CLIENT)
1224 process_name = " network client **";
1228 #if !defined(PLATFORM_ANDROID)
1229 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1232 if (mode & ERR_WARN)
1233 printf_log_nonewline("warning: ");
1235 if (mode & ERR_EXIT)
1236 printf_log_nonewline("fatal error: ");
1240 va_start(ap, format);
1241 vprintf_log(format, ap);
1244 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1246 va_start(ap, format);
1247 program.exit_message_function(format, ap);
1252 if (mode & ERR_HELP)
1253 printf_log("%s: Try option '--help' for more information.",
1254 program.command_basename);
1256 if (mode & ERR_EXIT)
1257 printf_log("%s%s: aborting", program.command_basename, process_name);
1259 if (mode & ERR_EXIT)
1261 if (mode & ERR_FROM_SERVER)
1262 exit(1); /* child process: normal exit */
1264 program.exit_function(1); /* main process: clean up stuff */
1269 /* ------------------------------------------------------------------------- */
1270 /* checked memory allocation and freeing functions */
1271 /* ------------------------------------------------------------------------- */
1273 void *checked_malloc(unsigned int size)
1280 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1285 void *checked_calloc(unsigned int size)
1289 ptr = calloc(1, size);
1292 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1297 void *checked_realloc(void *ptr, unsigned int size)
1299 ptr = realloc(ptr, size);
1302 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1307 void checked_free(void *ptr)
1309 if (ptr != NULL) /* this check should be done by free() anyway */
1313 void clear_mem(void *ptr, unsigned int size)
1315 #if defined(PLATFORM_WIN32)
1316 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1317 char *cptr = (char *)ptr;
1322 memset(ptr, 0, size);
1327 /* ------------------------------------------------------------------------- */
1328 /* various helper functions */
1329 /* ------------------------------------------------------------------------- */
1331 void swap_numbers(int *i1, int *i2)
1339 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1351 /* the "put" variants of the following file access functions check for the file
1352 pointer being != NULL and return the number of bytes they have or would have
1353 written; this allows for chunk writing functions to first determine the size
1354 of the (not yet written) chunk, write the correct chunk size and finally
1355 write the chunk itself */
1357 int getFile8BitInteger(File *file)
1359 return getByteFromFile(file);
1362 int putFile8BitInteger(FILE *file, int value)
1370 int getFile16BitInteger(File *file, int byte_order)
1372 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1373 return ((getByteFromFile(file) << 8) |
1374 (getByteFromFile(file) << 0));
1375 else /* BYTE_ORDER_LITTLE_ENDIAN */
1376 return ((getByteFromFile(file) << 0) |
1377 (getByteFromFile(file) << 8));
1380 int putFile16BitInteger(FILE *file, int value, int byte_order)
1384 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1386 fputc((value >> 8) & 0xff, file);
1387 fputc((value >> 0) & 0xff, file);
1389 else /* BYTE_ORDER_LITTLE_ENDIAN */
1391 fputc((value >> 0) & 0xff, file);
1392 fputc((value >> 8) & 0xff, file);
1399 int getFile32BitInteger(File *file, int byte_order)
1401 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1402 return ((getByteFromFile(file) << 24) |
1403 (getByteFromFile(file) << 16) |
1404 (getByteFromFile(file) << 8) |
1405 (getByteFromFile(file) << 0));
1406 else /* BYTE_ORDER_LITTLE_ENDIAN */
1407 return ((getByteFromFile(file) << 0) |
1408 (getByteFromFile(file) << 8) |
1409 (getByteFromFile(file) << 16) |
1410 (getByteFromFile(file) << 24));
1413 int putFile32BitInteger(FILE *file, int value, int byte_order)
1417 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1419 fputc((value >> 24) & 0xff, file);
1420 fputc((value >> 16) & 0xff, file);
1421 fputc((value >> 8) & 0xff, file);
1422 fputc((value >> 0) & 0xff, file);
1424 else /* BYTE_ORDER_LITTLE_ENDIAN */
1426 fputc((value >> 0) & 0xff, file);
1427 fputc((value >> 8) & 0xff, file);
1428 fputc((value >> 16) & 0xff, file);
1429 fputc((value >> 24) & 0xff, file);
1436 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1439 const int chunk_name_length = 4;
1441 /* read chunk name */
1442 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1445 if (chunk_size != NULL)
1447 /* read chunk size */
1448 *chunk_size = getFile32BitInteger(file, byte_order);
1451 return (checkEndOfFile(file) ? FALSE : TRUE);
1454 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1459 /* write chunk name */
1461 fputs(chunk_name, file);
1463 num_bytes += strlen(chunk_name);
1465 if (chunk_size >= 0)
1467 /* write chunk size */
1469 putFile32BitInteger(file, chunk_size, byte_order);
1477 int getFileVersion(File *file)
1479 int version_major = getByteFromFile(file);
1480 int version_minor = getByteFromFile(file);
1481 int version_patch = getByteFromFile(file);
1482 int version_build = getByteFromFile(file);
1484 return VERSION_IDENT(version_major, version_minor, version_patch,
1488 int putFileVersion(FILE *file, int version)
1492 int version_major = VERSION_MAJOR(version);
1493 int version_minor = VERSION_MINOR(version);
1494 int version_patch = VERSION_PATCH(version);
1495 int version_build = VERSION_BUILD(version);
1497 fputc(version_major, file);
1498 fputc(version_minor, file);
1499 fputc(version_patch, file);
1500 fputc(version_build, file);
1506 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1510 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1511 buffer[i] = getByteFromFile(file);
1514 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1518 for(i = 0; i < bytes; i++)
1519 fputc(buffer[i], file);
1522 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1524 while (bytes-- && !checkEndOfFile(file))
1525 getByteFromFile(file);
1528 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1535 /* ------------------------------------------------------------------------- */
1536 /* functions to translate key identifiers between different format */
1537 /* ------------------------------------------------------------------------- */
1539 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1540 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1541 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1542 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1544 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1553 /* normal cursor keys */
1554 { KSYM_Left, "XK_Left", "cursor left" },
1555 { KSYM_Right, "XK_Right", "cursor right" },
1556 { KSYM_Up, "XK_Up", "cursor up" },
1557 { KSYM_Down, "XK_Down", "cursor down" },
1559 /* keypad cursor keys */
1561 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1562 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1563 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1564 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1567 /* other keypad keys */
1568 #ifdef KSYM_KP_Enter
1569 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1570 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1571 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1572 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1573 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1574 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1578 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1579 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1580 { KSYM_Control_L, "XK_Control_L", "left control" },
1581 { KSYM_Control_R, "XK_Control_R", "right control" },
1582 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1583 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1584 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1585 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1586 #if !defined(TARGET_SDL2)
1587 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1588 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1590 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1591 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1593 /* some special keys */
1594 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1595 { KSYM_Delete, "XK_Delete", "delete" },
1596 { KSYM_Insert, "XK_Insert", "insert" },
1597 { KSYM_Tab, "XK_Tab", "tab" },
1598 { KSYM_Home, "XK_Home", "home" },
1599 { KSYM_End, "XK_End", "end" },
1600 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1601 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1603 #if defined(TARGET_SDL2)
1604 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1605 { KSYM_Back, "XK_Back", "back" }, /* back key */
1608 /* ASCII 0x20 to 0x40 keys (except numbers) */
1609 { KSYM_space, "XK_space", "space" },
1610 { KSYM_exclam, "XK_exclam", "!" },
1611 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1612 { KSYM_numbersign, "XK_numbersign", "#" },
1613 { KSYM_dollar, "XK_dollar", "$" },
1614 { KSYM_percent, "XK_percent", "%" },
1615 { KSYM_ampersand, "XK_ampersand", "&" },
1616 { KSYM_apostrophe, "XK_apostrophe", "'" },
1617 { KSYM_parenleft, "XK_parenleft", "(" },
1618 { KSYM_parenright, "XK_parenright", ")" },
1619 { KSYM_asterisk, "XK_asterisk", "*" },
1620 { KSYM_plus, "XK_plus", "+" },
1621 { KSYM_comma, "XK_comma", "," },
1622 { KSYM_minus, "XK_minus", "-" },
1623 { KSYM_period, "XK_period", "." },
1624 { KSYM_slash, "XK_slash", "/" },
1625 { KSYM_colon, "XK_colon", ":" },
1626 { KSYM_semicolon, "XK_semicolon", ";" },
1627 { KSYM_less, "XK_less", "<" },
1628 { KSYM_equal, "XK_equal", "=" },
1629 { KSYM_greater, "XK_greater", ">" },
1630 { KSYM_question, "XK_question", "?" },
1631 { KSYM_at, "XK_at", "@" },
1633 /* more ASCII keys */
1634 { KSYM_bracketleft, "XK_bracketleft", "[" },
1635 { KSYM_backslash, "XK_backslash", "\\" },
1636 { KSYM_bracketright,"XK_bracketright", "]" },
1637 { KSYM_asciicircum, "XK_asciicircum", "^" },
1638 { KSYM_underscore, "XK_underscore", "_" },
1639 { KSYM_grave, "XK_grave", "grave" },
1640 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1641 { KSYM_braceleft, "XK_braceleft", "brace left" },
1642 { KSYM_bar, "XK_bar", "bar" },
1643 { KSYM_braceright, "XK_braceright", "brace right" },
1644 { KSYM_asciitilde, "XK_asciitilde", "~" },
1646 /* special (non-ASCII) keys */
1647 { KSYM_degree, "XK_degree", "degree" },
1648 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1649 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1650 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1651 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1652 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1653 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1654 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1656 #if defined(TARGET_SDL2)
1657 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1658 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1659 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1660 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1661 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1662 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1663 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1664 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1665 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1667 /* other keys (for reverse mapping only) */
1668 { KSYM_space, "XK_space", " " },
1671 #if defined(TARGET_SDL2)
1672 /* keypad keys are not in numerical order in SDL2 */
1673 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1674 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1675 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1676 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1677 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1678 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1679 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1680 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1681 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1682 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1685 /* end-of-array identifier */
1691 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1693 static char name_buffer[30];
1696 if (key >= KSYM_A && key <= KSYM_Z)
1697 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1698 else if (key >= KSYM_a && key <= KSYM_z)
1699 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1700 else if (key >= KSYM_0 && key <= KSYM_9)
1701 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1702 #if !defined(TARGET_SDL2)
1703 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1704 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1706 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1707 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1708 else if (key == KSYM_UNDEFINED)
1709 strcpy(name_buffer, "(undefined)");
1716 if (key == translate_key[i].key)
1718 strcpy(name_buffer, translate_key[i].name);
1722 while (translate_key[++i].name);
1724 if (!translate_key[i].name)
1725 strcpy(name_buffer, "(unknown)");
1728 *name = name_buffer;
1730 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1732 static char name_buffer[30];
1735 if (key >= KSYM_A && key <= KSYM_Z)
1736 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1737 else if (key >= KSYM_a && key <= KSYM_z)
1738 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1739 else if (key >= KSYM_0 && key <= KSYM_9)
1740 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1741 #if !defined(TARGET_SDL2)
1742 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1743 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1745 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1746 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1747 else if (key == KSYM_UNDEFINED)
1748 strcpy(name_buffer, "[undefined]");
1755 if (key == translate_key[i].key)
1757 strcpy(name_buffer, translate_key[i].x11name);
1761 while (translate_key[++i].x11name);
1763 if (!translate_key[i].x11name)
1764 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1767 *x11name = name_buffer;
1769 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1771 Key key = KSYM_UNDEFINED;
1772 char *name_ptr = *name;
1774 if (strlen(*name) == 1)
1776 char c = name_ptr[0];
1778 if (c >= 'A' && c <= 'Z')
1779 key = KSYM_A + (Key)(c - 'A');
1780 else if (c >= 'a' && c <= 'z')
1781 key = KSYM_a + (Key)(c - 'a');
1782 else if (c >= '0' && c <= '9')
1783 key = KSYM_0 + (Key)(c - '0');
1786 if (key == KSYM_UNDEFINED)
1792 if (strEqual(translate_key[i].name, *name))
1794 key = translate_key[i].key;
1798 while (translate_key[++i].x11name);
1801 if (key == KSYM_UNDEFINED)
1802 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1806 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1808 Key key = KSYM_UNDEFINED;
1809 char *name_ptr = *x11name;
1811 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1813 char c = name_ptr[3];
1815 if (c >= 'A' && c <= 'Z')
1816 key = KSYM_A + (Key)(c - 'A');
1817 else if (c >= 'a' && c <= 'z')
1818 key = KSYM_a + (Key)(c - 'a');
1819 else if (c >= '0' && c <= '9')
1820 key = KSYM_0 + (Key)(c - '0');
1822 #if !defined(TARGET_SDL2)
1823 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1825 char c = name_ptr[6];
1827 if (c >= '0' && c <= '9')
1828 key = KSYM_KP_0 + (Key)(c - '0');
1831 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1833 char c1 = name_ptr[4];
1834 char c2 = name_ptr[5];
1837 if ((c1 >= '0' && c1 <= '9') &&
1838 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1839 d = atoi(&name_ptr[4]);
1841 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1842 key = KSYM_F1 + (Key)(d - 1);
1844 else if (strPrefix(name_ptr, "XK_"))
1850 if (strEqual(name_ptr, translate_key[i].x11name))
1852 key = translate_key[i].key;
1856 while (translate_key[++i].x11name);
1858 else if (strPrefix(name_ptr, "0x"))
1860 unsigned int value = 0;
1866 char c = *name_ptr++;
1869 if (c >= '0' && c <= '9')
1871 else if (c >= 'a' && c <= 'f')
1872 d = (int)(c - 'a' + 10);
1873 else if (c >= 'A' && c <= 'F')
1874 d = (int)(c - 'A' + 10);
1882 value = value * 16 + d;
1893 char *getKeyNameFromKey(Key key)
1897 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1901 char *getX11KeyNameFromKey(Key key)
1905 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1909 Key getKeyFromKeyName(char *name)
1913 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1917 Key getKeyFromX11KeyName(char *x11name)
1921 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1925 char getCharFromKey(Key key)
1931 } translate_key_char[] =
1933 /* special (non-ASCII) keys (ISO-8859-1) */
1934 { KSYM_degree, CHAR_BYTE_DEGREE },
1935 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1936 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1937 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1938 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1939 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1940 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1941 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1943 /* end-of-array identifier */
1947 char *keyname = getKeyNameFromKey(key);
1950 if (strlen(keyname) == 1)
1952 else if (strEqual(keyname, "space"))
1960 if (key == translate_key_char[i].key)
1962 c = translate_key_char[i].key_char;
1967 while (translate_key_char[++i].key_char);
1973 char getValidConfigValueChar(char c)
1975 if (c == '#' || /* used to mark comments */
1976 c == '\\') /* used to mark continued lines */
1983 /* ------------------------------------------------------------------------- */
1984 /* functions to translate string identifiers to integer or boolean value */
1985 /* ------------------------------------------------------------------------- */
1987 int get_integer_from_string(char *s)
1989 static char *number_text[][3] =
1991 { "0", "zero", "null", },
1992 { "1", "one", "first" },
1993 { "2", "two", "second" },
1994 { "3", "three", "third" },
1995 { "4", "four", "fourth" },
1996 { "5", "five", "fifth" },
1997 { "6", "six", "sixth" },
1998 { "7", "seven", "seventh" },
1999 { "8", "eight", "eighth" },
2000 { "9", "nine", "ninth" },
2001 { "10", "ten", "tenth" },
2002 { "11", "eleven", "eleventh" },
2003 { "12", "twelve", "twelfth" },
2005 { NULL, NULL, NULL },
2009 char *s_lower = getStringToLower(s);
2012 for (i = 0; number_text[i][0] != NULL; i++)
2013 for (j = 0; j < 3; j++)
2014 if (strEqual(s_lower, number_text[i][j]))
2019 if (strEqual(s_lower, "false") ||
2020 strEqual(s_lower, "no") ||
2021 strEqual(s_lower, "off"))
2023 else if (strEqual(s_lower, "true") ||
2024 strEqual(s_lower, "yes") ||
2025 strEqual(s_lower, "on"))
2036 boolean get_boolean_from_string(char *s)
2038 char *s_lower = getStringToLower(s);
2039 boolean result = FALSE;
2041 if (strEqual(s_lower, "true") ||
2042 strEqual(s_lower, "yes") ||
2043 strEqual(s_lower, "on") ||
2044 get_integer_from_string(s) == 1)
2052 int get_switch3_from_string(char *s)
2054 char *s_lower = getStringToLower(s);
2057 if (strEqual(s_lower, "true") ||
2058 strEqual(s_lower, "yes") ||
2059 strEqual(s_lower, "on") ||
2060 get_integer_from_string(s) == 1)
2062 else if (strEqual(s_lower, "auto"))
2071 /* ------------------------------------------------------------------------- */
2072 /* functions for generic lists */
2073 /* ------------------------------------------------------------------------- */
2075 ListNode *newListNode()
2077 return checked_calloc(sizeof(ListNode));
2080 void addNodeToList(ListNode **node_first, char *key, void *content)
2082 ListNode *node_new = newListNode();
2084 node_new->key = getStringCopy(key);
2085 node_new->content = content;
2086 node_new->next = *node_first;
2089 (*node_first)->prev = node_new;
2091 *node_first = node_new;
2094 void deleteNodeFromList(ListNode **node_first, char *key,
2095 void (*destructor_function)(void *))
2097 if (node_first == NULL || *node_first == NULL)
2100 if (strEqual((*node_first)->key, key))
2102 checked_free((*node_first)->key);
2104 if (destructor_function)
2105 destructor_function((*node_first)->content);
2107 if ((*node_first)->next)
2108 (*node_first)->next->prev = (*node_first)->prev;
2110 checked_free(*node_first);
2112 *node_first = (*node_first)->next;
2115 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2118 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2120 if (node_first == NULL)
2123 if (strEqual(node_first->key, key))
2126 return getNodeFromKey(node_first->next, key);
2129 int getNumNodes(ListNode *node_first)
2131 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2134 void dumpList(ListNode *node_first)
2136 ListNode *node = node_first;
2140 printf("['%s' (%d)]\n", node->key,
2141 ((struct ListNodeInfo *)node->content)->num_references);
2145 printf("[%d nodes]\n", getNumNodes(node_first));
2149 /* ------------------------------------------------------------------------- */
2150 /* functions for file handling */
2151 /* ------------------------------------------------------------------------- */
2153 File *openFile(char *filename, char *mode)
2155 File *file = checked_calloc(sizeof(File));
2157 file->file = fopen(filename, mode);
2159 if (file->file != NULL)
2161 file->filename = getStringCopy(filename);
2166 #if defined(PLATFORM_ANDROID)
2167 file->asset_file = SDL_RWFromFile(filename, mode);
2169 if (file->asset_file != NULL)
2171 file->file_is_asset = TRUE;
2172 file->filename = getStringCopy(filename);
2183 int closeFile(File *file)
2190 #if defined(PLATFORM_ANDROID)
2191 if (file->asset_file)
2192 result = SDL_RWclose(file->asset_file);
2196 result = fclose(file->file);
2198 checked_free(file->filename);
2204 int checkEndOfFile(File *file)
2206 #if defined(PLATFORM_ANDROID)
2207 if (file->file_is_asset)
2208 return file->end_of_file;
2211 return feof(file->file);
2214 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2216 #if defined(PLATFORM_ANDROID)
2217 if (file->file_is_asset)
2219 if (file->end_of_file)
2222 size_t num_items_read =
2223 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2225 if (num_items_read < num_items)
2226 file->end_of_file = TRUE;
2228 return num_items_read;
2232 return fread(buffer, item_size, num_items, file->file);
2235 int seekFile(File *file, long offset, int whence)
2237 #if defined(PLATFORM_ANDROID)
2238 if (file->file_is_asset)
2240 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2241 whence == SEEK_CUR ? RW_SEEK_CUR :
2242 whence == SEEK_END ? RW_SEEK_END : 0);
2244 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2248 return fseek(file->file, offset, whence);
2251 int getByteFromFile(File *file)
2253 #if defined(PLATFORM_ANDROID)
2254 if (file->file_is_asset)
2256 if (file->end_of_file)
2260 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2262 if (num_bytes_read < 1)
2263 file->end_of_file = TRUE;
2265 return (file->end_of_file ? EOF : (int)c);
2269 return fgetc(file->file);
2272 char *getStringFromFile(File *file, char *line, int size)
2274 #if defined(PLATFORM_ANDROID)
2275 if (file->file_is_asset)
2277 if (file->end_of_file)
2280 char *line_ptr = line;
2281 int num_bytes_read = 0;
2283 while (num_bytes_read < size - 1 &&
2284 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2285 *line_ptr++ != '\n')
2290 if (strlen(line) == 0)
2292 file->end_of_file = TRUE;
2301 return fgets(line, size, file->file);
2305 /* ------------------------------------------------------------------------- */
2306 /* functions for directory handling */
2307 /* ------------------------------------------------------------------------- */
2309 Directory *openDirectory(char *dir_name)
2311 Directory *dir = checked_calloc(sizeof(Directory));
2313 dir->dir = opendir(dir_name);
2315 if (dir->dir != NULL)
2317 dir->filename = getStringCopy(dir_name);
2322 #if defined(PLATFORM_ANDROID)
2323 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2325 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2327 checked_free(asset_toc_filename);
2329 if (dir->asset_toc_file != NULL)
2331 dir->directory_is_asset = TRUE;
2332 dir->filename = getStringCopy(dir_name);
2343 int closeDirectory(Directory *dir)
2350 #if defined(PLATFORM_ANDROID)
2351 if (dir->asset_toc_file)
2352 result = SDL_RWclose(dir->asset_toc_file);
2356 result = closedir(dir->dir);
2359 freeDirectoryEntry(dir->dir_entry);
2361 checked_free(dir->filename);
2367 DirectoryEntry *readDirectory(Directory *dir)
2370 freeDirectoryEntry(dir->dir_entry);
2372 dir->dir_entry = NULL;
2374 #if defined(PLATFORM_ANDROID)
2375 if (dir->directory_is_asset)
2377 char line[MAX_LINE_LEN];
2378 char *line_ptr = line;
2379 int num_bytes_read = 0;
2381 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2382 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2391 if (strlen(line) == 0)
2394 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2396 dir->dir_entry->is_directory = FALSE;
2397 if (line[strlen(line) - 1] == '/')
2399 dir->dir_entry->is_directory = TRUE;
2401 line[strlen(line) - 1] = '\0';
2404 dir->dir_entry->basename = getStringCopy(line);
2405 dir->dir_entry->filename = getPath2(dir->filename, line);
2407 return dir->dir_entry;
2411 struct dirent *dir_entry = readdir(dir->dir);
2413 if (dir_entry == NULL)
2416 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2418 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2419 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2421 struct stat file_status;
2423 dir->dir_entry->is_directory =
2424 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2425 S_ISDIR(file_status.st_mode));
2427 return dir->dir_entry;
2430 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2432 if (dir_entry == NULL)
2435 checked_free(dir_entry->basename);
2436 checked_free(dir_entry->filename);
2437 checked_free(dir_entry);
2441 /* ------------------------------------------------------------------------- */
2442 /* functions for checking files and filenames */
2443 /* ------------------------------------------------------------------------- */
2445 boolean directoryExists(char *dir_name)
2447 if (dir_name == NULL)
2450 struct stat file_status;
2451 boolean success = (stat(dir_name, &file_status) == 0 &&
2452 S_ISDIR(file_status.st_mode));
2454 #if defined(PLATFORM_ANDROID)
2457 // this might be an asset directory; check by trying to open toc file
2458 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2459 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2461 checked_free(asset_toc_filename);
2463 success = (file != NULL);
2473 boolean fileExists(char *filename)
2475 if (filename == NULL)
2478 boolean success = (access(filename, F_OK) == 0);
2480 #if defined(PLATFORM_ANDROID)
2483 // this might be an asset file; check by trying to open it
2484 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2486 success = (file != NULL);
2496 boolean fileHasPrefix(char *basename, char *prefix)
2498 static char *basename_lower = NULL;
2499 int basename_length, prefix_length;
2501 checked_free(basename_lower);
2503 if (basename == NULL || prefix == NULL)
2506 basename_lower = getStringToLower(basename);
2507 basename_length = strlen(basename_lower);
2508 prefix_length = strlen(prefix);
2510 if (basename_length > prefix_length + 1 &&
2511 basename_lower[prefix_length] == '.' &&
2512 strncmp(basename_lower, prefix, prefix_length) == 0)
2518 boolean fileHasSuffix(char *basename, char *suffix)
2520 static char *basename_lower = NULL;
2521 int basename_length, suffix_length;
2523 checked_free(basename_lower);
2525 if (basename == NULL || suffix == NULL)
2528 basename_lower = getStringToLower(basename);
2529 basename_length = strlen(basename_lower);
2530 suffix_length = strlen(suffix);
2532 if (basename_length > suffix_length + 1 &&
2533 basename_lower[basename_length - suffix_length - 1] == '.' &&
2534 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2540 static boolean FileCouldBeArtwork(char *filename)
2542 char *basename = getBaseNamePtr(filename);
2544 return (!strEqual(basename, ".") &&
2545 !strEqual(basename, "..") &&
2546 !fileHasSuffix(basename, "txt") &&
2547 !fileHasSuffix(basename, "conf") &&
2548 !directoryExists(filename));
2551 boolean FileIsGraphic(char *filename)
2553 return FileCouldBeArtwork(filename);
2556 boolean FileIsSound(char *filename)
2558 return FileCouldBeArtwork(filename);
2561 boolean FileIsMusic(char *filename)
2563 return FileCouldBeArtwork(filename);
2566 boolean FileIsArtworkType(char *filename, int type)
2568 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2569 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2570 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2576 /* ------------------------------------------------------------------------- */
2577 /* functions for loading artwork configuration information */
2578 /* ------------------------------------------------------------------------- */
2580 char *get_mapped_token(char *token)
2582 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2583 static char *map_token_prefix[][2] =
2585 { "char_procent", "char_percent" },
2590 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2592 int len_token_prefix = strlen(map_token_prefix[i][0]);
2594 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2595 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2601 /* This function checks if a string <s> of the format "string1, string2, ..."
2602 exactly contains a string <s_contained>. */
2604 static boolean string_has_parameter(char *s, char *s_contained)
2608 if (s == NULL || s_contained == NULL)
2611 if (strlen(s_contained) > strlen(s))
2614 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2616 char next_char = s[strlen(s_contained)];
2618 /* check if next character is delimiter or whitespace */
2619 return (next_char == ',' || next_char == '\0' ||
2620 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2623 /* check if string contains another parameter string after a comma */
2624 substring = strchr(s, ',');
2625 if (substring == NULL) /* string does not contain a comma */
2628 /* advance string pointer to next character after the comma */
2631 /* skip potential whitespaces after the comma */
2632 while (*substring == ' ' || *substring == '\t')
2635 return string_has_parameter(substring, s_contained);
2638 int get_parameter_value(char *value_raw, char *suffix, int type)
2640 char *value = getStringToLower(value_raw);
2641 int result = 0; /* probably a save default value */
2643 if (strEqual(suffix, ".direction"))
2645 result = (strEqual(value, "left") ? MV_LEFT :
2646 strEqual(value, "right") ? MV_RIGHT :
2647 strEqual(value, "up") ? MV_UP :
2648 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2650 else if (strEqual(suffix, ".align"))
2652 result = (strEqual(value, "left") ? ALIGN_LEFT :
2653 strEqual(value, "right") ? ALIGN_RIGHT :
2654 strEqual(value, "center") ? ALIGN_CENTER :
2655 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2657 else if (strEqual(suffix, ".valign"))
2659 result = (strEqual(value, "top") ? VALIGN_TOP :
2660 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2661 strEqual(value, "middle") ? VALIGN_MIDDLE :
2662 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2664 else if (strEqual(suffix, ".anim_mode"))
2666 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2667 string_has_parameter(value, "loop") ? ANIM_LOOP :
2668 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2669 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2670 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2671 string_has_parameter(value, "random") ? ANIM_RANDOM :
2672 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2673 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2674 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2675 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2676 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2677 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2680 if (string_has_parameter(value, "reverse"))
2681 result |= ANIM_REVERSE;
2683 if (string_has_parameter(value, "opaque_player"))
2684 result |= ANIM_OPAQUE_PLAYER;
2686 if (string_has_parameter(value, "static_panel"))
2687 result |= ANIM_STATIC_PANEL;
2689 else if (strEqual(suffix, ".class"))
2691 result = get_hash_from_key(value);
2693 else if (strEqual(suffix, ".style"))
2695 result = STYLE_DEFAULT;
2697 if (string_has_parameter(value, "accurate_borders"))
2698 result |= STYLE_ACCURATE_BORDERS;
2700 if (string_has_parameter(value, "inner_corners"))
2701 result |= STYLE_INNER_CORNERS;
2703 else if (strEqual(suffix, ".fade_mode"))
2705 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2706 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2707 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2708 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2711 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2713 result = gfx.get_font_from_token_function(value);
2715 else /* generic parameter of type integer or boolean */
2717 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2718 type == TYPE_INTEGER ? get_integer_from_string(value) :
2719 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2720 ARG_UNDEFINED_VALUE);
2728 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2730 static struct ScreenModeInfo screen_mode;
2731 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2732 char *screen_mode_string_copy;
2733 char *screen_mode_string_pos_w;
2734 char *screen_mode_string_pos_h;
2736 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2739 screen_mode_string_copy = getStringCopy(screen_mode_string);
2741 screen_mode_string_pos_w = screen_mode_string_copy;
2742 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2743 *screen_mode_string_pos_h++ = '\0';
2745 screen_mode.width = atoi(screen_mode_string_pos_w);
2746 screen_mode.height = atoi(screen_mode_string_pos_h);
2748 return &screen_mode;
2751 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2754 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2755 float aspect_ratio_new;
2760 *x = i * aspect_ratio + 0.000001;
2763 aspect_ratio_new = (float)*x / (float)*y;
2767 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2770 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2771 struct ListNodeInfo ***, int *);
2773 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2774 struct ConfigTypeInfo *suffix_list,
2775 char **ignore_tokens,
2776 int num_file_list_entries)
2778 struct FileInfo *file_list;
2779 int num_file_list_entries_found = 0;
2780 int num_suffix_list_entries = 0;
2784 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2786 for (i = 0; suffix_list[i].token != NULL; i++)
2787 num_suffix_list_entries++;
2789 /* always start with reliable default values */
2790 for (i = 0; i < num_file_list_entries; i++)
2792 file_list[i].token = NULL;
2794 file_list[i].default_filename = NULL;
2795 file_list[i].filename = NULL;
2797 if (num_suffix_list_entries > 0)
2799 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2801 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2802 file_list[i].parameter = checked_calloc(parameter_array_size);
2804 for (j = 0; j < num_suffix_list_entries; j++)
2806 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2807 setString(&file_list[i].parameter[j], suffix_list[j].value);
2810 file_list[i].redefined = FALSE;
2811 file_list[i].fallback_to_default = FALSE;
2812 file_list[i].default_is_cloned = FALSE;
2818 for (i = 0; config_list[i].token != NULL; i++)
2820 int len_config_token = strlen(config_list[i].token);
2821 boolean is_file_entry = TRUE;
2823 for (j = 0; suffix_list[j].token != NULL; j++)
2825 int len_suffix = strlen(suffix_list[j].token);
2827 if (len_suffix < len_config_token &&
2828 strEqual(&config_list[i].token[len_config_token - len_suffix],
2829 suffix_list[j].token))
2831 setString(&file_list[list_pos].default_parameter[j],
2832 config_list[i].value);
2834 is_file_entry = FALSE;
2840 /* the following tokens are no file definitions, but other config tokens */
2841 for (j = 0; ignore_tokens[j] != NULL; j++)
2842 if (strEqual(config_list[i].token, ignore_tokens[j]))
2843 is_file_entry = FALSE;
2850 if (list_pos >= num_file_list_entries)
2853 file_list[list_pos].token = config_list[i].token;
2854 file_list[list_pos].default_filename = config_list[i].value;
2857 if (strSuffix(config_list[i].token, ".clone_from"))
2858 file_list[list_pos].default_is_cloned = TRUE;
2861 num_file_list_entries_found = list_pos + 1;
2862 if (num_file_list_entries_found != num_file_list_entries)
2864 Error(ERR_INFO_LINE, "-");
2865 Error(ERR_INFO, "inconsistant config list information:");
2866 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2867 num_file_list_entries);
2868 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2869 num_file_list_entries_found);
2870 Error(ERR_EXIT, "please fix");
2876 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2878 int len_token = strlen(token);
2879 int len_suffix = strlen(suffix);
2881 if (start_pos < 0) /* compare suffix from end of string */
2882 start_pos += len_token;
2884 if (start_pos < 0 || start_pos + len_suffix > len_token)
2887 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2890 if (token[start_pos + len_suffix] == '\0')
2893 if (token[start_pos + len_suffix] == '.')
2899 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2901 static void read_token_parameters(SetupFileHash *setup_file_hash,
2902 struct ConfigTypeInfo *suffix_list,
2903 struct FileInfo *file_list_entry)
2905 /* check for config token that is the base token without any suffixes */
2906 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2907 char *known_token_value = KNOWN_TOKEN_VALUE;
2910 if (filename != NULL)
2912 setString(&file_list_entry->filename, filename);
2914 /* when file definition found, set all parameters to default values */
2915 for (i = 0; suffix_list[i].token != NULL; i++)
2916 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2918 file_list_entry->redefined = TRUE;
2920 /* mark config file token as well known from default config */
2921 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2924 /* check for config tokens that can be build by base token and suffixes */
2925 for (i = 0; suffix_list[i].token != NULL; i++)
2927 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2928 char *value = getHashEntry(setup_file_hash, token);
2932 setString(&file_list_entry->parameter[i], value);
2934 /* mark config file token as well known from default config */
2935 setHashEntry(setup_file_hash, token, known_token_value);
2942 static void add_dynamic_file_list_entry(struct FileInfo **list,
2943 int *num_list_entries,
2944 SetupFileHash *extra_file_hash,
2945 struct ConfigTypeInfo *suffix_list,
2946 int num_suffix_list_entries,
2949 struct FileInfo *new_list_entry;
2950 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2952 (*num_list_entries)++;
2953 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2954 new_list_entry = &(*list)[*num_list_entries - 1];
2956 new_list_entry->token = getStringCopy(token);
2957 new_list_entry->default_filename = NULL;
2958 new_list_entry->filename = NULL;
2959 new_list_entry->parameter = checked_calloc(parameter_array_size);
2961 new_list_entry->redefined = FALSE;
2962 new_list_entry->fallback_to_default = FALSE;
2963 new_list_entry->default_is_cloned = FALSE;
2965 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2968 static void add_property_mapping(struct PropertyMapping **list,
2969 int *num_list_entries,
2970 int base_index, int ext1_index,
2971 int ext2_index, int ext3_index,
2974 struct PropertyMapping *new_list_entry;
2976 (*num_list_entries)++;
2977 *list = checked_realloc(*list,
2978 *num_list_entries * sizeof(struct PropertyMapping));
2979 new_list_entry = &(*list)[*num_list_entries - 1];
2981 new_list_entry->base_index = base_index;
2982 new_list_entry->ext1_index = ext1_index;
2983 new_list_entry->ext2_index = ext2_index;
2984 new_list_entry->ext3_index = ext3_index;
2986 new_list_entry->artwork_index = artwork_index;
2989 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2992 struct FileInfo *file_list = artwork_info->file_list;
2993 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2994 char **base_prefixes = artwork_info->base_prefixes;
2995 char **ext1_suffixes = artwork_info->ext1_suffixes;
2996 char **ext2_suffixes = artwork_info->ext2_suffixes;
2997 char **ext3_suffixes = artwork_info->ext3_suffixes;
2998 char **ignore_tokens = artwork_info->ignore_tokens;
2999 int num_file_list_entries = artwork_info->num_file_list_entries;
3000 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3001 int num_base_prefixes = artwork_info->num_base_prefixes;
3002 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3003 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3004 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3005 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3006 SetupFileHash *setup_file_hash, *valid_file_hash;
3007 SetupFileHash *extra_file_hash, *empty_file_hash;
3008 char *known_token_value = KNOWN_TOKEN_VALUE;
3011 if (filename == NULL)
3014 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3017 /* separate valid (defined) from empty (undefined) config token values */
3018 valid_file_hash = newSetupFileHash();
3019 empty_file_hash = newSetupFileHash();
3020 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3022 char *value = HASH_ITERATION_VALUE(itr);
3024 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3025 HASH_ITERATION_TOKEN(itr), value);
3027 END_HASH_ITERATION(setup_file_hash, itr)
3029 /* at this point, we do not need the setup file hash anymore -- free it */
3030 freeSetupFileHash(setup_file_hash);
3032 /* map deprecated to current tokens (using prefix match and replace) */
3033 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3035 char *token = HASH_ITERATION_TOKEN(itr);
3036 char *mapped_token = get_mapped_token(token);
3038 if (mapped_token != NULL)
3040 char *value = HASH_ITERATION_VALUE(itr);
3042 /* add mapped token */
3043 setHashEntry(valid_file_hash, mapped_token, value);
3045 /* ignore old token (by setting it to "known" keyword) */
3046 setHashEntry(valid_file_hash, token, known_token_value);
3051 END_HASH_ITERATION(valid_file_hash, itr)
3053 /* read parameters for all known config file tokens */
3054 for (i = 0; i < num_file_list_entries; i++)
3055 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3057 /* set all tokens that can be ignored here to "known" keyword */
3058 for (i = 0; i < num_ignore_tokens; i++)
3059 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3061 /* copy all unknown config file tokens to extra config hash */
3062 extra_file_hash = newSetupFileHash();
3063 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3065 char *value = HASH_ITERATION_VALUE(itr);
3067 if (!strEqual(value, known_token_value))
3068 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3070 END_HASH_ITERATION(valid_file_hash, itr)
3072 /* at this point, we do not need the valid file hash anymore -- free it */
3073 freeSetupFileHash(valid_file_hash);
3075 /* now try to determine valid, dynamically defined config tokens */
3077 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3079 struct FileInfo **dynamic_file_list =
3080 &artwork_info->dynamic_file_list;
3081 int *num_dynamic_file_list_entries =
3082 &artwork_info->num_dynamic_file_list_entries;
3083 struct PropertyMapping **property_mapping =
3084 &artwork_info->property_mapping;
3085 int *num_property_mapping_entries =
3086 &artwork_info->num_property_mapping_entries;
3087 int current_summarized_file_list_entry =
3088 artwork_info->num_file_list_entries +
3089 artwork_info->num_dynamic_file_list_entries;
3090 char *token = HASH_ITERATION_TOKEN(itr);
3091 int len_token = strlen(token);
3093 boolean base_prefix_found = FALSE;
3094 boolean parameter_suffix_found = FALSE;
3096 /* skip all parameter definitions (handled by read_token_parameters()) */
3097 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3099 int len_suffix = strlen(suffix_list[i].token);
3101 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3102 parameter_suffix_found = TRUE;
3105 if (parameter_suffix_found)
3108 /* ---------- step 0: search for matching base prefix ---------- */
3111 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3113 char *base_prefix = base_prefixes[i];
3114 int len_base_prefix = strlen(base_prefix);
3115 boolean ext1_suffix_found = FALSE;
3116 boolean ext2_suffix_found = FALSE;
3117 boolean ext3_suffix_found = FALSE;
3118 boolean exact_match = FALSE;
3119 int base_index = -1;
3120 int ext1_index = -1;
3121 int ext2_index = -1;
3122 int ext3_index = -1;
3124 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3126 if (!base_prefix_found)
3131 if (start_pos + len_base_prefix == len_token) /* exact match */
3135 add_dynamic_file_list_entry(dynamic_file_list,
3136 num_dynamic_file_list_entries,
3139 num_suffix_list_entries,
3141 add_property_mapping(property_mapping,
3142 num_property_mapping_entries,
3143 base_index, -1, -1, -1,
3144 current_summarized_file_list_entry);
3148 /* ---------- step 1: search for matching first suffix ---------- */
3150 start_pos += len_base_prefix;
3151 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3153 char *ext1_suffix = ext1_suffixes[j];
3154 int len_ext1_suffix = strlen(ext1_suffix);
3156 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3158 if (!ext1_suffix_found)
3163 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3167 add_dynamic_file_list_entry(dynamic_file_list,
3168 num_dynamic_file_list_entries,
3171 num_suffix_list_entries,
3173 add_property_mapping(property_mapping,
3174 num_property_mapping_entries,
3175 base_index, ext1_index, -1, -1,
3176 current_summarized_file_list_entry);
3180 start_pos += len_ext1_suffix;
3186 /* ---------- step 2: search for matching second suffix ---------- */
3188 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3190 char *ext2_suffix = ext2_suffixes[k];
3191 int len_ext2_suffix = strlen(ext2_suffix);
3193 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3195 if (!ext2_suffix_found)
3200 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3204 add_dynamic_file_list_entry(dynamic_file_list,
3205 num_dynamic_file_list_entries,
3208 num_suffix_list_entries,
3210 add_property_mapping(property_mapping,
3211 num_property_mapping_entries,
3212 base_index, ext1_index, ext2_index, -1,
3213 current_summarized_file_list_entry);
3217 start_pos += len_ext2_suffix;
3223 /* ---------- step 3: search for matching third suffix ---------- */
3225 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3227 char *ext3_suffix = ext3_suffixes[l];
3228 int len_ext3_suffix = strlen(ext3_suffix);
3230 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3232 if (!ext3_suffix_found)
3237 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3241 add_dynamic_file_list_entry(dynamic_file_list,
3242 num_dynamic_file_list_entries,
3245 num_suffix_list_entries,
3247 add_property_mapping(property_mapping,
3248 num_property_mapping_entries,
3249 base_index, ext1_index, ext2_index, ext3_index,
3250 current_summarized_file_list_entry);
3256 END_HASH_ITERATION(extra_file_hash, itr)
3258 if (artwork_info->num_dynamic_file_list_entries > 0)
3260 artwork_info->dynamic_artwork_list =
3261 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3262 artwork_info->sizeof_artwork_list_entry);
3265 if (options.verbose && IS_PARENT_PROCESS())
3267 SetupFileList *setup_file_list, *list;
3268 boolean dynamic_tokens_found = FALSE;
3269 boolean unknown_tokens_found = FALSE;
3270 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3272 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3273 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3275 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3277 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3278 dynamic_tokens_found = TRUE;
3280 unknown_tokens_found = TRUE;
3282 END_HASH_ITERATION(extra_file_hash, itr)
3284 if (options.debug && dynamic_tokens_found)
3286 Error(ERR_INFO_LINE, "-");
3287 Error(ERR_INFO, "dynamic token(s) found in config file:");
3288 Error(ERR_INFO, "- config file: '%s'", filename);
3290 for (list = setup_file_list; list != NULL; list = list->next)
3292 char *value = getHashEntry(extra_file_hash, list->token);
3294 if (value != NULL && strEqual(value, known_token_value))
3295 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3298 Error(ERR_INFO_LINE, "-");
3301 if (unknown_tokens_found)
3303 Error(ERR_INFO_LINE, "-");
3304 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3305 Error(ERR_INFO, "- config file: '%s'", filename);
3307 for (list = setup_file_list; list != NULL; list = list->next)
3309 char *value = getHashEntry(extra_file_hash, list->token);
3311 if (value != NULL && !strEqual(value, known_token_value))
3312 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3315 Error(ERR_INFO_LINE, "-");
3318 if (undefined_values_found)
3320 Error(ERR_INFO_LINE, "-");
3321 Error(ERR_INFO, "warning: undefined values found in config file:");
3322 Error(ERR_INFO, "- config file: '%s'", filename);
3324 for (list = setup_file_list; list != NULL; list = list->next)
3326 char *value = getHashEntry(empty_file_hash, list->token);
3329 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3332 Error(ERR_INFO_LINE, "-");
3335 freeSetupFileList(setup_file_list);
3338 freeSetupFileHash(extra_file_hash);
3339 freeSetupFileHash(empty_file_hash);
3342 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3344 struct FileInfo *file_list = artwork_info->file_list;
3345 int num_file_list_entries = artwork_info->num_file_list_entries;
3346 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3347 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3350 DrawInitText("Loading artwork config", 120, FC_GREEN);
3351 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3353 /* always start with reliable default values */
3354 for (i = 0; i < num_file_list_entries; i++)
3356 setString(&file_list[i].filename, file_list[i].default_filename);
3358 for (j = 0; j < num_suffix_list_entries; j++)
3359 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3361 file_list[i].redefined = FALSE;
3362 file_list[i].fallback_to_default = FALSE;
3365 /* free previous dynamic artwork file array */
3366 if (artwork_info->dynamic_file_list != NULL)
3368 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3370 free(artwork_info->dynamic_file_list[i].token);
3371 free(artwork_info->dynamic_file_list[i].filename);
3372 free(artwork_info->dynamic_file_list[i].parameter);
3375 free(artwork_info->dynamic_file_list);
3376 artwork_info->dynamic_file_list = NULL;
3378 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3379 &artwork_info->num_dynamic_file_list_entries);
3382 /* free previous property mapping */
3383 if (artwork_info->property_mapping != NULL)
3385 free(artwork_info->property_mapping);
3387 artwork_info->property_mapping = NULL;
3388 artwork_info->num_property_mapping_entries = 0;
3391 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3393 /* first look for special artwork configured in level series config */
3394 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3396 if (fileExists(filename_base))
3397 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3400 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3402 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3403 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3406 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3407 struct ListNodeInfo **listnode)
3411 char *filename = (*listnode)->source_filename;
3413 if (--(*listnode)->num_references <= 0)
3414 deleteNodeFromList(&artwork_info->content_list, filename,
3415 artwork_info->free_artwork);
3421 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3422 struct ListNodeInfo **listnode,
3423 struct FileInfo *file_list_entry)
3433 char *basename = file_list_entry->filename;
3434 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3436 if (filename == NULL)
3438 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3440 basename = file_list_entry->default_filename;
3442 /* fail for cloned default artwork that has no default filename defined */
3443 if (file_list_entry->default_is_cloned &&
3444 strEqual(basename, UNDEFINED_FILENAME))
3446 int error_mode = ERR_WARN;
3448 /* we can get away without sounds and music, but not without graphics */
3449 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3450 error_mode = ERR_EXIT;
3452 Error(error_mode, "token '%s' was cloned and has no default filename",
3453 file_list_entry->token);
3458 /* dynamic artwork has no default filename / skip empty default artwork */
3459 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3462 file_list_entry->fallback_to_default = TRUE;
3464 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3466 filename = getCustomArtworkFilename(basename, artwork_info->type);
3468 if (filename == NULL)
3470 int error_mode = ERR_WARN;
3472 /* we can get away without sounds and music, but not without graphics */
3473 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3474 error_mode = ERR_EXIT;
3476 Error(error_mode, "cannot find default artwork file '%s'", basename);
3482 /* check if the old and the new artwork file are the same */
3483 if (*listnode && strEqual((*listnode)->source_filename, filename))
3485 /* The old and new artwork are the same (have the same filename and path).
3486 This usually means that this artwork does not exist in this artwork set
3487 and a fallback to the existing artwork is done. */
3492 /* delete existing artwork file entry */
3493 deleteArtworkListEntry(artwork_info, listnode);
3495 /* check if the new artwork file already exists in the list of artwork */
3496 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3498 *listnode = (struct ListNodeInfo *)node->content;
3499 (*listnode)->num_references++;
3504 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3505 DrawInitText(basename, 150, FC_YELLOW);
3507 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3509 /* add new artwork file entry to the list of artwork files */
3510 (*listnode)->num_references = 1;
3511 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3516 int error_mode = ERR_WARN;
3518 /* we can get away without sounds and music, but not without graphics */
3519 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3520 error_mode = ERR_EXIT;
3522 Error(error_mode, "cannot load artwork file '%s'", basename);
3528 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3529 struct ListNodeInfo **listnode,
3530 struct FileInfo *file_list_entry)
3532 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3534 deleteArtworkListEntry(artwork_info, listnode);
3539 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3542 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3544 struct FileInfo *file_list = artwork_info->file_list;
3545 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3546 int num_file_list_entries = artwork_info->num_file_list_entries;
3547 int num_dynamic_file_list_entries =
3548 artwork_info->num_dynamic_file_list_entries;
3551 print_timestamp_init("ReloadCustomArtworkList");
3553 for (i = 0; i < num_file_list_entries; i++)
3554 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3557 for (i = 0; i < num_dynamic_file_list_entries; i++)
3558 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3559 &dynamic_file_list[i]);
3561 print_timestamp_done("ReloadCustomArtworkList");
3564 dumpList(artwork_info->content_list);
3568 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3569 struct ListNodeInfo ***list,
3570 int *num_list_entries)
3577 for (i = 0; i < *num_list_entries; i++)
3578 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3582 *num_list_entries = 0;
3585 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3587 if (artwork_info == NULL)
3590 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3591 &artwork_info->num_file_list_entries);
3593 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3594 &artwork_info->num_dynamic_file_list_entries);
3598 /* ------------------------------------------------------------------------- */
3599 /* functions only needed for non-Unix (non-command-line) systems */
3600 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3601 /* (now also added for Windows, to create files in user data directory) */
3602 /* ------------------------------------------------------------------------- */
3604 char *getLogFilename(char *basename)
3606 return getPath2(getUserGameDataDir(), basename);
3613 InitUserDataDirectory();
3615 for (i = 0; i < NUM_LOGS; i++)
3617 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3620 program.log_file[i] = program.log_file_default[i]; // reset to default
3622 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3623 program.log_filename[i], strerror(errno));
3626 /* output should be unbuffered so it is not truncated in a crash */
3627 setbuf(program.log_file[i], NULL);
3631 void CloseLogFiles()
3635 for (i = 0; i < NUM_LOGS; i++)
3636 if (program.log_file[i] != program.log_file_default[i])
3637 fclose(program.log_file[i]);
3640 void DumpLogFile(int nr)
3642 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3644 if (log_file == NULL)
3647 while (!feof(log_file))
3648 fputc(fgetc(log_file), stdout);
3653 void NotifyUserAboutErrorFile()
3655 #if defined(PLATFORM_WIN32)
3656 char *title_text = getStringCat2(program.program_title, " Error Message");
3657 char *error_text = getStringCat2("The program was aborted due to an error; "
3658 "for details, see the following error file:"
3660 program.log_filename[LOG_ERR_ID]);
3662 MessageBox(NULL, error_text, title_text, MB_OK);
3667 /* ------------------------------------------------------------------------- */
3668 /* the following is only for debugging purpose and normally not used */
3669 /* ------------------------------------------------------------------------- */
3673 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3674 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3676 #define DEBUG_NUM_TIMESTAMPS 10
3677 #define DEBUG_TIME_IN_MICROSECONDS 0
3679 #if DEBUG_TIME_IN_MICROSECONDS
3680 static double Counter_Microseconds()
3682 static struct timeval base_time = { 0, 0 };
3683 struct timeval current_time;
3686 gettimeofday(¤t_time, NULL);
3688 /* reset base time in case of wrap-around */
3689 if (current_time.tv_sec < base_time.tv_sec)
3690 base_time = current_time;
3693 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3694 ((double)(current_time.tv_usec - base_time.tv_usec));
3696 return counter; /* return microseconds since last init */
3700 char *debug_print_timestamp_get_padding(int padding_size)
3702 static char *padding = NULL;
3703 int max_padding_size = 100;
3705 if (padding == NULL)
3707 padding = checked_calloc(max_padding_size + 1);
3708 memset(padding, ' ', max_padding_size);
3711 return &padding[MAX(0, max_padding_size - padding_size)];
3714 void debug_print_timestamp(int counter_nr, char *message)
3716 int indent_size = 8;
3717 int padding_size = 40;
3718 float timestamp_interval;
3721 Error(ERR_EXIT, "debugging: invalid negative counter");
3722 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3723 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3725 #if DEBUG_TIME_IN_MICROSECONDS
3726 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3729 counter[counter_nr][0] = Counter_Microseconds();
3731 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3734 counter[counter_nr][0] = Counter();
3737 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3738 counter[counter_nr][1] = counter[counter_nr][0];
3741 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3742 debug_print_timestamp_get_padding(counter_nr * indent_size),
3744 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3745 timestamp_interval / 1000,
3749 void debug_print_parent_only(char *format, ...)
3751 if (!IS_PARENT_PROCESS())
3758 va_start(ap, format);
3759 vprintf(format, ap);
3768 void print_timestamp_ext(char *message, char *mode)
3770 #if DEBUG_PRINT_INIT_TIMESTAMPS
3771 static char *debug_message = NULL;
3772 static char *last_message = NULL;
3773 static int counter_nr = 0;
3774 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3776 checked_free(debug_message);
3777 debug_message = getStringCat3(mode, " ", message);
3779 if (strEqual(mode, "INIT"))
3781 debug_print_timestamp(counter_nr, NULL);
3783 if (counter_nr + 1 < max_depth)
3784 debug_print_timestamp(counter_nr, debug_message);
3788 debug_print_timestamp(counter_nr, NULL);
3790 else if (strEqual(mode, "DONE"))
3794 if (counter_nr + 1 < max_depth ||
3795 (counter_nr == 0 && max_depth == 1))
3797 last_message = message;
3799 if (counter_nr == 0 && max_depth == 1)
3801 checked_free(debug_message);
3802 debug_message = getStringCat3("TIME", " ", message);
3805 debug_print_timestamp(counter_nr, debug_message);
3808 else if (!strEqual(mode, "TIME") ||
3809 !strEqual(message, last_message))
3811 if (counter_nr < max_depth)
3812 debug_print_timestamp(counter_nr, debug_message);
3817 void print_timestamp_init(char *message)
3819 print_timestamp_ext(message, "INIT");
3822 void print_timestamp_time(char *message)
3824 print_timestamp_ext(message, "TIME");
3827 void print_timestamp_done(char *message)
3829 print_timestamp_ext(message, "DONE");