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 *getBasePath(char *filename)
659 char *basepath = getStringCopy(filename);
660 char *last_separator = getLastPathSeparatorPtr(basepath);
662 if (last_separator != NULL)
663 *last_separator = '\0'; /* separator found: strip basename */
665 basepath = "."; /* no separator found: use current path */
670 static char *getProgramMainDataPath()
672 char *main_data_path = getStringCopy(program.command_basepath);
674 #if defined(PLATFORM_MACOSX)
675 static char *main_data_binary_subdir = NULL;
677 if (main_data_binary_subdir == NULL)
679 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
681 strlen(MAC_APP_BINARY_SUBDIR) + 1);
683 sprintf(main_data_binary_subdir, "%s.app/%s",
684 program.program_title, MAC_APP_BINARY_SUBDIR);
687 // cut relative path to Mac OS X application binary directory from path
688 if (strSuffix(main_data_path, main_data_binary_subdir))
689 main_data_path[strlen(main_data_path) -
690 strlen(main_data_binary_subdir)] = '\0';
692 // cut trailing path separator from path (but not if path is root directory)
693 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
694 main_data_path[strlen(main_data_path) - 1] = '\0';
697 return main_data_path;
701 /* ------------------------------------------------------------------------- */
702 /* various string functions */
703 /* ------------------------------------------------------------------------- */
705 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
707 if (s1 == NULL || s2 == NULL || sep == NULL)
710 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
713 sprintf(complete_string, "%s%s%s", s1, sep, s2);
715 return complete_string;
718 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
720 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
723 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
724 strlen(s2) + strlen(sep) +
727 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
729 return complete_string;
732 char *getStringCat2(char *s1, char *s2)
734 return getStringCat2WithSeparator(s1, s2, "");
737 char *getStringCat3(char *s1, char *s2, char *s3)
739 return getStringCat3WithSeparator(s1, s2, s3, "");
742 char *getPath2(char *path1, char *path2)
744 #if defined(PLATFORM_ANDROID)
745 // workaround for reading from assets directory -- skip "." subdirs in path
746 if (strEqual(path1, "."))
747 return getStringCopy(path2);
748 else if (strEqual(path2, "."))
749 return getStringCopy(path1);
752 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
755 char *getPath3(char *path1, char *path2, char *path3)
757 #if defined(PLATFORM_ANDROID)
758 // workaround for reading from assets directory -- skip "." subdirs in path
759 if (strEqual(path1, "."))
760 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
761 else if (strEqual(path2, "."))
762 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
763 else if (strEqual(path3, "."))
764 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
767 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
770 char *getImg2(char *path1, char *path2)
772 char *filename = getPath2(path1, path2);
774 if (!fileExists(filename) && strSuffix(path2, ".png"))
776 // backward compatibility: if PNG file not found, check for PCX file
777 char *path2pcx = getStringCopy(path2);
779 strcpy(&path2pcx[strlen(path2pcx) - 3], "pcx");
783 filename = getPath2(path1, path2pcx);
791 char *getImg3(char *path1, char *path2, char *path3)
793 char *filename = getPath3(path1, path2, path3);
795 if (!fileExists(filename) && strSuffix(path3, ".png"))
797 // backward compatibility: if PNG file not found, check for PCX file
798 char *path3pcx = getStringCopy(path3);
800 strcpy(&path3pcx[strlen(path3pcx) - 3], "pcx");
804 filename = getPath3(path1, path2, path3pcx);
812 char *getStringCopy(const char *s)
819 s_copy = checked_malloc(strlen(s) + 1);
825 char *getStringCopyN(const char *s, int n)
828 int s_len = MAX(0, n);
833 s_copy = checked_malloc(s_len + 1);
834 strncpy(s_copy, s, s_len);
835 s_copy[s_len] = '\0';
840 char *getStringCopyNStatic(const char *s, int n)
842 static char *s_copy = NULL;
844 checked_free(s_copy);
846 s_copy = getStringCopyN(s, n);
851 char *getStringToLower(const char *s)
853 char *s_copy = checked_malloc(strlen(s) + 1);
854 char *s_ptr = s_copy;
857 *s_ptr++ = tolower(*s++);
863 void setString(char **old_value, char *new_value)
865 checked_free(*old_value);
867 *old_value = getStringCopy(new_value);
870 boolean strEqual(char *s1, char *s2)
872 return (s1 == NULL && s2 == NULL ? TRUE :
873 s1 == NULL && s2 != NULL ? FALSE :
874 s1 != NULL && s2 == NULL ? FALSE :
875 strcmp(s1, s2) == 0);
878 boolean strEqualN(char *s1, char *s2, int n)
880 return (s1 == NULL && s2 == NULL ? TRUE :
881 s1 == NULL && s2 != NULL ? FALSE :
882 s1 != NULL && s2 == NULL ? FALSE :
883 strncmp(s1, s2, n) == 0);
886 boolean strPrefix(char *s, char *prefix)
888 return (s == NULL && prefix == NULL ? TRUE :
889 s == NULL && prefix != NULL ? FALSE :
890 s != NULL && prefix == NULL ? FALSE :
891 strncmp(s, prefix, strlen(prefix)) == 0);
894 boolean strSuffix(char *s, char *suffix)
896 return (s == NULL && suffix == NULL ? TRUE :
897 s == NULL && suffix != NULL ? FALSE :
898 s != NULL && suffix == NULL ? FALSE :
899 strlen(s) < strlen(suffix) ? FALSE :
900 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
903 boolean strPrefixLower(char *s, char *prefix)
905 char *s_lower = getStringToLower(s);
906 boolean match = strPrefix(s_lower, prefix);
913 boolean strSuffixLower(char *s, char *suffix)
915 char *s_lower = getStringToLower(s);
916 boolean match = strSuffix(s_lower, suffix);
924 /* ------------------------------------------------------------------------- */
925 /* command line option handling functions */
926 /* ------------------------------------------------------------------------- */
928 void GetOptions(char *argv[],
929 void (*print_usage_function)(void),
930 void (*print_version_function)(void))
932 char *ro_base_path = RO_BASE_PATH;
933 char *rw_base_path = RW_BASE_PATH;
934 char **options_left = &argv[1];
936 /* if the program is configured to start from current directory (default),
937 determine program package directory from program binary (some versions
938 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
939 set the current working directory to the program package directory) */
941 if (strEqual(ro_base_path, "."))
942 ro_base_path = getProgramMainDataPath();
943 if (strEqual(rw_base_path, "."))
944 rw_base_path = getProgramMainDataPath();
946 /* initialize global program options */
947 options.display_name = NULL;
948 options.server_host = NULL;
949 options.server_port = 0;
951 options.ro_base_directory = ro_base_path;
952 options.rw_base_directory = rw_base_path;
953 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
954 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
955 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
956 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
957 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
959 options.execute_command = NULL;
960 options.special_flags = NULL;
962 options.serveronly = FALSE;
963 options.network = FALSE;
964 options.verbose = FALSE;
965 options.debug = FALSE;
968 options.verbose = TRUE;
970 #if !defined(PLATFORM_UNIX)
971 if (*options_left == NULL) /* no options given -- enable verbose mode */
972 options.verbose = TRUE;
976 while (*options_left)
978 char option_str[MAX_OPTION_LEN];
979 char *option = options_left[0];
980 char *next_option = options_left[1];
981 char *option_arg = NULL;
982 int option_len = strlen(option);
984 if (option_len >= MAX_OPTION_LEN)
985 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
987 strcpy(option_str, option); /* copy argument into buffer */
990 if (strEqual(option, "--")) /* stop scanning arguments */
993 if (strPrefix(option, "--")) /* treat '--' like '-' */
996 option_arg = strchr(option, '=');
997 if (option_arg == NULL) /* no '=' in option */
998 option_arg = next_option;
1001 *option_arg++ = '\0'; /* cut argument from option */
1002 if (*option_arg == '\0') /* no argument after '=' */
1003 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
1006 option_len = strlen(option);
1008 if (strEqual(option, "-"))
1010 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
1012 else if (strncmp(option, "-help", option_len) == 0)
1014 print_usage_function();
1018 else if (strncmp(option, "-display", option_len) == 0)
1020 if (option_arg == NULL)
1021 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1023 options.display_name = option_arg;
1024 if (option_arg == next_option)
1027 else if (strncmp(option, "-basepath", option_len) == 0)
1029 if (option_arg == NULL)
1030 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1032 /* this should be extended to separate options for ro and rw data */
1033 options.ro_base_directory = ro_base_path = option_arg;
1034 options.rw_base_directory = rw_base_path = option_arg;
1035 if (option_arg == next_option)
1038 /* adjust paths for sub-directories in base directory accordingly */
1039 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
1040 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
1041 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
1042 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
1043 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
1045 else if (strncmp(option, "-levels", option_len) == 0)
1047 if (option_arg == NULL)
1048 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1050 options.level_directory = option_arg;
1051 if (option_arg == next_option)
1054 else if (strncmp(option, "-graphics", option_len) == 0)
1056 if (option_arg == NULL)
1057 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1059 options.graphics_directory = option_arg;
1060 if (option_arg == next_option)
1063 else if (strncmp(option, "-sounds", option_len) == 0)
1065 if (option_arg == NULL)
1066 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1068 options.sounds_directory = option_arg;
1069 if (option_arg == next_option)
1072 else if (strncmp(option, "-music", option_len) == 0)
1074 if (option_arg == NULL)
1075 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1077 options.music_directory = option_arg;
1078 if (option_arg == next_option)
1081 else if (strncmp(option, "-network", option_len) == 0)
1083 options.network = TRUE;
1085 else if (strncmp(option, "-serveronly", option_len) == 0)
1087 options.serveronly = TRUE;
1089 else if (strncmp(option, "-debug", option_len) == 0)
1091 options.debug = TRUE;
1093 else if (strncmp(option, "-verbose", option_len) == 0)
1095 options.verbose = TRUE;
1097 else if (strncmp(option, "-version", option_len) == 0 ||
1098 strncmp(option, "-V", option_len) == 0)
1100 print_version_function();
1104 else if (strPrefix(option, "-D"))
1106 options.special_flags = getStringCopy(&option[2]);
1108 else if (strncmp(option, "-execute", option_len) == 0)
1110 if (option_arg == NULL)
1111 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1113 options.execute_command = option_arg;
1114 if (option_arg == next_option)
1117 /* when doing batch processing, always enable verbose mode (warnings) */
1118 options.verbose = TRUE;
1120 else if (*option == '-')
1122 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1124 else if (options.server_host == NULL)
1126 options.server_host = *options_left;
1128 else if (options.server_port == 0)
1130 options.server_port = atoi(*options_left);
1131 if (options.server_port < 1024)
1132 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1135 Error(ERR_EXIT_HELP, "too many arguments");
1142 /* ------------------------------------------------------------------------- */
1143 /* error handling functions */
1144 /* ------------------------------------------------------------------------- */
1146 #define MAX_INTERNAL_ERROR_SIZE 1024
1148 /* used by SetError() and GetError() to store internal error messages */
1149 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1151 void SetError(char *format, ...)
1155 va_start(ap, format);
1156 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1162 return internal_error;
1165 void Error(int mode, char *format, ...)
1167 static boolean last_line_was_separator = FALSE;
1168 char *process_name = "";
1170 if (program.log_file[LOG_ERR_ID] == NULL)
1173 #if defined(PLATFORM_ANDROID)
1174 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1175 mode & ERR_INFO ? ANDROID_LOG_INFO :
1176 mode & ERR_WARN ? ANDROID_LOG_WARN :
1177 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1178 ANDROID_LOG_UNKNOWN);
1181 /* display warnings only when running in verbose mode */
1182 if (mode & ERR_WARN && !options.verbose)
1185 if (mode == ERR_INFO_LINE)
1187 if (!last_line_was_separator)
1188 printf_log_line(format, 79);
1190 last_line_was_separator = TRUE;
1195 last_line_was_separator = FALSE;
1197 if (mode & ERR_SOUND_SERVER)
1198 process_name = " sound server";
1199 else if (mode & ERR_NETWORK_SERVER)
1200 process_name = " network server";
1201 else if (mode & ERR_NETWORK_CLIENT)
1202 process_name = " network client **";
1206 #if !defined(PLATFORM_ANDROID)
1207 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1210 if (mode & ERR_WARN)
1211 printf_log_nonewline("warning: ");
1213 if (mode & ERR_EXIT)
1214 printf_log_nonewline("fatal error: ");
1218 va_start(ap, format);
1219 vprintf_log(format, ap);
1222 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1224 va_start(ap, format);
1225 program.exit_message_function(format, ap);
1230 if (mode & ERR_HELP)
1231 printf_log("%s: Try option '--help' for more information.",
1232 program.command_basename);
1234 if (mode & ERR_EXIT)
1235 printf_log("%s%s: aborting", program.command_basename, process_name);
1237 if (mode & ERR_EXIT)
1239 if (mode & ERR_FROM_SERVER)
1240 exit(1); /* child process: normal exit */
1242 program.exit_function(1); /* main process: clean up stuff */
1247 /* ------------------------------------------------------------------------- */
1248 /* checked memory allocation and freeing functions */
1249 /* ------------------------------------------------------------------------- */
1251 void *checked_malloc(unsigned int size)
1258 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1263 void *checked_calloc(unsigned int size)
1267 ptr = calloc(1, size);
1270 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1275 void *checked_realloc(void *ptr, unsigned int size)
1277 ptr = realloc(ptr, size);
1280 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1285 void checked_free(void *ptr)
1287 if (ptr != NULL) /* this check should be done by free() anyway */
1291 void clear_mem(void *ptr, unsigned int size)
1293 #if defined(PLATFORM_WIN32)
1294 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1295 char *cptr = (char *)ptr;
1300 memset(ptr, 0, size);
1305 /* ------------------------------------------------------------------------- */
1306 /* various helper functions */
1307 /* ------------------------------------------------------------------------- */
1309 inline void swap_numbers(int *i1, int *i2)
1317 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1329 /* the "put" variants of the following file access functions check for the file
1330 pointer being != NULL and return the number of bytes they have or would have
1331 written; this allows for chunk writing functions to first determine the size
1332 of the (not yet written) chunk, write the correct chunk size and finally
1333 write the chunk itself */
1335 int getFile8BitInteger(File *file)
1337 return getByteFromFile(file);
1340 int putFile8BitInteger(FILE *file, int value)
1348 int getFile16BitInteger(File *file, int byte_order)
1350 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1351 return ((getByteFromFile(file) << 8) |
1352 (getByteFromFile(file) << 0));
1353 else /* BYTE_ORDER_LITTLE_ENDIAN */
1354 return ((getByteFromFile(file) << 0) |
1355 (getByteFromFile(file) << 8));
1358 int putFile16BitInteger(FILE *file, int value, int byte_order)
1362 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1364 fputc((value >> 8) & 0xff, file);
1365 fputc((value >> 0) & 0xff, file);
1367 else /* BYTE_ORDER_LITTLE_ENDIAN */
1369 fputc((value >> 0) & 0xff, file);
1370 fputc((value >> 8) & 0xff, file);
1377 int getFile32BitInteger(File *file, int byte_order)
1379 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1380 return ((getByteFromFile(file) << 24) |
1381 (getByteFromFile(file) << 16) |
1382 (getByteFromFile(file) << 8) |
1383 (getByteFromFile(file) << 0));
1384 else /* BYTE_ORDER_LITTLE_ENDIAN */
1385 return ((getByteFromFile(file) << 0) |
1386 (getByteFromFile(file) << 8) |
1387 (getByteFromFile(file) << 16) |
1388 (getByteFromFile(file) << 24));
1391 int putFile32BitInteger(FILE *file, int value, int byte_order)
1395 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1397 fputc((value >> 24) & 0xff, file);
1398 fputc((value >> 16) & 0xff, file);
1399 fputc((value >> 8) & 0xff, file);
1400 fputc((value >> 0) & 0xff, file);
1402 else /* BYTE_ORDER_LITTLE_ENDIAN */
1404 fputc((value >> 0) & 0xff, file);
1405 fputc((value >> 8) & 0xff, file);
1406 fputc((value >> 16) & 0xff, file);
1407 fputc((value >> 24) & 0xff, file);
1414 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1417 const int chunk_name_length = 4;
1419 /* read chunk name */
1420 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1423 if (chunk_size != NULL)
1425 /* read chunk size */
1426 *chunk_size = getFile32BitInteger(file, byte_order);
1429 return (checkEndOfFile(file) ? FALSE : TRUE);
1432 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1437 /* write chunk name */
1439 fputs(chunk_name, file);
1441 num_bytes += strlen(chunk_name);
1443 if (chunk_size >= 0)
1445 /* write chunk size */
1447 putFile32BitInteger(file, chunk_size, byte_order);
1455 int getFileVersion(File *file)
1457 int version_major = getByteFromFile(file);
1458 int version_minor = getByteFromFile(file);
1459 int version_patch = getByteFromFile(file);
1460 int version_build = getByteFromFile(file);
1462 return VERSION_IDENT(version_major, version_minor, version_patch,
1466 int putFileVersion(FILE *file, int version)
1470 int version_major = VERSION_MAJOR(version);
1471 int version_minor = VERSION_MINOR(version);
1472 int version_patch = VERSION_PATCH(version);
1473 int version_build = VERSION_BUILD(version);
1475 fputc(version_major, file);
1476 fputc(version_minor, file);
1477 fputc(version_patch, file);
1478 fputc(version_build, file);
1484 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1488 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1489 buffer[i] = getByteFromFile(file);
1492 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1496 for(i = 0; i < bytes; i++)
1497 fputc(buffer[i], file);
1500 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1502 while (bytes-- && !checkEndOfFile(file))
1503 getByteFromFile(file);
1506 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1513 /* ------------------------------------------------------------------------- */
1514 /* functions to translate key identifiers between different format */
1515 /* ------------------------------------------------------------------------- */
1517 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1518 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1519 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1520 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1522 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1531 /* normal cursor keys */
1532 { KSYM_Left, "XK_Left", "cursor left" },
1533 { KSYM_Right, "XK_Right", "cursor right" },
1534 { KSYM_Up, "XK_Up", "cursor up" },
1535 { KSYM_Down, "XK_Down", "cursor down" },
1537 /* keypad cursor keys */
1539 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1540 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1541 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1542 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1545 /* other keypad keys */
1546 #ifdef KSYM_KP_Enter
1547 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1548 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1549 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1550 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1551 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1552 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1556 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1557 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1558 { KSYM_Control_L, "XK_Control_L", "left control" },
1559 { KSYM_Control_R, "XK_Control_R", "right control" },
1560 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1561 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1562 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1563 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1564 #if !defined(TARGET_SDL2)
1565 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1566 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1568 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1569 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1571 /* some special keys */
1572 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1573 { KSYM_Delete, "XK_Delete", "delete" },
1574 { KSYM_Insert, "XK_Insert", "insert" },
1575 { KSYM_Tab, "XK_Tab", "tab" },
1576 { KSYM_Home, "XK_Home", "home" },
1577 { KSYM_End, "XK_End", "end" },
1578 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1579 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1581 #if defined(TARGET_SDL2)
1582 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1583 { KSYM_Back, "XK_Back", "back" }, /* back key */
1586 /* ASCII 0x20 to 0x40 keys (except numbers) */
1587 { KSYM_space, "XK_space", "space" },
1588 { KSYM_exclam, "XK_exclam", "!" },
1589 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1590 { KSYM_numbersign, "XK_numbersign", "#" },
1591 { KSYM_dollar, "XK_dollar", "$" },
1592 { KSYM_percent, "XK_percent", "%" },
1593 { KSYM_ampersand, "XK_ampersand", "&" },
1594 { KSYM_apostrophe, "XK_apostrophe", "'" },
1595 { KSYM_parenleft, "XK_parenleft", "(" },
1596 { KSYM_parenright, "XK_parenright", ")" },
1597 { KSYM_asterisk, "XK_asterisk", "*" },
1598 { KSYM_plus, "XK_plus", "+" },
1599 { KSYM_comma, "XK_comma", "," },
1600 { KSYM_minus, "XK_minus", "-" },
1601 { KSYM_period, "XK_period", "." },
1602 { KSYM_slash, "XK_slash", "/" },
1603 { KSYM_colon, "XK_colon", ":" },
1604 { KSYM_semicolon, "XK_semicolon", ";" },
1605 { KSYM_less, "XK_less", "<" },
1606 { KSYM_equal, "XK_equal", "=" },
1607 { KSYM_greater, "XK_greater", ">" },
1608 { KSYM_question, "XK_question", "?" },
1609 { KSYM_at, "XK_at", "@" },
1611 /* more ASCII keys */
1612 { KSYM_bracketleft, "XK_bracketleft", "[" },
1613 { KSYM_backslash, "XK_backslash", "\\" },
1614 { KSYM_bracketright,"XK_bracketright", "]" },
1615 { KSYM_asciicircum, "XK_asciicircum", "^" },
1616 { KSYM_underscore, "XK_underscore", "_" },
1617 { KSYM_grave, "XK_grave", "grave" },
1618 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1619 { KSYM_braceleft, "XK_braceleft", "brace left" },
1620 { KSYM_bar, "XK_bar", "bar" },
1621 { KSYM_braceright, "XK_braceright", "brace right" },
1622 { KSYM_asciitilde, "XK_asciitilde", "~" },
1624 /* special (non-ASCII) keys */
1625 { KSYM_degree, "XK_degree", "degree" },
1626 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1627 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1628 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1629 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1630 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1631 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1632 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1634 #if defined(TARGET_SDL2)
1635 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1636 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1637 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1638 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1639 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1640 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1641 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1642 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1643 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1645 /* other keys (for reverse mapping only) */
1646 { KSYM_space, "XK_space", " " },
1649 #if defined(TARGET_SDL2)
1650 /* keypad keys are not in numerical order in SDL2 */
1651 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1652 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1653 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1654 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1655 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1656 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1657 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1658 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1659 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1660 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1663 /* end-of-array identifier */
1669 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1671 static char name_buffer[30];
1674 if (key >= KSYM_A && key <= KSYM_Z)
1675 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1676 else if (key >= KSYM_a && key <= KSYM_z)
1677 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1678 else if (key >= KSYM_0 && key <= KSYM_9)
1679 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1680 #if !defined(TARGET_SDL2)
1681 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1682 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1684 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1685 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1686 else if (key == KSYM_UNDEFINED)
1687 strcpy(name_buffer, "(undefined)");
1694 if (key == translate_key[i].key)
1696 strcpy(name_buffer, translate_key[i].name);
1700 while (translate_key[++i].name);
1702 if (!translate_key[i].name)
1703 strcpy(name_buffer, "(unknown)");
1706 *name = name_buffer;
1708 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1710 static char name_buffer[30];
1713 if (key >= KSYM_A && key <= KSYM_Z)
1714 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1715 else if (key >= KSYM_a && key <= KSYM_z)
1716 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1717 else if (key >= KSYM_0 && key <= KSYM_9)
1718 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1719 #if !defined(TARGET_SDL2)
1720 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1721 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1723 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1724 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1725 else if (key == KSYM_UNDEFINED)
1726 strcpy(name_buffer, "[undefined]");
1733 if (key == translate_key[i].key)
1735 strcpy(name_buffer, translate_key[i].x11name);
1739 while (translate_key[++i].x11name);
1741 if (!translate_key[i].x11name)
1742 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1745 *x11name = name_buffer;
1747 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1749 Key key = KSYM_UNDEFINED;
1750 char *name_ptr = *name;
1752 if (strlen(*name) == 1)
1754 char c = name_ptr[0];
1756 if (c >= 'A' && c <= 'Z')
1757 key = KSYM_A + (Key)(c - 'A');
1758 else if (c >= 'a' && c <= 'z')
1759 key = KSYM_a + (Key)(c - 'a');
1760 else if (c >= '0' && c <= '9')
1761 key = KSYM_0 + (Key)(c - '0');
1764 if (key == KSYM_UNDEFINED)
1770 if (strEqual(translate_key[i].name, *name))
1772 key = translate_key[i].key;
1776 while (translate_key[++i].x11name);
1779 if (key == KSYM_UNDEFINED)
1780 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1784 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1786 Key key = KSYM_UNDEFINED;
1787 char *name_ptr = *x11name;
1789 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1791 char c = name_ptr[3];
1793 if (c >= 'A' && c <= 'Z')
1794 key = KSYM_A + (Key)(c - 'A');
1795 else if (c >= 'a' && c <= 'z')
1796 key = KSYM_a + (Key)(c - 'a');
1797 else if (c >= '0' && c <= '9')
1798 key = KSYM_0 + (Key)(c - '0');
1800 #if !defined(TARGET_SDL2)
1801 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1803 char c = name_ptr[6];
1805 if (c >= '0' && c <= '9')
1806 key = KSYM_KP_0 + (Key)(c - '0');
1809 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1811 char c1 = name_ptr[4];
1812 char c2 = name_ptr[5];
1815 if ((c1 >= '0' && c1 <= '9') &&
1816 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1817 d = atoi(&name_ptr[4]);
1819 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1820 key = KSYM_F1 + (Key)(d - 1);
1822 else if (strPrefix(name_ptr, "XK_"))
1828 if (strEqual(name_ptr, translate_key[i].x11name))
1830 key = translate_key[i].key;
1834 while (translate_key[++i].x11name);
1836 else if (strPrefix(name_ptr, "0x"))
1838 unsigned int value = 0;
1844 char c = *name_ptr++;
1847 if (c >= '0' && c <= '9')
1849 else if (c >= 'a' && c <= 'f')
1850 d = (int)(c - 'a' + 10);
1851 else if (c >= 'A' && c <= 'F')
1852 d = (int)(c - 'A' + 10);
1860 value = value * 16 + d;
1871 char *getKeyNameFromKey(Key key)
1875 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1879 char *getX11KeyNameFromKey(Key key)
1883 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1887 Key getKeyFromKeyName(char *name)
1891 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1895 Key getKeyFromX11KeyName(char *x11name)
1899 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1903 char getCharFromKey(Key key)
1909 } translate_key_char[] =
1911 /* special (non-ASCII) keys (ISO-8859-1) */
1912 { KSYM_degree, CHAR_BYTE_DEGREE },
1913 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1914 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1915 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1916 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1917 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1918 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1919 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1921 /* end-of-array identifier */
1925 char *keyname = getKeyNameFromKey(key);
1928 if (strlen(keyname) == 1)
1930 else if (strEqual(keyname, "space"))
1938 if (key == translate_key_char[i].key)
1940 c = translate_key_char[i].key_char;
1945 while (translate_key_char[++i].key_char);
1951 char getValidConfigValueChar(char c)
1953 if (c == '#' || /* used to mark comments */
1954 c == '\\') /* used to mark continued lines */
1961 /* ------------------------------------------------------------------------- */
1962 /* functions to translate string identifiers to integer or boolean value */
1963 /* ------------------------------------------------------------------------- */
1965 int get_integer_from_string(char *s)
1967 static char *number_text[][3] =
1969 { "0", "zero", "null", },
1970 { "1", "one", "first" },
1971 { "2", "two", "second" },
1972 { "3", "three", "third" },
1973 { "4", "four", "fourth" },
1974 { "5", "five", "fifth" },
1975 { "6", "six", "sixth" },
1976 { "7", "seven", "seventh" },
1977 { "8", "eight", "eighth" },
1978 { "9", "nine", "ninth" },
1979 { "10", "ten", "tenth" },
1980 { "11", "eleven", "eleventh" },
1981 { "12", "twelve", "twelfth" },
1983 { NULL, NULL, NULL },
1987 char *s_lower = getStringToLower(s);
1990 for (i = 0; number_text[i][0] != NULL; i++)
1991 for (j = 0; j < 3; j++)
1992 if (strEqual(s_lower, number_text[i][j]))
1997 if (strEqual(s_lower, "false") ||
1998 strEqual(s_lower, "no") ||
1999 strEqual(s_lower, "off"))
2001 else if (strEqual(s_lower, "true") ||
2002 strEqual(s_lower, "yes") ||
2003 strEqual(s_lower, "on"))
2014 boolean get_boolean_from_string(char *s)
2016 char *s_lower = getStringToLower(s);
2017 boolean result = FALSE;
2019 if (strEqual(s_lower, "true") ||
2020 strEqual(s_lower, "yes") ||
2021 strEqual(s_lower, "on") ||
2022 get_integer_from_string(s) == 1)
2030 int get_switch3_from_string(char *s)
2032 char *s_lower = getStringToLower(s);
2035 if (strEqual(s_lower, "true") ||
2036 strEqual(s_lower, "yes") ||
2037 strEqual(s_lower, "on") ||
2038 get_integer_from_string(s) == 1)
2040 else if (strEqual(s_lower, "auto"))
2049 /* ------------------------------------------------------------------------- */
2050 /* functions for generic lists */
2051 /* ------------------------------------------------------------------------- */
2053 ListNode *newListNode()
2055 return checked_calloc(sizeof(ListNode));
2058 void addNodeToList(ListNode **node_first, char *key, void *content)
2060 ListNode *node_new = newListNode();
2062 node_new->key = getStringCopy(key);
2063 node_new->content = content;
2064 node_new->next = *node_first;
2067 (*node_first)->prev = node_new;
2069 *node_first = node_new;
2072 void deleteNodeFromList(ListNode **node_first, char *key,
2073 void (*destructor_function)(void *))
2075 if (node_first == NULL || *node_first == NULL)
2078 if (strEqual((*node_first)->key, key))
2080 checked_free((*node_first)->key);
2082 if (destructor_function)
2083 destructor_function((*node_first)->content);
2085 if ((*node_first)->next)
2086 (*node_first)->next->prev = (*node_first)->prev;
2088 checked_free(*node_first);
2090 *node_first = (*node_first)->next;
2093 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2096 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2098 if (node_first == NULL)
2101 if (strEqual(node_first->key, key))
2104 return getNodeFromKey(node_first->next, key);
2107 int getNumNodes(ListNode *node_first)
2109 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2112 void dumpList(ListNode *node_first)
2114 ListNode *node = node_first;
2118 printf("['%s' (%d)]\n", node->key,
2119 ((struct ListNodeInfo *)node->content)->num_references);
2123 printf("[%d nodes]\n", getNumNodes(node_first));
2127 /* ------------------------------------------------------------------------- */
2128 /* functions for file handling */
2129 /* ------------------------------------------------------------------------- */
2131 File *openFile(char *filename, char *mode)
2133 File *file = checked_calloc(sizeof(File));
2135 file->file = fopen(filename, mode);
2137 if (file->file != NULL)
2139 file->filename = getStringCopy(filename);
2144 #if defined(PLATFORM_ANDROID)
2145 file->asset_file = SDL_RWFromFile(filename, mode);
2147 if (file->asset_file != NULL)
2149 file->file_is_asset = TRUE;
2150 file->filename = getStringCopy(filename);
2161 int closeFile(File *file)
2168 #if defined(PLATFORM_ANDROID)
2169 if (file->asset_file)
2170 result = SDL_RWclose(file->asset_file);
2174 result = fclose(file->file);
2176 checked_free(file->filename);
2182 int checkEndOfFile(File *file)
2184 #if defined(PLATFORM_ANDROID)
2185 if (file->file_is_asset)
2186 return file->end_of_file;
2189 return feof(file->file);
2192 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2194 #if defined(PLATFORM_ANDROID)
2195 if (file->file_is_asset)
2197 if (file->end_of_file)
2200 size_t num_items_read =
2201 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2203 if (num_items_read < num_items)
2204 file->end_of_file = TRUE;
2206 return num_items_read;
2210 return fread(buffer, item_size, num_items, file->file);
2213 int seekFile(File *file, long offset, int whence)
2215 #if defined(PLATFORM_ANDROID)
2216 if (file->file_is_asset)
2218 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2219 whence == SEEK_CUR ? RW_SEEK_CUR :
2220 whence == SEEK_END ? RW_SEEK_END : 0);
2222 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2226 return fseek(file->file, offset, whence);
2229 int getByteFromFile(File *file)
2231 #if defined(PLATFORM_ANDROID)
2232 if (file->file_is_asset)
2234 if (file->end_of_file)
2238 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2240 if (num_bytes_read < 1)
2241 file->end_of_file = TRUE;
2243 return (file->end_of_file ? EOF : (int)c);
2247 return fgetc(file->file);
2250 char *getStringFromFile(File *file, char *line, int size)
2252 #if defined(PLATFORM_ANDROID)
2253 if (file->file_is_asset)
2255 if (file->end_of_file)
2258 char *line_ptr = line;
2259 int num_bytes_read = 0;
2261 while (num_bytes_read < size - 1 &&
2262 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2263 *line_ptr++ != '\n')
2268 if (strlen(line) == 0)
2270 file->end_of_file = TRUE;
2279 return fgets(line, size, file->file);
2283 /* ------------------------------------------------------------------------- */
2284 /* functions for directory handling */
2285 /* ------------------------------------------------------------------------- */
2287 Directory *openDirectory(char *dir_name)
2289 Directory *dir = checked_calloc(sizeof(Directory));
2291 dir->dir = opendir(dir_name);
2293 if (dir->dir != NULL)
2295 dir->filename = getStringCopy(dir_name);
2300 #if defined(PLATFORM_ANDROID)
2301 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2303 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2305 checked_free(asset_toc_filename);
2307 if (dir->asset_toc_file != NULL)
2309 dir->directory_is_asset = TRUE;
2310 dir->filename = getStringCopy(dir_name);
2321 int closeDirectory(Directory *dir)
2328 #if defined(PLATFORM_ANDROID)
2329 if (dir->asset_toc_file)
2330 result = SDL_RWclose(dir->asset_toc_file);
2334 result = closedir(dir->dir);
2337 freeDirectoryEntry(dir->dir_entry);
2339 checked_free(dir->filename);
2345 DirectoryEntry *readDirectory(Directory *dir)
2348 freeDirectoryEntry(dir->dir_entry);
2350 dir->dir_entry = NULL;
2352 #if defined(PLATFORM_ANDROID)
2353 if (dir->directory_is_asset)
2355 char line[MAX_LINE_LEN];
2356 char *line_ptr = line;
2357 int num_bytes_read = 0;
2359 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2360 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2369 if (strlen(line) == 0)
2372 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2374 dir->dir_entry->is_directory = FALSE;
2375 if (line[strlen(line) - 1] == '/')
2377 dir->dir_entry->is_directory = TRUE;
2379 line[strlen(line) - 1] = '\0';
2382 dir->dir_entry->basename = getStringCopy(line);
2383 dir->dir_entry->filename = getPath2(dir->filename, line);
2385 return dir->dir_entry;
2389 struct dirent *dir_entry = readdir(dir->dir);
2391 if (dir_entry == NULL)
2394 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2396 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2397 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2399 struct stat file_status;
2401 dir->dir_entry->is_directory =
2402 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2403 S_ISDIR(file_status.st_mode));
2405 return dir->dir_entry;
2408 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2410 if (dir_entry == NULL)
2413 checked_free(dir_entry->basename);
2414 checked_free(dir_entry->filename);
2415 checked_free(dir_entry);
2419 /* ------------------------------------------------------------------------- */
2420 /* functions for checking files and filenames */
2421 /* ------------------------------------------------------------------------- */
2423 boolean directoryExists(char *dir_name)
2425 if (dir_name == NULL)
2428 struct stat file_status;
2429 boolean success = (stat(dir_name, &file_status) == 0 &&
2430 S_ISDIR(file_status.st_mode));
2432 #if defined(PLATFORM_ANDROID)
2435 // this might be an asset directory; check by trying to open toc file
2436 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2437 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2439 checked_free(asset_toc_filename);
2441 success = (file != NULL);
2451 boolean fileExists(char *filename)
2453 if (filename == NULL)
2456 boolean success = (access(filename, F_OK) == 0);
2458 #if defined(PLATFORM_ANDROID)
2461 // this might be an asset file; check by trying to open it
2462 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2464 success = (file != NULL);
2474 boolean fileHasPrefix(char *basename, char *prefix)
2476 static char *basename_lower = NULL;
2477 int basename_length, prefix_length;
2479 checked_free(basename_lower);
2481 if (basename == NULL || prefix == NULL)
2484 basename_lower = getStringToLower(basename);
2485 basename_length = strlen(basename_lower);
2486 prefix_length = strlen(prefix);
2488 if (basename_length > prefix_length + 1 &&
2489 basename_lower[prefix_length] == '.' &&
2490 strncmp(basename_lower, prefix, prefix_length) == 0)
2496 boolean fileHasSuffix(char *basename, char *suffix)
2498 static char *basename_lower = NULL;
2499 int basename_length, suffix_length;
2501 checked_free(basename_lower);
2503 if (basename == NULL || suffix == NULL)
2506 basename_lower = getStringToLower(basename);
2507 basename_length = strlen(basename_lower);
2508 suffix_length = strlen(suffix);
2510 if (basename_length > suffix_length + 1 &&
2511 basename_lower[basename_length - suffix_length - 1] == '.' &&
2512 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2518 static boolean FileCouldBeArtwork(char *filename)
2520 char *basename = getBaseNamePtr(filename);
2522 return (!strEqual(basename, ".") &&
2523 !strEqual(basename, "..") &&
2524 !fileHasSuffix(basename, "txt") &&
2525 !fileHasSuffix(basename, "conf") &&
2526 !directoryExists(filename));
2529 boolean FileIsGraphic(char *filename)
2531 return FileCouldBeArtwork(filename);
2534 boolean FileIsSound(char *filename)
2536 return FileCouldBeArtwork(filename);
2539 boolean FileIsMusic(char *filename)
2541 return FileCouldBeArtwork(filename);
2544 boolean FileIsArtworkType(char *filename, int type)
2546 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2547 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2548 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2554 /* ------------------------------------------------------------------------- */
2555 /* functions for loading artwork configuration information */
2556 /* ------------------------------------------------------------------------- */
2558 char *get_mapped_token(char *token)
2560 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2561 static char *map_token_prefix[][2] =
2563 { "char_procent", "char_percent" },
2568 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2570 int len_token_prefix = strlen(map_token_prefix[i][0]);
2572 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2573 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2579 /* This function checks if a string <s> of the format "string1, string2, ..."
2580 exactly contains a string <s_contained>. */
2582 static boolean string_has_parameter(char *s, char *s_contained)
2586 if (s == NULL || s_contained == NULL)
2589 if (strlen(s_contained) > strlen(s))
2592 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2594 char next_char = s[strlen(s_contained)];
2596 /* check if next character is delimiter or whitespace */
2597 return (next_char == ',' || next_char == '\0' ||
2598 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2601 /* check if string contains another parameter string after a comma */
2602 substring = strchr(s, ',');
2603 if (substring == NULL) /* string does not contain a comma */
2606 /* advance string pointer to next character after the comma */
2609 /* skip potential whitespaces after the comma */
2610 while (*substring == ' ' || *substring == '\t')
2613 return string_has_parameter(substring, s_contained);
2616 int get_parameter_value(char *value_raw, char *suffix, int type)
2618 char *value = getStringToLower(value_raw);
2619 int result = 0; /* probably a save default value */
2621 if (strEqual(suffix, ".direction"))
2623 result = (strEqual(value, "left") ? MV_LEFT :
2624 strEqual(value, "right") ? MV_RIGHT :
2625 strEqual(value, "up") ? MV_UP :
2626 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2628 else if (strEqual(suffix, ".align"))
2630 result = (strEqual(value, "left") ? ALIGN_LEFT :
2631 strEqual(value, "right") ? ALIGN_RIGHT :
2632 strEqual(value, "center") ? ALIGN_CENTER :
2633 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2635 else if (strEqual(suffix, ".valign"))
2637 result = (strEqual(value, "top") ? VALIGN_TOP :
2638 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2639 strEqual(value, "middle") ? VALIGN_MIDDLE :
2640 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2642 else if (strEqual(suffix, ".anim_mode"))
2644 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2645 string_has_parameter(value, "loop") ? ANIM_LOOP :
2646 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2647 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2648 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2649 string_has_parameter(value, "random") ? ANIM_RANDOM :
2650 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2651 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2652 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2653 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2654 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2655 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2658 if (string_has_parameter(value, "reverse"))
2659 result |= ANIM_REVERSE;
2661 if (string_has_parameter(value, "opaque_player"))
2662 result |= ANIM_OPAQUE_PLAYER;
2664 if (string_has_parameter(value, "static_panel"))
2665 result |= ANIM_STATIC_PANEL;
2667 else if (strEqual(suffix, ".class"))
2669 result = get_hash_from_key(value);
2671 else if (strEqual(suffix, ".style"))
2673 result = STYLE_DEFAULT;
2675 if (string_has_parameter(value, "accurate_borders"))
2676 result |= STYLE_ACCURATE_BORDERS;
2678 if (string_has_parameter(value, "inner_corners"))
2679 result |= STYLE_INNER_CORNERS;
2681 else if (strEqual(suffix, ".fade_mode"))
2683 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2684 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2685 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2686 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2689 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2691 result = gfx.get_font_from_token_function(value);
2693 else /* generic parameter of type integer or boolean */
2695 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2696 type == TYPE_INTEGER ? get_integer_from_string(value) :
2697 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2698 ARG_UNDEFINED_VALUE);
2706 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2708 static struct ScreenModeInfo screen_mode;
2709 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2710 char *screen_mode_string_copy;
2711 char *screen_mode_string_pos_w;
2712 char *screen_mode_string_pos_h;
2714 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2717 screen_mode_string_copy = getStringCopy(screen_mode_string);
2719 screen_mode_string_pos_w = screen_mode_string_copy;
2720 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2721 *screen_mode_string_pos_h++ = '\0';
2723 screen_mode.width = atoi(screen_mode_string_pos_w);
2724 screen_mode.height = atoi(screen_mode_string_pos_h);
2726 return &screen_mode;
2729 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2732 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2733 float aspect_ratio_new;
2738 *x = i * aspect_ratio + 0.000001;
2741 aspect_ratio_new = (float)*x / (float)*y;
2745 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2748 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2749 struct ListNodeInfo ***, int *);
2751 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2752 struct ConfigTypeInfo *suffix_list,
2753 char **ignore_tokens,
2754 int num_file_list_entries)
2756 struct FileInfo *file_list;
2757 int num_file_list_entries_found = 0;
2758 int num_suffix_list_entries = 0;
2762 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2764 for (i = 0; suffix_list[i].token != NULL; i++)
2765 num_suffix_list_entries++;
2767 /* always start with reliable default values */
2768 for (i = 0; i < num_file_list_entries; i++)
2770 file_list[i].token = NULL;
2772 file_list[i].default_filename = NULL;
2773 file_list[i].filename = NULL;
2775 if (num_suffix_list_entries > 0)
2777 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2779 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2780 file_list[i].parameter = checked_calloc(parameter_array_size);
2782 for (j = 0; j < num_suffix_list_entries; j++)
2784 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2785 setString(&file_list[i].parameter[j], suffix_list[j].value);
2788 file_list[i].redefined = FALSE;
2789 file_list[i].fallback_to_default = FALSE;
2790 file_list[i].default_is_cloned = FALSE;
2796 for (i = 0; config_list[i].token != NULL; i++)
2798 int len_config_token = strlen(config_list[i].token);
2799 boolean is_file_entry = TRUE;
2801 for (j = 0; suffix_list[j].token != NULL; j++)
2803 int len_suffix = strlen(suffix_list[j].token);
2805 if (len_suffix < len_config_token &&
2806 strEqual(&config_list[i].token[len_config_token - len_suffix],
2807 suffix_list[j].token))
2809 setString(&file_list[list_pos].default_parameter[j],
2810 config_list[i].value);
2812 is_file_entry = FALSE;
2818 /* the following tokens are no file definitions, but other config tokens */
2819 for (j = 0; ignore_tokens[j] != NULL; j++)
2820 if (strEqual(config_list[i].token, ignore_tokens[j]))
2821 is_file_entry = FALSE;
2828 if (list_pos >= num_file_list_entries)
2831 file_list[list_pos].token = config_list[i].token;
2832 file_list[list_pos].default_filename = config_list[i].value;
2835 if (strSuffix(config_list[i].token, ".clone_from"))
2836 file_list[list_pos].default_is_cloned = TRUE;
2839 num_file_list_entries_found = list_pos + 1;
2840 if (num_file_list_entries_found != num_file_list_entries)
2842 Error(ERR_INFO_LINE, "-");
2843 Error(ERR_INFO, "inconsistant config list information:");
2844 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2845 num_file_list_entries);
2846 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2847 num_file_list_entries_found);
2848 Error(ERR_EXIT, "please fix");
2854 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2856 int len_token = strlen(token);
2857 int len_suffix = strlen(suffix);
2859 if (start_pos < 0) /* compare suffix from end of string */
2860 start_pos += len_token;
2862 if (start_pos < 0 || start_pos + len_suffix > len_token)
2865 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2868 if (token[start_pos + len_suffix] == '\0')
2871 if (token[start_pos + len_suffix] == '.')
2877 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2879 static void read_token_parameters(SetupFileHash *setup_file_hash,
2880 struct ConfigTypeInfo *suffix_list,
2881 struct FileInfo *file_list_entry)
2883 /* check for config token that is the base token without any suffixes */
2884 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2885 char *known_token_value = KNOWN_TOKEN_VALUE;
2888 if (filename != NULL)
2890 setString(&file_list_entry->filename, filename);
2892 /* when file definition found, set all parameters to default values */
2893 for (i = 0; suffix_list[i].token != NULL; i++)
2894 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2896 file_list_entry->redefined = TRUE;
2898 /* mark config file token as well known from default config */
2899 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2902 /* check for config tokens that can be build by base token and suffixes */
2903 for (i = 0; suffix_list[i].token != NULL; i++)
2905 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2906 char *value = getHashEntry(setup_file_hash, token);
2910 setString(&file_list_entry->parameter[i], value);
2912 /* mark config file token as well known from default config */
2913 setHashEntry(setup_file_hash, token, known_token_value);
2920 static void add_dynamic_file_list_entry(struct FileInfo **list,
2921 int *num_list_entries,
2922 SetupFileHash *extra_file_hash,
2923 struct ConfigTypeInfo *suffix_list,
2924 int num_suffix_list_entries,
2927 struct FileInfo *new_list_entry;
2928 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2930 (*num_list_entries)++;
2931 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2932 new_list_entry = &(*list)[*num_list_entries - 1];
2934 new_list_entry->token = getStringCopy(token);
2935 new_list_entry->default_filename = NULL;
2936 new_list_entry->filename = NULL;
2937 new_list_entry->parameter = checked_calloc(parameter_array_size);
2939 new_list_entry->redefined = FALSE;
2940 new_list_entry->fallback_to_default = FALSE;
2941 new_list_entry->default_is_cloned = FALSE;
2943 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2946 static void add_property_mapping(struct PropertyMapping **list,
2947 int *num_list_entries,
2948 int base_index, int ext1_index,
2949 int ext2_index, int ext3_index,
2952 struct PropertyMapping *new_list_entry;
2954 (*num_list_entries)++;
2955 *list = checked_realloc(*list,
2956 *num_list_entries * sizeof(struct PropertyMapping));
2957 new_list_entry = &(*list)[*num_list_entries - 1];
2959 new_list_entry->base_index = base_index;
2960 new_list_entry->ext1_index = ext1_index;
2961 new_list_entry->ext2_index = ext2_index;
2962 new_list_entry->ext3_index = ext3_index;
2964 new_list_entry->artwork_index = artwork_index;
2967 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2970 struct FileInfo *file_list = artwork_info->file_list;
2971 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2972 char **base_prefixes = artwork_info->base_prefixes;
2973 char **ext1_suffixes = artwork_info->ext1_suffixes;
2974 char **ext2_suffixes = artwork_info->ext2_suffixes;
2975 char **ext3_suffixes = artwork_info->ext3_suffixes;
2976 char **ignore_tokens = artwork_info->ignore_tokens;
2977 int num_file_list_entries = artwork_info->num_file_list_entries;
2978 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2979 int num_base_prefixes = artwork_info->num_base_prefixes;
2980 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2981 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2982 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2983 int num_ignore_tokens = artwork_info->num_ignore_tokens;
2984 SetupFileHash *setup_file_hash, *valid_file_hash;
2985 SetupFileHash *extra_file_hash, *empty_file_hash;
2986 char *known_token_value = KNOWN_TOKEN_VALUE;
2989 if (filename == NULL)
2992 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2995 /* separate valid (defined) from empty (undefined) config token values */
2996 valid_file_hash = newSetupFileHash();
2997 empty_file_hash = newSetupFileHash();
2998 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3000 char *value = HASH_ITERATION_VALUE(itr);
3002 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3003 HASH_ITERATION_TOKEN(itr), value);
3005 END_HASH_ITERATION(setup_file_hash, itr)
3007 /* at this point, we do not need the setup file hash anymore -- free it */
3008 freeSetupFileHash(setup_file_hash);
3010 /* map deprecated to current tokens (using prefix match and replace) */
3011 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3013 char *token = HASH_ITERATION_TOKEN(itr);
3014 char *mapped_token = get_mapped_token(token);
3016 if (mapped_token != NULL)
3018 char *value = HASH_ITERATION_VALUE(itr);
3020 /* add mapped token */
3021 setHashEntry(valid_file_hash, mapped_token, value);
3023 /* ignore old token (by setting it to "known" keyword) */
3024 setHashEntry(valid_file_hash, token, known_token_value);
3029 END_HASH_ITERATION(valid_file_hash, itr)
3031 /* read parameters for all known config file tokens */
3032 for (i = 0; i < num_file_list_entries; i++)
3033 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
3035 /* set all tokens that can be ignored here to "known" keyword */
3036 for (i = 0; i < num_ignore_tokens; i++)
3037 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
3039 /* copy all unknown config file tokens to extra config hash */
3040 extra_file_hash = newSetupFileHash();
3041 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3043 char *value = HASH_ITERATION_VALUE(itr);
3045 if (!strEqual(value, known_token_value))
3046 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
3048 END_HASH_ITERATION(valid_file_hash, itr)
3050 /* at this point, we do not need the valid file hash anymore -- free it */
3051 freeSetupFileHash(valid_file_hash);
3053 /* now try to determine valid, dynamically defined config tokens */
3055 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3057 struct FileInfo **dynamic_file_list =
3058 &artwork_info->dynamic_file_list;
3059 int *num_dynamic_file_list_entries =
3060 &artwork_info->num_dynamic_file_list_entries;
3061 struct PropertyMapping **property_mapping =
3062 &artwork_info->property_mapping;
3063 int *num_property_mapping_entries =
3064 &artwork_info->num_property_mapping_entries;
3065 int current_summarized_file_list_entry =
3066 artwork_info->num_file_list_entries +
3067 artwork_info->num_dynamic_file_list_entries;
3068 char *token = HASH_ITERATION_TOKEN(itr);
3069 int len_token = strlen(token);
3071 boolean base_prefix_found = FALSE;
3072 boolean parameter_suffix_found = FALSE;
3074 /* skip all parameter definitions (handled by read_token_parameters()) */
3075 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3077 int len_suffix = strlen(suffix_list[i].token);
3079 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3080 parameter_suffix_found = TRUE;
3083 if (parameter_suffix_found)
3086 /* ---------- step 0: search for matching base prefix ---------- */
3089 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3091 char *base_prefix = base_prefixes[i];
3092 int len_base_prefix = strlen(base_prefix);
3093 boolean ext1_suffix_found = FALSE;
3094 boolean ext2_suffix_found = FALSE;
3095 boolean ext3_suffix_found = FALSE;
3096 boolean exact_match = FALSE;
3097 int base_index = -1;
3098 int ext1_index = -1;
3099 int ext2_index = -1;
3100 int ext3_index = -1;
3102 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3104 if (!base_prefix_found)
3109 if (start_pos + len_base_prefix == len_token) /* exact match */
3113 add_dynamic_file_list_entry(dynamic_file_list,
3114 num_dynamic_file_list_entries,
3117 num_suffix_list_entries,
3119 add_property_mapping(property_mapping,
3120 num_property_mapping_entries,
3121 base_index, -1, -1, -1,
3122 current_summarized_file_list_entry);
3126 /* ---------- step 1: search for matching first suffix ---------- */
3128 start_pos += len_base_prefix;
3129 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3131 char *ext1_suffix = ext1_suffixes[j];
3132 int len_ext1_suffix = strlen(ext1_suffix);
3134 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3136 if (!ext1_suffix_found)
3141 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3145 add_dynamic_file_list_entry(dynamic_file_list,
3146 num_dynamic_file_list_entries,
3149 num_suffix_list_entries,
3151 add_property_mapping(property_mapping,
3152 num_property_mapping_entries,
3153 base_index, ext1_index, -1, -1,
3154 current_summarized_file_list_entry);
3158 start_pos += len_ext1_suffix;
3164 /* ---------- step 2: search for matching second suffix ---------- */
3166 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3168 char *ext2_suffix = ext2_suffixes[k];
3169 int len_ext2_suffix = strlen(ext2_suffix);
3171 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3173 if (!ext2_suffix_found)
3178 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3182 add_dynamic_file_list_entry(dynamic_file_list,
3183 num_dynamic_file_list_entries,
3186 num_suffix_list_entries,
3188 add_property_mapping(property_mapping,
3189 num_property_mapping_entries,
3190 base_index, ext1_index, ext2_index, -1,
3191 current_summarized_file_list_entry);
3195 start_pos += len_ext2_suffix;
3201 /* ---------- step 3: search for matching third suffix ---------- */
3203 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3205 char *ext3_suffix = ext3_suffixes[l];
3206 int len_ext3_suffix = strlen(ext3_suffix);
3208 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3210 if (!ext3_suffix_found)
3215 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3219 add_dynamic_file_list_entry(dynamic_file_list,
3220 num_dynamic_file_list_entries,
3223 num_suffix_list_entries,
3225 add_property_mapping(property_mapping,
3226 num_property_mapping_entries,
3227 base_index, ext1_index, ext2_index, ext3_index,
3228 current_summarized_file_list_entry);
3234 END_HASH_ITERATION(extra_file_hash, itr)
3236 if (artwork_info->num_dynamic_file_list_entries > 0)
3238 artwork_info->dynamic_artwork_list =
3239 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3240 artwork_info->sizeof_artwork_list_entry);
3243 if (options.verbose && IS_PARENT_PROCESS())
3245 SetupFileList *setup_file_list, *list;
3246 boolean dynamic_tokens_found = FALSE;
3247 boolean unknown_tokens_found = FALSE;
3248 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3250 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3251 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3253 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3255 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3256 dynamic_tokens_found = TRUE;
3258 unknown_tokens_found = TRUE;
3260 END_HASH_ITERATION(extra_file_hash, itr)
3262 if (options.debug && dynamic_tokens_found)
3264 Error(ERR_INFO_LINE, "-");
3265 Error(ERR_INFO, "dynamic token(s) found in config file:");
3266 Error(ERR_INFO, "- config file: '%s'", filename);
3268 for (list = setup_file_list; list != NULL; list = list->next)
3270 char *value = getHashEntry(extra_file_hash, list->token);
3272 if (value != NULL && strEqual(value, known_token_value))
3273 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3276 Error(ERR_INFO_LINE, "-");
3279 if (unknown_tokens_found)
3281 Error(ERR_INFO_LINE, "-");
3282 Error(ERR_INFO, "warning: unknown 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 (undefined_values_found)
3298 Error(ERR_INFO_LINE, "-");
3299 Error(ERR_INFO, "warning: undefined values 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(empty_file_hash, list->token);
3307 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3310 Error(ERR_INFO_LINE, "-");
3313 freeSetupFileList(setup_file_list);
3316 freeSetupFileHash(extra_file_hash);
3317 freeSetupFileHash(empty_file_hash);
3320 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3322 struct FileInfo *file_list = artwork_info->file_list;
3323 int num_file_list_entries = artwork_info->num_file_list_entries;
3324 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3325 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3328 DrawInitText("Loading artwork config", 120, FC_GREEN);
3329 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3331 /* always start with reliable default values */
3332 for (i = 0; i < num_file_list_entries; i++)
3334 setString(&file_list[i].filename, file_list[i].default_filename);
3336 for (j = 0; j < num_suffix_list_entries; j++)
3337 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3339 file_list[i].redefined = FALSE;
3340 file_list[i].fallback_to_default = FALSE;
3343 /* free previous dynamic artwork file array */
3344 if (artwork_info->dynamic_file_list != NULL)
3346 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3348 free(artwork_info->dynamic_file_list[i].token);
3349 free(artwork_info->dynamic_file_list[i].filename);
3350 free(artwork_info->dynamic_file_list[i].parameter);
3353 free(artwork_info->dynamic_file_list);
3354 artwork_info->dynamic_file_list = NULL;
3356 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3357 &artwork_info->num_dynamic_file_list_entries);
3360 /* free previous property mapping */
3361 if (artwork_info->property_mapping != NULL)
3363 free(artwork_info->property_mapping);
3365 artwork_info->property_mapping = NULL;
3366 artwork_info->num_property_mapping_entries = 0;
3369 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3371 /* first look for special artwork configured in level series config */
3372 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3374 if (fileExists(filename_base))
3375 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3378 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3380 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3381 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3384 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3385 struct ListNodeInfo **listnode)
3389 char *filename = (*listnode)->source_filename;
3391 if (--(*listnode)->num_references <= 0)
3392 deleteNodeFromList(&artwork_info->content_list, filename,
3393 artwork_info->free_artwork);
3399 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3400 struct ListNodeInfo **listnode,
3401 struct FileInfo *file_list_entry)
3411 char *basename = file_list_entry->filename;
3412 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3414 if (filename == NULL)
3416 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3418 basename = file_list_entry->default_filename;
3420 /* fail for cloned default artwork that has no default filename defined */
3421 if (file_list_entry->default_is_cloned &&
3422 strEqual(basename, UNDEFINED_FILENAME))
3424 int error_mode = ERR_WARN;
3426 /* we can get away without sounds and music, but not without graphics */
3427 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3428 error_mode = ERR_EXIT;
3430 Error(error_mode, "token '%s' was cloned and has no default filename",
3431 file_list_entry->token);
3436 /* dynamic artwork has no default filename / skip empty default artwork */
3437 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3440 file_list_entry->fallback_to_default = TRUE;
3442 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3444 filename = getCustomArtworkFilename(basename, artwork_info->type);
3446 if (filename == NULL)
3448 int error_mode = ERR_WARN;
3450 /* we can get away without sounds and music, but not without graphics */
3451 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3452 error_mode = ERR_EXIT;
3454 Error(error_mode, "cannot find default artwork file '%s'", basename);
3460 /* check if the old and the new artwork file are the same */
3461 if (*listnode && strEqual((*listnode)->source_filename, filename))
3463 /* The old and new artwork are the same (have the same filename and path).
3464 This usually means that this artwork does not exist in this artwork set
3465 and a fallback to the existing artwork is done. */
3470 /* delete existing artwork file entry */
3471 deleteArtworkListEntry(artwork_info, listnode);
3473 /* check if the new artwork file already exists in the list of artwork */
3474 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3476 *listnode = (struct ListNodeInfo *)node->content;
3477 (*listnode)->num_references++;
3482 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3483 DrawInitText(basename, 150, FC_YELLOW);
3485 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3487 /* add new artwork file entry to the list of artwork files */
3488 (*listnode)->num_references = 1;
3489 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3494 int error_mode = ERR_WARN;
3496 /* we can get away without sounds and music, but not without graphics */
3497 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3498 error_mode = ERR_EXIT;
3500 Error(error_mode, "cannot load artwork file '%s'", basename);
3506 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3507 struct ListNodeInfo **listnode,
3508 struct FileInfo *file_list_entry)
3510 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3512 deleteArtworkListEntry(artwork_info, listnode);
3517 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3520 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3522 struct FileInfo *file_list = artwork_info->file_list;
3523 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3524 int num_file_list_entries = artwork_info->num_file_list_entries;
3525 int num_dynamic_file_list_entries =
3526 artwork_info->num_dynamic_file_list_entries;
3529 print_timestamp_init("ReloadCustomArtworkList");
3531 for (i = 0; i < num_file_list_entries; i++)
3532 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3535 for (i = 0; i < num_dynamic_file_list_entries; i++)
3536 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3537 &dynamic_file_list[i]);
3539 print_timestamp_done("ReloadCustomArtworkList");
3542 dumpList(artwork_info->content_list);
3546 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3547 struct ListNodeInfo ***list,
3548 int *num_list_entries)
3555 for (i = 0; i < *num_list_entries; i++)
3556 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3560 *num_list_entries = 0;
3563 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3565 if (artwork_info == NULL)
3568 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3569 &artwork_info->num_file_list_entries);
3571 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3572 &artwork_info->num_dynamic_file_list_entries);
3576 /* ------------------------------------------------------------------------- */
3577 /* functions only needed for non-Unix (non-command-line) systems */
3578 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3579 /* (now also added for Windows, to create files in user data directory) */
3580 /* ------------------------------------------------------------------------- */
3582 char *getLogFilename(char *basename)
3584 return getPath2(getUserGameDataDir(), basename);
3591 InitUserDataDirectory();
3593 for (i = 0; i < NUM_LOGS; i++)
3595 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3598 program.log_file[i] = program.log_file_default[i]; // reset to default
3600 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3601 program.log_filename[i], strerror(errno));
3604 /* output should be unbuffered so it is not truncated in a crash */
3605 setbuf(program.log_file[i], NULL);
3609 void CloseLogFiles()
3613 for (i = 0; i < NUM_LOGS; i++)
3614 if (program.log_file[i] != program.log_file_default[i])
3615 fclose(program.log_file[i]);
3618 void DumpLogFile(int nr)
3620 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3622 if (log_file == NULL)
3625 while (!feof(log_file))
3626 fputc(fgetc(log_file), stdout);
3631 void NotifyUserAboutErrorFile()
3633 #if defined(PLATFORM_WIN32)
3634 char *title_text = getStringCat2(program.program_title, " Error Message");
3635 char *error_text = getStringCat2("The program was aborted due to an error; "
3636 "for details, see the following error file:"
3638 program.log_filename[LOG_ERR_ID]);
3640 MessageBox(NULL, error_text, title_text, MB_OK);
3645 /* ------------------------------------------------------------------------- */
3646 /* the following is only for debugging purpose and normally not used */
3647 /* ------------------------------------------------------------------------- */
3651 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3652 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3654 #define DEBUG_NUM_TIMESTAMPS 10
3655 #define DEBUG_TIME_IN_MICROSECONDS 0
3657 #if DEBUG_TIME_IN_MICROSECONDS
3658 static double Counter_Microseconds()
3660 static struct timeval base_time = { 0, 0 };
3661 struct timeval current_time;
3664 gettimeofday(¤t_time, NULL);
3666 /* reset base time in case of wrap-around */
3667 if (current_time.tv_sec < base_time.tv_sec)
3668 base_time = current_time;
3671 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3672 ((double)(current_time.tv_usec - base_time.tv_usec));
3674 return counter; /* return microseconds since last init */
3678 char *debug_print_timestamp_get_padding(int padding_size)
3680 static char *padding = NULL;
3681 int max_padding_size = 100;
3683 if (padding == NULL)
3685 padding = checked_calloc(max_padding_size + 1);
3686 memset(padding, ' ', max_padding_size);
3689 return &padding[MAX(0, max_padding_size - padding_size)];
3692 void debug_print_timestamp(int counter_nr, char *message)
3694 int indent_size = 8;
3695 int padding_size = 40;
3696 float timestamp_interval;
3699 Error(ERR_EXIT, "debugging: invalid negative counter");
3700 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3701 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3703 #if DEBUG_TIME_IN_MICROSECONDS
3704 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3707 counter[counter_nr][0] = Counter_Microseconds();
3709 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3712 counter[counter_nr][0] = Counter();
3715 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3716 counter[counter_nr][1] = counter[counter_nr][0];
3719 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3720 debug_print_timestamp_get_padding(counter_nr * indent_size),
3722 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3723 timestamp_interval / 1000,
3727 void debug_print_parent_only(char *format, ...)
3729 if (!IS_PARENT_PROCESS())
3736 va_start(ap, format);
3737 vprintf(format, ap);
3746 void print_timestamp_ext(char *message, char *mode)
3748 #if DEBUG_PRINT_INIT_TIMESTAMPS
3749 static char *debug_message = NULL;
3750 static char *last_message = NULL;
3751 static int counter_nr = 0;
3752 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3754 checked_free(debug_message);
3755 debug_message = getStringCat3(mode, " ", message);
3757 if (strEqual(mode, "INIT"))
3759 debug_print_timestamp(counter_nr, NULL);
3761 if (counter_nr + 1 < max_depth)
3762 debug_print_timestamp(counter_nr, debug_message);
3766 debug_print_timestamp(counter_nr, NULL);
3768 else if (strEqual(mode, "DONE"))
3772 if (counter_nr + 1 < max_depth ||
3773 (counter_nr == 0 && max_depth == 1))
3775 last_message = message;
3777 if (counter_nr == 0 && max_depth == 1)
3779 checked_free(debug_message);
3780 debug_message = getStringCat3("TIME", " ", message);
3783 debug_print_timestamp(counter_nr, debug_message);
3786 else if (!strEqual(mode, "TIME") ||
3787 !strEqual(message, last_message))
3789 if (counter_nr < max_depth)
3790 debug_print_timestamp(counter_nr, debug_message);
3795 void print_timestamp_init(char *message)
3797 print_timestamp_ext(message, "INIT");
3800 void print_timestamp_time(char *message)
3802 print_timestamp_ext(message, "TIME");
3805 void print_timestamp_done(char *message)
3807 print_timestamp_ext(message, "DONE");