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(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 **options_left = &argv[1];
953 /* if the program is configured to start from current directory (default),
954 determine program package directory from program binary (some versions
955 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
956 set the current working directory to the program package directory) */
958 if (strEqual(ro_base_path, "."))
959 ro_base_path = getProgramMainDataPath();
960 if (strEqual(rw_base_path, "."))
961 rw_base_path = getProgramMainDataPath();
963 /* initialize global program options */
964 options.display_name = NULL;
965 options.server_host = NULL;
966 options.server_port = 0;
968 options.ro_base_directory = ro_base_path;
969 options.rw_base_directory = rw_base_path;
970 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
971 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
972 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
973 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
974 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
976 options.execute_command = NULL;
977 options.special_flags = NULL;
979 options.serveronly = FALSE;
980 options.network = FALSE;
981 options.verbose = FALSE;
982 options.debug = FALSE;
985 options.verbose = TRUE;
987 #if !defined(PLATFORM_UNIX)
988 if (*options_left == NULL) /* no options given -- enable verbose mode */
989 options.verbose = TRUE;
993 while (*options_left)
995 char option_str[MAX_OPTION_LEN];
996 char *option = options_left[0];
997 char *next_option = options_left[1];
998 char *option_arg = NULL;
999 int option_len = strlen(option);
1001 if (option_len >= MAX_OPTION_LEN)
1002 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1004 strcpy(option_str, option); /* copy argument into buffer */
1005 option = option_str;
1007 if (strEqual(option, "--")) /* stop scanning arguments */
1010 if (strPrefix(option, "--")) /* treat '--' like '-' */
1013 option_arg = strchr(option, '=');
1014 if (option_arg == NULL) /* no '=' in option */
1015 option_arg = next_option;
1018 *option_arg++ = '\0'; /* cut argument from option */
1019 if (*option_arg == '\0') /* no argument after '=' */
1020 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
1023 option_len = strlen(option);
1025 if (strEqual(option, "-"))
1027 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1029 else if (strncmp(option, "-help", option_len) == 0)
1031 print_usage_function();
1035 else if (strncmp(option, "-display", option_len) == 0)
1037 if (option_arg == NULL)
1038 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1040 options.display_name = option_arg;
1041 if (option_arg == next_option)
1044 else if (strncmp(option, "-basepath", option_len) == 0)
1046 if (option_arg == NULL)
1047 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1049 /* this should be extended to separate options for ro and rw data */
1050 options.ro_base_directory = ro_base_path = option_arg;
1051 options.rw_base_directory = rw_base_path = option_arg;
1052 if (option_arg == next_option)
1055 /* adjust paths for sub-directories in base directory accordingly */
1056 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1057 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1058 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1059 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1060 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1062 else if (strncmp(option, "-levels", option_len) == 0)
1064 if (option_arg == NULL)
1065 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1067 options.level_directory = option_arg;
1068 if (option_arg == next_option)
1071 else if (strncmp(option, "-graphics", option_len) == 0)
1073 if (option_arg == NULL)
1074 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1076 options.graphics_directory = option_arg;
1077 if (option_arg == next_option)
1080 else if (strncmp(option, "-sounds", option_len) == 0)
1082 if (option_arg == NULL)
1083 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1085 options.sounds_directory = option_arg;
1086 if (option_arg == next_option)
1089 else if (strncmp(option, "-music", option_len) == 0)
1091 if (option_arg == NULL)
1092 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1094 options.music_directory = option_arg;
1095 if (option_arg == next_option)
1098 else if (strncmp(option, "-network", option_len) == 0)
1100 options.network = TRUE;
1102 else if (strncmp(option, "-serveronly", option_len) == 0)
1104 options.serveronly = TRUE;
1106 else if (strncmp(option, "-debug", option_len) == 0)
1108 options.debug = TRUE;
1110 else if (strncmp(option, "-verbose", option_len) == 0)
1112 options.verbose = TRUE;
1114 else if (strncmp(option, "-version", option_len) == 0 ||
1115 strncmp(option, "-V", option_len) == 0)
1117 print_version_function();
1121 else if (strPrefix(option, "-D"))
1123 options.special_flags = getStringCopy(&option[2]);
1125 else if (strncmp(option, "-execute", option_len) == 0)
1127 if (option_arg == NULL)
1128 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1130 options.execute_command = option_arg;
1131 if (option_arg == next_option)
1134 /* when doing batch processing, always enable verbose mode (warnings) */
1135 options.verbose = TRUE;
1137 else if (*option == '-')
1139 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1141 else if (options.server_host == NULL)
1143 options.server_host = *options_left;
1145 else if (options.server_port == 0)
1147 options.server_port = atoi(*options_left);
1148 if (options.server_port < 1024)
1149 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1152 Error(ERR_EXIT_HELP, "too many arguments");
1159 /* ------------------------------------------------------------------------- */
1160 /* error handling functions */
1161 /* ------------------------------------------------------------------------- */
1163 #define MAX_INTERNAL_ERROR_SIZE 1024
1165 /* used by SetError() and GetError() to store internal error messages */
1166 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1168 void SetError(char *format, ...)
1172 va_start(ap, format);
1173 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1179 return internal_error;
1182 void Error(int mode, char *format, ...)
1184 static boolean last_line_was_separator = FALSE;
1185 char *process_name = "";
1187 if (program.log_file[LOG_ERR_ID] == NULL)
1190 #if defined(PLATFORM_ANDROID)
1191 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1192 mode & ERR_INFO ? ANDROID_LOG_INFO :
1193 mode & ERR_WARN ? ANDROID_LOG_WARN :
1194 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1195 ANDROID_LOG_UNKNOWN);
1198 /* display warnings only when running in verbose mode */
1199 if (mode & ERR_WARN && !options.verbose)
1202 if (mode == ERR_INFO_LINE)
1204 if (!last_line_was_separator)
1205 printf_log_line(format, 79);
1207 last_line_was_separator = TRUE;
1212 last_line_was_separator = FALSE;
1214 if (mode & ERR_SOUND_SERVER)
1215 process_name = " sound server";
1216 else if (mode & ERR_NETWORK_SERVER)
1217 process_name = " network server";
1218 else if (mode & ERR_NETWORK_CLIENT)
1219 process_name = " network client **";
1223 #if !defined(PLATFORM_ANDROID)
1224 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1227 if (mode & ERR_WARN)
1228 printf_log_nonewline("warning: ");
1230 if (mode & ERR_EXIT)
1231 printf_log_nonewline("fatal error: ");
1235 va_start(ap, format);
1236 vprintf_log(format, ap);
1239 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1241 va_start(ap, format);
1242 program.exit_message_function(format, ap);
1247 if (mode & ERR_HELP)
1248 printf_log("%s: Try option '--help' for more information.",
1249 program.command_basename);
1251 if (mode & ERR_EXIT)
1252 printf_log("%s%s: aborting", program.command_basename, process_name);
1254 if (mode & ERR_EXIT)
1256 if (mode & ERR_FROM_SERVER)
1257 exit(1); /* child process: normal exit */
1259 program.exit_function(1); /* main process: clean up stuff */
1264 /* ------------------------------------------------------------------------- */
1265 /* checked memory allocation and freeing functions */
1266 /* ------------------------------------------------------------------------- */
1268 void *checked_malloc(unsigned int size)
1275 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1280 void *checked_calloc(unsigned int size)
1284 ptr = calloc(1, size);
1287 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1292 void *checked_realloc(void *ptr, unsigned int size)
1294 ptr = realloc(ptr, size);
1297 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1302 void checked_free(void *ptr)
1304 if (ptr != NULL) /* this check should be done by free() anyway */
1308 void clear_mem(void *ptr, unsigned int size)
1310 #if defined(PLATFORM_WIN32)
1311 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1312 char *cptr = (char *)ptr;
1317 memset(ptr, 0, size);
1322 /* ------------------------------------------------------------------------- */
1323 /* various helper functions */
1324 /* ------------------------------------------------------------------------- */
1326 void swap_numbers(int *i1, int *i2)
1334 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1346 /* the "put" variants of the following file access functions check for the file
1347 pointer being != NULL and return the number of bytes they have or would have
1348 written; this allows for chunk writing functions to first determine the size
1349 of the (not yet written) chunk, write the correct chunk size and finally
1350 write the chunk itself */
1352 int getFile8BitInteger(File *file)
1354 return getByteFromFile(file);
1357 int putFile8BitInteger(FILE *file, int value)
1365 int getFile16BitInteger(File *file, int byte_order)
1367 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1368 return ((getByteFromFile(file) << 8) |
1369 (getByteFromFile(file) << 0));
1370 else /* BYTE_ORDER_LITTLE_ENDIAN */
1371 return ((getByteFromFile(file) << 0) |
1372 (getByteFromFile(file) << 8));
1375 int putFile16BitInteger(FILE *file, int value, int byte_order)
1379 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1381 fputc((value >> 8) & 0xff, file);
1382 fputc((value >> 0) & 0xff, file);
1384 else /* BYTE_ORDER_LITTLE_ENDIAN */
1386 fputc((value >> 0) & 0xff, file);
1387 fputc((value >> 8) & 0xff, file);
1394 int getFile32BitInteger(File *file, int byte_order)
1396 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1397 return ((getByteFromFile(file) << 24) |
1398 (getByteFromFile(file) << 16) |
1399 (getByteFromFile(file) << 8) |
1400 (getByteFromFile(file) << 0));
1401 else /* BYTE_ORDER_LITTLE_ENDIAN */
1402 return ((getByteFromFile(file) << 0) |
1403 (getByteFromFile(file) << 8) |
1404 (getByteFromFile(file) << 16) |
1405 (getByteFromFile(file) << 24));
1408 int putFile32BitInteger(FILE *file, int value, int byte_order)
1412 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1414 fputc((value >> 24) & 0xff, file);
1415 fputc((value >> 16) & 0xff, file);
1416 fputc((value >> 8) & 0xff, file);
1417 fputc((value >> 0) & 0xff, file);
1419 else /* BYTE_ORDER_LITTLE_ENDIAN */
1421 fputc((value >> 0) & 0xff, file);
1422 fputc((value >> 8) & 0xff, file);
1423 fputc((value >> 16) & 0xff, file);
1424 fputc((value >> 24) & 0xff, file);
1431 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1434 const int chunk_name_length = 4;
1436 /* read chunk name */
1437 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1440 if (chunk_size != NULL)
1442 /* read chunk size */
1443 *chunk_size = getFile32BitInteger(file, byte_order);
1446 return (checkEndOfFile(file) ? FALSE : TRUE);
1449 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1454 /* write chunk name */
1456 fputs(chunk_name, file);
1458 num_bytes += strlen(chunk_name);
1460 if (chunk_size >= 0)
1462 /* write chunk size */
1464 putFile32BitInteger(file, chunk_size, byte_order);
1472 int getFileVersion(File *file)
1474 int version_major = getByteFromFile(file);
1475 int version_minor = getByteFromFile(file);
1476 int version_patch = getByteFromFile(file);
1477 int version_build = getByteFromFile(file);
1479 return VERSION_IDENT(version_major, version_minor, version_patch,
1483 int putFileVersion(FILE *file, int version)
1487 int version_major = VERSION_MAJOR(version);
1488 int version_minor = VERSION_MINOR(version);
1489 int version_patch = VERSION_PATCH(version);
1490 int version_build = VERSION_BUILD(version);
1492 fputc(version_major, file);
1493 fputc(version_minor, file);
1494 fputc(version_patch, file);
1495 fputc(version_build, file);
1501 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1505 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1506 buffer[i] = getByteFromFile(file);
1509 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1513 for(i = 0; i < bytes; i++)
1514 fputc(buffer[i], file);
1517 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1519 while (bytes-- && !checkEndOfFile(file))
1520 getByteFromFile(file);
1523 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1530 /* ------------------------------------------------------------------------- */
1531 /* functions to translate key identifiers between different format */
1532 /* ------------------------------------------------------------------------- */
1534 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1535 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1536 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1537 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1539 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1548 /* normal cursor keys */
1549 { KSYM_Left, "XK_Left", "cursor left" },
1550 { KSYM_Right, "XK_Right", "cursor right" },
1551 { KSYM_Up, "XK_Up", "cursor up" },
1552 { KSYM_Down, "XK_Down", "cursor down" },
1554 /* keypad cursor keys */
1556 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1557 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1558 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1559 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1562 /* other keypad keys */
1563 #ifdef KSYM_KP_Enter
1564 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1565 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1566 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1567 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1568 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1569 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1573 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1574 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1575 { KSYM_Control_L, "XK_Control_L", "left control" },
1576 { KSYM_Control_R, "XK_Control_R", "right control" },
1577 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1578 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1579 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1580 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1581 #if !defined(TARGET_SDL2)
1582 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1583 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1585 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1586 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1588 /* some special keys */
1589 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1590 { KSYM_Delete, "XK_Delete", "delete" },
1591 { KSYM_Insert, "XK_Insert", "insert" },
1592 { KSYM_Tab, "XK_Tab", "tab" },
1593 { KSYM_Home, "XK_Home", "home" },
1594 { KSYM_End, "XK_End", "end" },
1595 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1596 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1598 #if defined(TARGET_SDL2)
1599 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1600 { KSYM_Back, "XK_Back", "back" }, /* back key */
1603 /* ASCII 0x20 to 0x40 keys (except numbers) */
1604 { KSYM_space, "XK_space", "space" },
1605 { KSYM_exclam, "XK_exclam", "!" },
1606 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1607 { KSYM_numbersign, "XK_numbersign", "#" },
1608 { KSYM_dollar, "XK_dollar", "$" },
1609 { KSYM_percent, "XK_percent", "%" },
1610 { KSYM_ampersand, "XK_ampersand", "&" },
1611 { KSYM_apostrophe, "XK_apostrophe", "'" },
1612 { KSYM_parenleft, "XK_parenleft", "(" },
1613 { KSYM_parenright, "XK_parenright", ")" },
1614 { KSYM_asterisk, "XK_asterisk", "*" },
1615 { KSYM_plus, "XK_plus", "+" },
1616 { KSYM_comma, "XK_comma", "," },
1617 { KSYM_minus, "XK_minus", "-" },
1618 { KSYM_period, "XK_period", "." },
1619 { KSYM_slash, "XK_slash", "/" },
1620 { KSYM_colon, "XK_colon", ":" },
1621 { KSYM_semicolon, "XK_semicolon", ";" },
1622 { KSYM_less, "XK_less", "<" },
1623 { KSYM_equal, "XK_equal", "=" },
1624 { KSYM_greater, "XK_greater", ">" },
1625 { KSYM_question, "XK_question", "?" },
1626 { KSYM_at, "XK_at", "@" },
1628 /* more ASCII keys */
1629 { KSYM_bracketleft, "XK_bracketleft", "[" },
1630 { KSYM_backslash, "XK_backslash", "\\" },
1631 { KSYM_bracketright,"XK_bracketright", "]" },
1632 { KSYM_asciicircum, "XK_asciicircum", "^" },
1633 { KSYM_underscore, "XK_underscore", "_" },
1634 { KSYM_grave, "XK_grave", "grave" },
1635 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1636 { KSYM_braceleft, "XK_braceleft", "brace left" },
1637 { KSYM_bar, "XK_bar", "bar" },
1638 { KSYM_braceright, "XK_braceright", "brace right" },
1639 { KSYM_asciitilde, "XK_asciitilde", "~" },
1641 /* special (non-ASCII) keys */
1642 { KSYM_degree, "XK_degree", "degree" },
1643 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1644 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1645 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1646 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1647 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1648 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1649 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1651 #if defined(TARGET_SDL2)
1652 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1653 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1654 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1655 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1656 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1657 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1658 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1659 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1660 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1662 /* other keys (for reverse mapping only) */
1663 { KSYM_space, "XK_space", " " },
1666 #if defined(TARGET_SDL2)
1667 /* keypad keys are not in numerical order in SDL2 */
1668 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1669 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1670 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1671 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1672 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1673 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1674 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1675 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1676 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1677 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1680 /* end-of-array identifier */
1686 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1688 static char name_buffer[30];
1691 if (key >= KSYM_A && key <= KSYM_Z)
1692 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1693 else if (key >= KSYM_a && key <= KSYM_z)
1694 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1695 else if (key >= KSYM_0 && key <= KSYM_9)
1696 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1697 #if !defined(TARGET_SDL2)
1698 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1699 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1701 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1702 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1703 else if (key == KSYM_UNDEFINED)
1704 strcpy(name_buffer, "(undefined)");
1711 if (key == translate_key[i].key)
1713 strcpy(name_buffer, translate_key[i].name);
1717 while (translate_key[++i].name);
1719 if (!translate_key[i].name)
1720 strcpy(name_buffer, "(unknown)");
1723 *name = name_buffer;
1725 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1727 static char name_buffer[30];
1730 if (key >= KSYM_A && key <= KSYM_Z)
1731 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1732 else if (key >= KSYM_a && key <= KSYM_z)
1733 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1734 else if (key >= KSYM_0 && key <= KSYM_9)
1735 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1736 #if !defined(TARGET_SDL2)
1737 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1738 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1740 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1741 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1742 else if (key == KSYM_UNDEFINED)
1743 strcpy(name_buffer, "[undefined]");
1750 if (key == translate_key[i].key)
1752 strcpy(name_buffer, translate_key[i].x11name);
1756 while (translate_key[++i].x11name);
1758 if (!translate_key[i].x11name)
1759 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1762 *x11name = name_buffer;
1764 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1766 Key key = KSYM_UNDEFINED;
1767 char *name_ptr = *name;
1769 if (strlen(*name) == 1)
1771 char c = name_ptr[0];
1773 if (c >= 'A' && c <= 'Z')
1774 key = KSYM_A + (Key)(c - 'A');
1775 else if (c >= 'a' && c <= 'z')
1776 key = KSYM_a + (Key)(c - 'a');
1777 else if (c >= '0' && c <= '9')
1778 key = KSYM_0 + (Key)(c - '0');
1781 if (key == KSYM_UNDEFINED)
1787 if (strEqual(translate_key[i].name, *name))
1789 key = translate_key[i].key;
1793 while (translate_key[++i].x11name);
1796 if (key == KSYM_UNDEFINED)
1797 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1801 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1803 Key key = KSYM_UNDEFINED;
1804 char *name_ptr = *x11name;
1806 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1808 char c = name_ptr[3];
1810 if (c >= 'A' && c <= 'Z')
1811 key = KSYM_A + (Key)(c - 'A');
1812 else if (c >= 'a' && c <= 'z')
1813 key = KSYM_a + (Key)(c - 'a');
1814 else if (c >= '0' && c <= '9')
1815 key = KSYM_0 + (Key)(c - '0');
1817 #if !defined(TARGET_SDL2)
1818 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1820 char c = name_ptr[6];
1822 if (c >= '0' && c <= '9')
1823 key = KSYM_KP_0 + (Key)(c - '0');
1826 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1828 char c1 = name_ptr[4];
1829 char c2 = name_ptr[5];
1832 if ((c1 >= '0' && c1 <= '9') &&
1833 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1834 d = atoi(&name_ptr[4]);
1836 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1837 key = KSYM_F1 + (Key)(d - 1);
1839 else if (strPrefix(name_ptr, "XK_"))
1845 if (strEqual(name_ptr, translate_key[i].x11name))
1847 key = translate_key[i].key;
1851 while (translate_key[++i].x11name);
1853 else if (strPrefix(name_ptr, "0x"))
1855 unsigned int value = 0;
1861 char c = *name_ptr++;
1864 if (c >= '0' && c <= '9')
1866 else if (c >= 'a' && c <= 'f')
1867 d = (int)(c - 'a' + 10);
1868 else if (c >= 'A' && c <= 'F')
1869 d = (int)(c - 'A' + 10);
1877 value = value * 16 + d;
1888 char *getKeyNameFromKey(Key key)
1892 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1896 char *getX11KeyNameFromKey(Key key)
1900 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1904 Key getKeyFromKeyName(char *name)
1908 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1912 Key getKeyFromX11KeyName(char *x11name)
1916 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1920 char getCharFromKey(Key key)
1926 } translate_key_char[] =
1928 /* special (non-ASCII) keys (ISO-8859-1) */
1929 { KSYM_degree, CHAR_BYTE_DEGREE },
1930 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1931 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1932 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1933 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1934 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1935 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1936 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1938 /* end-of-array identifier */
1942 char *keyname = getKeyNameFromKey(key);
1945 if (strlen(keyname) == 1)
1947 else if (strEqual(keyname, "space"))
1955 if (key == translate_key_char[i].key)
1957 c = translate_key_char[i].key_char;
1962 while (translate_key_char[++i].key_char);
1968 char getValidConfigValueChar(char c)
1970 if (c == '#' || /* used to mark comments */
1971 c == '\\') /* used to mark continued lines */
1978 /* ------------------------------------------------------------------------- */
1979 /* functions to translate string identifiers to integer or boolean value */
1980 /* ------------------------------------------------------------------------- */
1982 int get_integer_from_string(char *s)
1984 static char *number_text[][3] =
1986 { "0", "zero", "null", },
1987 { "1", "one", "first" },
1988 { "2", "two", "second" },
1989 { "3", "three", "third" },
1990 { "4", "four", "fourth" },
1991 { "5", "five", "fifth" },
1992 { "6", "six", "sixth" },
1993 { "7", "seven", "seventh" },
1994 { "8", "eight", "eighth" },
1995 { "9", "nine", "ninth" },
1996 { "10", "ten", "tenth" },
1997 { "11", "eleven", "eleventh" },
1998 { "12", "twelve", "twelfth" },
2000 { NULL, NULL, NULL },
2004 char *s_lower = getStringToLower(s);
2007 for (i = 0; number_text[i][0] != NULL; i++)
2008 for (j = 0; j < 3; j++)
2009 if (strEqual(s_lower, number_text[i][j]))
2014 if (strEqual(s_lower, "false") ||
2015 strEqual(s_lower, "no") ||
2016 strEqual(s_lower, "off"))
2018 else if (strEqual(s_lower, "true") ||
2019 strEqual(s_lower, "yes") ||
2020 strEqual(s_lower, "on"))
2031 boolean get_boolean_from_string(char *s)
2033 char *s_lower = getStringToLower(s);
2034 boolean result = FALSE;
2036 if (strEqual(s_lower, "true") ||
2037 strEqual(s_lower, "yes") ||
2038 strEqual(s_lower, "on") ||
2039 get_integer_from_string(s) == 1)
2047 int get_switch3_from_string(char *s)
2049 char *s_lower = getStringToLower(s);
2052 if (strEqual(s_lower, "true") ||
2053 strEqual(s_lower, "yes") ||
2054 strEqual(s_lower, "on") ||
2055 get_integer_from_string(s) == 1)
2057 else if (strEqual(s_lower, "auto"))
2066 /* ------------------------------------------------------------------------- */
2067 /* functions for generic lists */
2068 /* ------------------------------------------------------------------------- */
2070 ListNode *newListNode()
2072 return checked_calloc(sizeof(ListNode));
2075 void addNodeToList(ListNode **node_first, char *key, void *content)
2077 ListNode *node_new = newListNode();
2079 node_new->key = getStringCopy(key);
2080 node_new->content = content;
2081 node_new->next = *node_first;
2084 (*node_first)->prev = node_new;
2086 *node_first = node_new;
2089 void deleteNodeFromList(ListNode **node_first, char *key,
2090 void (*destructor_function)(void *))
2092 if (node_first == NULL || *node_first == NULL)
2095 if (strEqual((*node_first)->key, key))
2097 checked_free((*node_first)->key);
2099 if (destructor_function)
2100 destructor_function((*node_first)->content);
2102 if ((*node_first)->next)
2103 (*node_first)->next->prev = (*node_first)->prev;
2105 checked_free(*node_first);
2107 *node_first = (*node_first)->next;
2110 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2113 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2115 if (node_first == NULL)
2118 if (strEqual(node_first->key, key))
2121 return getNodeFromKey(node_first->next, key);
2124 int getNumNodes(ListNode *node_first)
2126 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2129 void dumpList(ListNode *node_first)
2131 ListNode *node = node_first;
2135 printf("['%s' (%d)]\n", node->key,
2136 ((struct ListNodeInfo *)node->content)->num_references);
2140 printf("[%d nodes]\n", getNumNodes(node_first));
2144 /* ------------------------------------------------------------------------- */
2145 /* functions for file handling */
2146 /* ------------------------------------------------------------------------- */
2148 File *openFile(char *filename, char *mode)
2150 File *file = checked_calloc(sizeof(File));
2152 file->file = fopen(filename, mode);
2154 if (file->file != NULL)
2156 file->filename = getStringCopy(filename);
2161 #if defined(PLATFORM_ANDROID)
2162 file->asset_file = SDL_RWFromFile(filename, mode);
2164 if (file->asset_file != NULL)
2166 file->file_is_asset = TRUE;
2167 file->filename = getStringCopy(filename);
2178 int closeFile(File *file)
2185 #if defined(PLATFORM_ANDROID)
2186 if (file->asset_file)
2187 result = SDL_RWclose(file->asset_file);
2191 result = fclose(file->file);
2193 checked_free(file->filename);
2199 int checkEndOfFile(File *file)
2201 #if defined(PLATFORM_ANDROID)
2202 if (file->file_is_asset)
2203 return file->end_of_file;
2206 return feof(file->file);
2209 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2211 #if defined(PLATFORM_ANDROID)
2212 if (file->file_is_asset)
2214 if (file->end_of_file)
2217 size_t num_items_read =
2218 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2220 if (num_items_read < num_items)
2221 file->end_of_file = TRUE;
2223 return num_items_read;
2227 return fread(buffer, item_size, num_items, file->file);
2230 int seekFile(File *file, long offset, int whence)
2232 #if defined(PLATFORM_ANDROID)
2233 if (file->file_is_asset)
2235 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2236 whence == SEEK_CUR ? RW_SEEK_CUR :
2237 whence == SEEK_END ? RW_SEEK_END : 0);
2239 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2243 return fseek(file->file, offset, whence);
2246 int getByteFromFile(File *file)
2248 #if defined(PLATFORM_ANDROID)
2249 if (file->file_is_asset)
2251 if (file->end_of_file)
2255 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2257 if (num_bytes_read < 1)
2258 file->end_of_file = TRUE;
2260 return (file->end_of_file ? EOF : (int)c);
2264 return fgetc(file->file);
2267 char *getStringFromFile(File *file, char *line, int size)
2269 #if defined(PLATFORM_ANDROID)
2270 if (file->file_is_asset)
2272 if (file->end_of_file)
2275 char *line_ptr = line;
2276 int num_bytes_read = 0;
2278 while (num_bytes_read < size - 1 &&
2279 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2280 *line_ptr++ != '\n')
2285 if (strlen(line) == 0)
2287 file->end_of_file = TRUE;
2296 return fgets(line, size, file->file);
2300 /* ------------------------------------------------------------------------- */
2301 /* functions for directory handling */
2302 /* ------------------------------------------------------------------------- */
2304 Directory *openDirectory(char *dir_name)
2306 Directory *dir = checked_calloc(sizeof(Directory));
2308 dir->dir = opendir(dir_name);
2310 if (dir->dir != NULL)
2312 dir->filename = getStringCopy(dir_name);
2317 #if defined(PLATFORM_ANDROID)
2318 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2320 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2322 checked_free(asset_toc_filename);
2324 if (dir->asset_toc_file != NULL)
2326 dir->directory_is_asset = TRUE;
2327 dir->filename = getStringCopy(dir_name);
2338 int closeDirectory(Directory *dir)
2345 #if defined(PLATFORM_ANDROID)
2346 if (dir->asset_toc_file)
2347 result = SDL_RWclose(dir->asset_toc_file);
2351 result = closedir(dir->dir);
2354 freeDirectoryEntry(dir->dir_entry);
2356 checked_free(dir->filename);
2362 DirectoryEntry *readDirectory(Directory *dir)
2365 freeDirectoryEntry(dir->dir_entry);
2367 dir->dir_entry = NULL;
2369 #if defined(PLATFORM_ANDROID)
2370 if (dir->directory_is_asset)
2372 char line[MAX_LINE_LEN];
2373 char *line_ptr = line;
2374 int num_bytes_read = 0;
2376 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2377 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2386 if (strlen(line) == 0)
2389 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2391 dir->dir_entry->is_directory = FALSE;
2392 if (line[strlen(line) - 1] == '/')
2394 dir->dir_entry->is_directory = TRUE;
2396 line[strlen(line) - 1] = '\0';
2399 dir->dir_entry->basename = getStringCopy(line);
2400 dir->dir_entry->filename = getPath2(dir->filename, line);
2402 return dir->dir_entry;
2406 struct dirent *dir_entry = readdir(dir->dir);
2408 if (dir_entry == NULL)
2411 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2413 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2414 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2416 struct stat file_status;
2418 dir->dir_entry->is_directory =
2419 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2420 S_ISDIR(file_status.st_mode));
2422 return dir->dir_entry;
2425 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2427 if (dir_entry == NULL)
2430 checked_free(dir_entry->basename);
2431 checked_free(dir_entry->filename);
2432 checked_free(dir_entry);
2436 /* ------------------------------------------------------------------------- */
2437 /* functions for checking files and filenames */
2438 /* ------------------------------------------------------------------------- */
2440 boolean directoryExists(char *dir_name)
2442 if (dir_name == NULL)
2445 struct stat file_status;
2446 boolean success = (stat(dir_name, &file_status) == 0 &&
2447 S_ISDIR(file_status.st_mode));
2449 #if defined(PLATFORM_ANDROID)
2452 // this might be an asset directory; check by trying to open toc file
2453 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2454 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2456 checked_free(asset_toc_filename);
2458 success = (file != NULL);
2468 boolean fileExists(char *filename)
2470 if (filename == NULL)
2473 boolean success = (access(filename, F_OK) == 0);
2475 #if defined(PLATFORM_ANDROID)
2478 // this might be an asset file; check by trying to open it
2479 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2481 success = (file != NULL);
2491 boolean fileHasPrefix(char *basename, char *prefix)
2493 static char *basename_lower = NULL;
2494 int basename_length, prefix_length;
2496 checked_free(basename_lower);
2498 if (basename == NULL || prefix == NULL)
2501 basename_lower = getStringToLower(basename);
2502 basename_length = strlen(basename_lower);
2503 prefix_length = strlen(prefix);
2505 if (basename_length > prefix_length + 1 &&
2506 basename_lower[prefix_length] == '.' &&
2507 strncmp(basename_lower, prefix, prefix_length) == 0)
2513 boolean fileHasSuffix(char *basename, char *suffix)
2515 static char *basename_lower = NULL;
2516 int basename_length, suffix_length;
2518 checked_free(basename_lower);
2520 if (basename == NULL || suffix == NULL)
2523 basename_lower = getStringToLower(basename);
2524 basename_length = strlen(basename_lower);
2525 suffix_length = strlen(suffix);
2527 if (basename_length > suffix_length + 1 &&
2528 basename_lower[basename_length - suffix_length - 1] == '.' &&
2529 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2535 static boolean FileCouldBeArtwork(char *filename)
2537 char *basename = getBaseNamePtr(filename);
2539 return (!strEqual(basename, ".") &&
2540 !strEqual(basename, "..") &&
2541 !fileHasSuffix(basename, "txt") &&
2542 !fileHasSuffix(basename, "conf") &&
2543 !directoryExists(filename));
2546 boolean FileIsGraphic(char *filename)
2548 return FileCouldBeArtwork(filename);
2551 boolean FileIsSound(char *filename)
2553 return FileCouldBeArtwork(filename);
2556 boolean FileIsMusic(char *filename)
2558 return FileCouldBeArtwork(filename);
2561 boolean FileIsArtworkType(char *filename, int type)
2563 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2564 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2565 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2571 /* ------------------------------------------------------------------------- */
2572 /* functions for loading artwork configuration information */
2573 /* ------------------------------------------------------------------------- */
2575 char *get_mapped_token(char *token)
2577 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2578 static char *map_token_prefix[][2] =
2580 { "char_procent", "char_percent" },
2585 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2587 int len_token_prefix = strlen(map_token_prefix[i][0]);
2589 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2590 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2596 /* This function checks if a string <s> of the format "string1, string2, ..."
2597 exactly contains a string <s_contained>. */
2599 static boolean string_has_parameter(char *s, char *s_contained)
2603 if (s == NULL || s_contained == NULL)
2606 if (strlen(s_contained) > strlen(s))
2609 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2611 char next_char = s[strlen(s_contained)];
2613 /* check if next character is delimiter or whitespace */
2614 return (next_char == ',' || next_char == '\0' ||
2615 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2618 /* check if string contains another parameter string after a comma */
2619 substring = strchr(s, ',');
2620 if (substring == NULL) /* string does not contain a comma */
2623 /* advance string pointer to next character after the comma */
2626 /* skip potential whitespaces after the comma */
2627 while (*substring == ' ' || *substring == '\t')
2630 return string_has_parameter(substring, s_contained);
2633 int get_parameter_value(char *value_raw, char *suffix, int type)
2635 char *value = getStringToLower(value_raw);
2636 int result = 0; /* probably a save default value */
2638 if (strEqual(suffix, ".direction"))
2640 result = (strEqual(value, "left") ? MV_LEFT :
2641 strEqual(value, "right") ? MV_RIGHT :
2642 strEqual(value, "up") ? MV_UP :
2643 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2645 else if (strEqual(suffix, ".align"))
2647 result = (strEqual(value, "left") ? ALIGN_LEFT :
2648 strEqual(value, "right") ? ALIGN_RIGHT :
2649 strEqual(value, "center") ? ALIGN_CENTER :
2650 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2652 else if (strEqual(suffix, ".valign"))
2654 result = (strEqual(value, "top") ? VALIGN_TOP :
2655 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2656 strEqual(value, "middle") ? VALIGN_MIDDLE :
2657 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2659 else if (strEqual(suffix, ".anim_mode"))
2661 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2662 string_has_parameter(value, "loop") ? ANIM_LOOP :
2663 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2664 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2665 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2666 string_has_parameter(value, "random") ? ANIM_RANDOM :
2667 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2668 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2669 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2670 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2671 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2672 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2675 if (string_has_parameter(value, "reverse"))
2676 result |= ANIM_REVERSE;
2678 if (string_has_parameter(value, "opaque_player"))
2679 result |= ANIM_OPAQUE_PLAYER;
2681 if (string_has_parameter(value, "static_panel"))
2682 result |= ANIM_STATIC_PANEL;
2684 else if (strEqual(suffix, ".class"))
2686 result = get_hash_from_key(value);
2688 else if (strEqual(suffix, ".style"))
2690 result = STYLE_DEFAULT;
2692 if (string_has_parameter(value, "accurate_borders"))
2693 result |= STYLE_ACCURATE_BORDERS;
2695 if (string_has_parameter(value, "inner_corners"))
2696 result |= STYLE_INNER_CORNERS;
2698 else if (strEqual(suffix, ".fade_mode"))
2700 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2701 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2702 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2703 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2706 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2708 result = gfx.get_font_from_token_function(value);
2710 else /* generic parameter of type integer or boolean */
2712 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2713 type == TYPE_INTEGER ? get_integer_from_string(value) :
2714 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2715 ARG_UNDEFINED_VALUE);
2723 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2725 static struct ScreenModeInfo screen_mode;
2726 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2727 char *screen_mode_string_copy;
2728 char *screen_mode_string_pos_w;
2729 char *screen_mode_string_pos_h;
2731 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2734 screen_mode_string_copy = getStringCopy(screen_mode_string);
2736 screen_mode_string_pos_w = screen_mode_string_copy;
2737 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2738 *screen_mode_string_pos_h++ = '\0';
2740 screen_mode.width = atoi(screen_mode_string_pos_w);
2741 screen_mode.height = atoi(screen_mode_string_pos_h);
2743 return &screen_mode;
2746 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2749 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2750 float aspect_ratio_new;
2755 *x = i * aspect_ratio + 0.000001;
2758 aspect_ratio_new = (float)*x / (float)*y;
2762 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2765 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2766 struct ListNodeInfo ***, int *);
2768 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2769 struct ConfigTypeInfo *suffix_list,
2770 char **ignore_tokens,
2771 int num_file_list_entries)
2773 struct FileInfo *file_list;
2774 int num_file_list_entries_found = 0;
2775 int num_suffix_list_entries = 0;
2779 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2781 for (i = 0; suffix_list[i].token != NULL; i++)
2782 num_suffix_list_entries++;
2784 /* always start with reliable default values */
2785 for (i = 0; i < num_file_list_entries; i++)
2787 file_list[i].token = NULL;
2789 file_list[i].default_filename = NULL;
2790 file_list[i].filename = NULL;
2792 if (num_suffix_list_entries > 0)
2794 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2796 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2797 file_list[i].parameter = checked_calloc(parameter_array_size);
2799 for (j = 0; j < num_suffix_list_entries; j++)
2801 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2802 setString(&file_list[i].parameter[j], suffix_list[j].value);
2805 file_list[i].redefined = FALSE;
2806 file_list[i].fallback_to_default = FALSE;
2807 file_list[i].default_is_cloned = FALSE;
2813 for (i = 0; config_list[i].token != NULL; i++)
2815 int len_config_token = strlen(config_list[i].token);
2816 boolean is_file_entry = TRUE;
2818 for (j = 0; suffix_list[j].token != NULL; j++)
2820 int len_suffix = strlen(suffix_list[j].token);
2822 if (len_suffix < len_config_token &&
2823 strEqual(&config_list[i].token[len_config_token - len_suffix],
2824 suffix_list[j].token))
2826 setString(&file_list[list_pos].default_parameter[j],
2827 config_list[i].value);
2829 is_file_entry = FALSE;
2835 /* the following tokens are no file definitions, but other config tokens */
2836 for (j = 0; ignore_tokens[j] != NULL; j++)
2837 if (strEqual(config_list[i].token, ignore_tokens[j]))
2838 is_file_entry = FALSE;
2845 if (list_pos >= num_file_list_entries)
2848 file_list[list_pos].token = config_list[i].token;
2849 file_list[list_pos].default_filename = config_list[i].value;
2852 if (strSuffix(config_list[i].token, ".clone_from"))
2853 file_list[list_pos].default_is_cloned = TRUE;
2856 num_file_list_entries_found = list_pos + 1;
2857 if (num_file_list_entries_found != num_file_list_entries)
2859 Error(ERR_INFO_LINE, "-");
2860 Error(ERR_INFO, "inconsistant config list information:");
2861 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2862 num_file_list_entries);
2863 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2864 num_file_list_entries_found);
2865 Error(ERR_EXIT, "please fix");
2871 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2873 int len_token = strlen(token);
2874 int len_suffix = strlen(suffix);
2876 if (start_pos < 0) /* compare suffix from end of string */
2877 start_pos += len_token;
2879 if (start_pos < 0 || start_pos + len_suffix > len_token)
2882 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2885 if (token[start_pos + len_suffix] == '\0')
2888 if (token[start_pos + len_suffix] == '.')
2894 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2896 static void read_token_parameters(SetupFileHash *setup_file_hash,
2897 struct ConfigTypeInfo *suffix_list,
2898 struct FileInfo *file_list_entry)
2900 /* check for config token that is the base token without any suffixes */
2901 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2902 char *known_token_value = KNOWN_TOKEN_VALUE;
2905 if (filename != NULL)
2907 setString(&file_list_entry->filename, filename);
2909 /* when file definition found, set all parameters to default values */
2910 for (i = 0; suffix_list[i].token != NULL; i++)
2911 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2913 file_list_entry->redefined = TRUE;
2915 /* mark config file token as well known from default config */
2916 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2919 /* check for config tokens that can be build by base token and suffixes */
2920 for (i = 0; suffix_list[i].token != NULL; i++)
2922 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2923 char *value = getHashEntry(setup_file_hash, token);
2927 setString(&file_list_entry->parameter[i], value);
2929 /* mark config file token as well known from default config */
2930 setHashEntry(setup_file_hash, token, known_token_value);
2937 static void add_dynamic_file_list_entry(struct FileInfo **list,
2938 int *num_list_entries,
2939 SetupFileHash *extra_file_hash,
2940 struct ConfigTypeInfo *suffix_list,
2941 int num_suffix_list_entries,
2944 struct FileInfo *new_list_entry;
2945 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2947 (*num_list_entries)++;
2948 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2949 new_list_entry = &(*list)[*num_list_entries - 1];
2951 new_list_entry->token = getStringCopy(token);
2952 new_list_entry->default_filename = NULL;
2953 new_list_entry->filename = NULL;
2954 new_list_entry->parameter = checked_calloc(parameter_array_size);
2956 new_list_entry->redefined = FALSE;
2957 new_list_entry->fallback_to_default = FALSE;
2958 new_list_entry->default_is_cloned = FALSE;
2960 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2963 static void add_property_mapping(struct PropertyMapping **list,
2964 int *num_list_entries,
2965 int base_index, int ext1_index,
2966 int ext2_index, int ext3_index,
2969 struct PropertyMapping *new_list_entry;
2971 (*num_list_entries)++;
2972 *list = checked_realloc(*list,
2973 *num_list_entries * sizeof(struct PropertyMapping));
2974 new_list_entry = &(*list)[*num_list_entries - 1];
2976 new_list_entry->base_index = base_index;
2977 new_list_entry->ext1_index = ext1_index;
2978 new_list_entry->ext2_index = ext2_index;
2979 new_list_entry->ext3_index = ext3_index;
2981 new_list_entry->artwork_index = artwork_index;
2984 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2987 struct FileInfo *file_list = artwork_info->file_list;
2988 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2989 char **base_prefixes = artwork_info->base_prefixes;
2990 char **ext1_suffixes = artwork_info->ext1_suffixes;
2991 char **ext2_suffixes = artwork_info->ext2_suffixes;
2992 char **ext3_suffixes = artwork_info->ext3_suffixes;
2993 char **ignore_tokens = artwork_info->ignore_tokens;
2994 int num_file_list_entries = artwork_info->num_file_list_entries;
2995 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2996 int num_base_prefixes = artwork_info->num_base_prefixes;
2997 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2998 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2999 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3000 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3001 SetupFileHash *setup_file_hash, *valid_file_hash;
3002 SetupFileHash *extra_file_hash, *empty_file_hash;
3003 char *known_token_value = KNOWN_TOKEN_VALUE;
3006 if (filename == NULL)
3009 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3012 /* separate valid (defined) from empty (undefined) config token values */
3013 valid_file_hash = newSetupFileHash();
3014 empty_file_hash = newSetupFileHash();
3015 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3017 char *value = HASH_ITERATION_VALUE(itr);
3019 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3020 HASH_ITERATION_TOKEN(itr), value);
3022 END_HASH_ITERATION(setup_file_hash, itr)
3024 /* at this point, we do not need the setup file hash anymore -- free it */
3025 freeSetupFileHash(setup_file_hash);
3027 /* map deprecated to current tokens (using prefix match and replace) */
3028 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3030 char *token = HASH_ITERATION_TOKEN(itr);
3031 char *mapped_token = get_mapped_token(token);
3033 if (mapped_token != NULL)
3035 char *value = HASH_ITERATION_VALUE(itr);
3037 /* add mapped token */
3038 setHashEntry(valid_file_hash, mapped_token, value);
3040 /* ignore old token (by setting it to "known" keyword) */
3041 setHashEntry(valid_file_hash, token, known_token_value);
3046 END_HASH_ITERATION(valid_file_hash, itr)
3048 /* read parameters for all known config file tokens */
3049 for (i = 0; i < num_file_list_entries; i++)
3050 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3052 /* set all tokens that can be ignored here to "known" keyword */
3053 for (i = 0; i < num_ignore_tokens; i++)
3054 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3056 /* copy all unknown config file tokens to extra config hash */
3057 extra_file_hash = newSetupFileHash();
3058 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3060 char *value = HASH_ITERATION_VALUE(itr);
3062 if (!strEqual(value, known_token_value))
3063 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3065 END_HASH_ITERATION(valid_file_hash, itr)
3067 /* at this point, we do not need the valid file hash anymore -- free it */
3068 freeSetupFileHash(valid_file_hash);
3070 /* now try to determine valid, dynamically defined config tokens */
3072 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3074 struct FileInfo **dynamic_file_list =
3075 &artwork_info->dynamic_file_list;
3076 int *num_dynamic_file_list_entries =
3077 &artwork_info->num_dynamic_file_list_entries;
3078 struct PropertyMapping **property_mapping =
3079 &artwork_info->property_mapping;
3080 int *num_property_mapping_entries =
3081 &artwork_info->num_property_mapping_entries;
3082 int current_summarized_file_list_entry =
3083 artwork_info->num_file_list_entries +
3084 artwork_info->num_dynamic_file_list_entries;
3085 char *token = HASH_ITERATION_TOKEN(itr);
3086 int len_token = strlen(token);
3088 boolean base_prefix_found = FALSE;
3089 boolean parameter_suffix_found = FALSE;
3091 /* skip all parameter definitions (handled by read_token_parameters()) */
3092 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3094 int len_suffix = strlen(suffix_list[i].token);
3096 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3097 parameter_suffix_found = TRUE;
3100 if (parameter_suffix_found)
3103 /* ---------- step 0: search for matching base prefix ---------- */
3106 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3108 char *base_prefix = base_prefixes[i];
3109 int len_base_prefix = strlen(base_prefix);
3110 boolean ext1_suffix_found = FALSE;
3111 boolean ext2_suffix_found = FALSE;
3112 boolean ext3_suffix_found = FALSE;
3113 boolean exact_match = FALSE;
3114 int base_index = -1;
3115 int ext1_index = -1;
3116 int ext2_index = -1;
3117 int ext3_index = -1;
3119 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3121 if (!base_prefix_found)
3126 if (start_pos + len_base_prefix == len_token) /* exact match */
3130 add_dynamic_file_list_entry(dynamic_file_list,
3131 num_dynamic_file_list_entries,
3134 num_suffix_list_entries,
3136 add_property_mapping(property_mapping,
3137 num_property_mapping_entries,
3138 base_index, -1, -1, -1,
3139 current_summarized_file_list_entry);
3143 /* ---------- step 1: search for matching first suffix ---------- */
3145 start_pos += len_base_prefix;
3146 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3148 char *ext1_suffix = ext1_suffixes[j];
3149 int len_ext1_suffix = strlen(ext1_suffix);
3151 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3153 if (!ext1_suffix_found)
3158 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3162 add_dynamic_file_list_entry(dynamic_file_list,
3163 num_dynamic_file_list_entries,
3166 num_suffix_list_entries,
3168 add_property_mapping(property_mapping,
3169 num_property_mapping_entries,
3170 base_index, ext1_index, -1, -1,
3171 current_summarized_file_list_entry);
3175 start_pos += len_ext1_suffix;
3181 /* ---------- step 2: search for matching second suffix ---------- */
3183 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3185 char *ext2_suffix = ext2_suffixes[k];
3186 int len_ext2_suffix = strlen(ext2_suffix);
3188 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3190 if (!ext2_suffix_found)
3195 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3199 add_dynamic_file_list_entry(dynamic_file_list,
3200 num_dynamic_file_list_entries,
3203 num_suffix_list_entries,
3205 add_property_mapping(property_mapping,
3206 num_property_mapping_entries,
3207 base_index, ext1_index, ext2_index, -1,
3208 current_summarized_file_list_entry);
3212 start_pos += len_ext2_suffix;
3218 /* ---------- step 3: search for matching third suffix ---------- */
3220 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3222 char *ext3_suffix = ext3_suffixes[l];
3223 int len_ext3_suffix = strlen(ext3_suffix);
3225 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3227 if (!ext3_suffix_found)
3232 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3236 add_dynamic_file_list_entry(dynamic_file_list,
3237 num_dynamic_file_list_entries,
3240 num_suffix_list_entries,
3242 add_property_mapping(property_mapping,
3243 num_property_mapping_entries,
3244 base_index, ext1_index, ext2_index, ext3_index,
3245 current_summarized_file_list_entry);
3251 END_HASH_ITERATION(extra_file_hash, itr)
3253 if (artwork_info->num_dynamic_file_list_entries > 0)
3255 artwork_info->dynamic_artwork_list =
3256 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3257 artwork_info->sizeof_artwork_list_entry);
3260 if (options.verbose && IS_PARENT_PROCESS())
3262 SetupFileList *setup_file_list, *list;
3263 boolean dynamic_tokens_found = FALSE;
3264 boolean unknown_tokens_found = FALSE;
3265 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3267 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3268 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3270 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3272 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3273 dynamic_tokens_found = TRUE;
3275 unknown_tokens_found = TRUE;
3277 END_HASH_ITERATION(extra_file_hash, itr)
3279 if (options.debug && dynamic_tokens_found)
3281 Error(ERR_INFO_LINE, "-");
3282 Error(ERR_INFO, "dynamic token(s) found in config file:");
3283 Error(ERR_INFO, "- config file: '%s'", filename);
3285 for (list = setup_file_list; list != NULL; list = list->next)
3287 char *value = getHashEntry(extra_file_hash, list->token);
3289 if (value != NULL && strEqual(value, known_token_value))
3290 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3293 Error(ERR_INFO_LINE, "-");
3296 if (unknown_tokens_found)
3298 Error(ERR_INFO_LINE, "-");
3299 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3300 Error(ERR_INFO, "- config file: '%s'", filename);
3302 for (list = setup_file_list; list != NULL; list = list->next)
3304 char *value = getHashEntry(extra_file_hash, list->token);
3306 if (value != NULL && !strEqual(value, known_token_value))
3307 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3310 Error(ERR_INFO_LINE, "-");
3313 if (undefined_values_found)
3315 Error(ERR_INFO_LINE, "-");
3316 Error(ERR_INFO, "warning: undefined values found in config file:");
3317 Error(ERR_INFO, "- config file: '%s'", filename);
3319 for (list = setup_file_list; list != NULL; list = list->next)
3321 char *value = getHashEntry(empty_file_hash, list->token);
3324 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3327 Error(ERR_INFO_LINE, "-");
3330 freeSetupFileList(setup_file_list);
3333 freeSetupFileHash(extra_file_hash);
3334 freeSetupFileHash(empty_file_hash);
3337 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3339 struct FileInfo *file_list = artwork_info->file_list;
3340 int num_file_list_entries = artwork_info->num_file_list_entries;
3341 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3342 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3345 DrawInitText("Loading artwork config", 120, FC_GREEN);
3346 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3348 /* always start with reliable default values */
3349 for (i = 0; i < num_file_list_entries; i++)
3351 setString(&file_list[i].filename, file_list[i].default_filename);
3353 for (j = 0; j < num_suffix_list_entries; j++)
3354 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3356 file_list[i].redefined = FALSE;
3357 file_list[i].fallback_to_default = FALSE;
3360 /* free previous dynamic artwork file array */
3361 if (artwork_info->dynamic_file_list != NULL)
3363 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3365 free(artwork_info->dynamic_file_list[i].token);
3366 free(artwork_info->dynamic_file_list[i].filename);
3367 free(artwork_info->dynamic_file_list[i].parameter);
3370 free(artwork_info->dynamic_file_list);
3371 artwork_info->dynamic_file_list = NULL;
3373 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3374 &artwork_info->num_dynamic_file_list_entries);
3377 /* free previous property mapping */
3378 if (artwork_info->property_mapping != NULL)
3380 free(artwork_info->property_mapping);
3382 artwork_info->property_mapping = NULL;
3383 artwork_info->num_property_mapping_entries = 0;
3386 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3388 /* first look for special artwork configured in level series config */
3389 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3391 if (fileExists(filename_base))
3392 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3395 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3397 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3398 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3401 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3402 struct ListNodeInfo **listnode)
3406 char *filename = (*listnode)->source_filename;
3408 if (--(*listnode)->num_references <= 0)
3409 deleteNodeFromList(&artwork_info->content_list, filename,
3410 artwork_info->free_artwork);
3416 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3417 struct ListNodeInfo **listnode,
3418 struct FileInfo *file_list_entry)
3428 char *basename = file_list_entry->filename;
3429 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3431 if (filename == NULL)
3433 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3435 basename = file_list_entry->default_filename;
3437 /* fail for cloned default artwork that has no default filename defined */
3438 if (file_list_entry->default_is_cloned &&
3439 strEqual(basename, UNDEFINED_FILENAME))
3441 int error_mode = ERR_WARN;
3443 /* we can get away without sounds and music, but not without graphics */
3444 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3445 error_mode = ERR_EXIT;
3447 Error(error_mode, "token '%s' was cloned and has no default filename",
3448 file_list_entry->token);
3453 /* dynamic artwork has no default filename / skip empty default artwork */
3454 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3457 file_list_entry->fallback_to_default = TRUE;
3459 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3461 filename = getCustomArtworkFilename(basename, artwork_info->type);
3463 if (filename == NULL)
3465 int error_mode = ERR_WARN;
3467 /* we can get away without sounds and music, but not without graphics */
3468 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3469 error_mode = ERR_EXIT;
3471 Error(error_mode, "cannot find default artwork file '%s'", basename);
3477 /* check if the old and the new artwork file are the same */
3478 if (*listnode && strEqual((*listnode)->source_filename, filename))
3480 /* The old and new artwork are the same (have the same filename and path).
3481 This usually means that this artwork does not exist in this artwork set
3482 and a fallback to the existing artwork is done. */
3487 /* delete existing artwork file entry */
3488 deleteArtworkListEntry(artwork_info, listnode);
3490 /* check if the new artwork file already exists in the list of artwork */
3491 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3493 *listnode = (struct ListNodeInfo *)node->content;
3494 (*listnode)->num_references++;
3499 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3500 DrawInitText(basename, 150, FC_YELLOW);
3502 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3504 /* add new artwork file entry to the list of artwork files */
3505 (*listnode)->num_references = 1;
3506 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3511 int error_mode = ERR_WARN;
3513 /* we can get away without sounds and music, but not without graphics */
3514 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3515 error_mode = ERR_EXIT;
3517 Error(error_mode, "cannot load artwork file '%s'", basename);
3523 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3524 struct ListNodeInfo **listnode,
3525 struct FileInfo *file_list_entry)
3527 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3529 deleteArtworkListEntry(artwork_info, listnode);
3534 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3537 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3539 struct FileInfo *file_list = artwork_info->file_list;
3540 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3541 int num_file_list_entries = artwork_info->num_file_list_entries;
3542 int num_dynamic_file_list_entries =
3543 artwork_info->num_dynamic_file_list_entries;
3546 print_timestamp_init("ReloadCustomArtworkList");
3548 for (i = 0; i < num_file_list_entries; i++)
3549 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3552 for (i = 0; i < num_dynamic_file_list_entries; i++)
3553 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3554 &dynamic_file_list[i]);
3556 print_timestamp_done("ReloadCustomArtworkList");
3559 dumpList(artwork_info->content_list);
3563 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3564 struct ListNodeInfo ***list,
3565 int *num_list_entries)
3572 for (i = 0; i < *num_list_entries; i++)
3573 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3577 *num_list_entries = 0;
3580 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3582 if (artwork_info == NULL)
3585 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3586 &artwork_info->num_file_list_entries);
3588 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3589 &artwork_info->num_dynamic_file_list_entries);
3593 /* ------------------------------------------------------------------------- */
3594 /* functions only needed for non-Unix (non-command-line) systems */
3595 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3596 /* (now also added for Windows, to create files in user data directory) */
3597 /* ------------------------------------------------------------------------- */
3599 char *getLogFilename(char *basename)
3601 return getPath2(getUserGameDataDir(), basename);
3608 InitUserDataDirectory();
3610 for (i = 0; i < NUM_LOGS; i++)
3612 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3615 program.log_file[i] = program.log_file_default[i]; // reset to default
3617 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3618 program.log_filename[i], strerror(errno));
3621 /* output should be unbuffered so it is not truncated in a crash */
3622 setbuf(program.log_file[i], NULL);
3626 void CloseLogFiles()
3630 for (i = 0; i < NUM_LOGS; i++)
3631 if (program.log_file[i] != program.log_file_default[i])
3632 fclose(program.log_file[i]);
3635 void DumpLogFile(int nr)
3637 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3639 if (log_file == NULL)
3642 while (!feof(log_file))
3643 fputc(fgetc(log_file), stdout);
3648 void NotifyUserAboutErrorFile()
3650 #if defined(PLATFORM_WIN32)
3651 char *title_text = getStringCat2(program.program_title, " Error Message");
3652 char *error_text = getStringCat2("The program was aborted due to an error; "
3653 "for details, see the following error file:"
3655 program.log_filename[LOG_ERR_ID]);
3657 MessageBox(NULL, error_text, title_text, MB_OK);
3662 /* ------------------------------------------------------------------------- */
3663 /* the following is only for debugging purpose and normally not used */
3664 /* ------------------------------------------------------------------------- */
3668 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3669 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3671 #define DEBUG_NUM_TIMESTAMPS 10
3672 #define DEBUG_TIME_IN_MICROSECONDS 0
3674 #if DEBUG_TIME_IN_MICROSECONDS
3675 static double Counter_Microseconds()
3677 static struct timeval base_time = { 0, 0 };
3678 struct timeval current_time;
3681 gettimeofday(¤t_time, NULL);
3683 /* reset base time in case of wrap-around */
3684 if (current_time.tv_sec < base_time.tv_sec)
3685 base_time = current_time;
3688 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3689 ((double)(current_time.tv_usec - base_time.tv_usec));
3691 return counter; /* return microseconds since last init */
3695 char *debug_print_timestamp_get_padding(int padding_size)
3697 static char *padding = NULL;
3698 int max_padding_size = 100;
3700 if (padding == NULL)
3702 padding = checked_calloc(max_padding_size + 1);
3703 memset(padding, ' ', max_padding_size);
3706 return &padding[MAX(0, max_padding_size - padding_size)];
3709 void debug_print_timestamp(int counter_nr, char *message)
3711 int indent_size = 8;
3712 int padding_size = 40;
3713 float timestamp_interval;
3716 Error(ERR_EXIT, "debugging: invalid negative counter");
3717 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3718 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3720 #if DEBUG_TIME_IN_MICROSECONDS
3721 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3724 counter[counter_nr][0] = Counter_Microseconds();
3726 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3729 counter[counter_nr][0] = Counter();
3732 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3733 counter[counter_nr][1] = counter[counter_nr][0];
3736 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3737 debug_print_timestamp_get_padding(counter_nr * indent_size),
3739 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3740 timestamp_interval / 1000,
3744 void debug_print_parent_only(char *format, ...)
3746 if (!IS_PARENT_PROCESS())
3753 va_start(ap, format);
3754 vprintf(format, ap);
3763 void print_timestamp_ext(char *message, char *mode)
3765 #if DEBUG_PRINT_INIT_TIMESTAMPS
3766 static char *debug_message = NULL;
3767 static char *last_message = NULL;
3768 static int counter_nr = 0;
3769 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3771 checked_free(debug_message);
3772 debug_message = getStringCat3(mode, " ", message);
3774 if (strEqual(mode, "INIT"))
3776 debug_print_timestamp(counter_nr, NULL);
3778 if (counter_nr + 1 < max_depth)
3779 debug_print_timestamp(counter_nr, debug_message);
3783 debug_print_timestamp(counter_nr, NULL);
3785 else if (strEqual(mode, "DONE"))
3789 if (counter_nr + 1 < max_depth ||
3790 (counter_nr == 0 && max_depth == 1))
3792 last_message = message;
3794 if (counter_nr == 0 && max_depth == 1)
3796 checked_free(debug_message);
3797 debug_message = getStringCat3("TIME", " ", message);
3800 debug_print_timestamp(counter_nr, debug_message);
3803 else if (!strEqual(mode, "TIME") ||
3804 !strEqual(message, last_message))
3806 if (counter_nr < max_depth)
3807 debug_print_timestamp(counter_nr, debug_message);
3812 void print_timestamp_init(char *message)
3814 print_timestamp_ext(message, "INIT");
3817 void print_timestamp_time(char *message)
3819 print_timestamp_ext(message, "TIME");
3822 void print_timestamp_done(char *message)
3824 print_timestamp_ext(message, "DONE");