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 to 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 void WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
416 unsigned int actual_counter;
420 actual_counter = Counter();
422 if (actual_counter >= *counter_var &&
423 actual_counter < *counter_var + delay)
424 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
429 *counter_var = actual_counter;
433 /* ------------------------------------------------------------------------- */
434 /* random generator functions */
435 /* ------------------------------------------------------------------------- */
437 unsigned int init_random_number(int nr, int seed)
439 if (seed == NEW_RANDOMIZE)
441 /* default random seed */
442 seed = (int)time(NULL); // seconds since the epoch
444 #if !defined(PLATFORM_WIN32)
445 /* add some more randomness */
446 struct timeval current_time;
448 gettimeofday(¤t_time, NULL);
450 seed += (int)current_time.tv_usec; // microseconds since the epoch
453 /* add some more randomness */
454 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
456 /* add some more randomness */
457 seed += GetSimpleRandom(1000000);
460 srandom_linux_libc(nr, (unsigned int) seed);
462 return (unsigned int) seed;
465 unsigned int get_random_number(int nr, int max)
467 return (max > 0 ? random_linux_libc(nr) % max : 0);
471 /* ------------------------------------------------------------------------- */
472 /* system info functions */
473 /* ------------------------------------------------------------------------- */
475 #if !defined(PLATFORM_ANDROID)
476 static char *get_corrected_real_name(char *real_name)
478 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
479 char *from_ptr = real_name;
480 char *to_ptr = real_name_new;
482 /* copy the name string, but not more than MAX_USERNAME_LEN characters */
483 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
485 /* the name field read from "passwd" file may also contain additional
486 user information, separated by commas, which will be removed here */
487 if (*from_ptr == ',')
490 /* the user's real name may contain 'german sharp s' characters,
491 which have no equivalent in upper case letters (used by our fonts) */
492 if (*from_ptr == CHAR_BYTE_SHARP_S)
499 *to_ptr++ = *from_ptr++;
504 return real_name_new;
510 static char *login_name = NULL;
512 #if defined(PLATFORM_WIN32)
513 if (login_name == NULL)
515 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
516 login_name = checked_malloc(buffer_size);
518 if (GetUserName(login_name, &buffer_size) == 0)
519 strcpy(login_name, ANONYMOUS_NAME);
522 if (login_name == NULL)
526 if ((pwd = getpwuid(getuid())) == NULL)
527 login_name = ANONYMOUS_NAME;
529 login_name = getStringCopy(pwd->pw_name);
538 static char *real_name = NULL;
540 #if defined(PLATFORM_WIN32)
541 if (real_name == NULL)
543 static char buffer[MAX_USERNAME_LEN + 1];
544 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
546 if (GetUserName(buffer, &buffer_size) != 0)
547 real_name = get_corrected_real_name(buffer);
549 real_name = ANONYMOUS_NAME;
551 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
552 if (real_name == NULL)
556 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
557 real_name = get_corrected_real_name(pwd->pw_gecos);
559 real_name = ANONYMOUS_NAME;
562 real_name = ANONYMOUS_NAME;
568 time_t getFileTimestampEpochSeconds(char *filename)
570 struct stat file_status;
572 if (stat(filename, &file_status) != 0) /* cannot stat file */
575 return file_status.st_mtime;
579 /* ------------------------------------------------------------------------- */
580 /* path manipulation functions */
581 /* ------------------------------------------------------------------------- */
583 static char *getLastPathSeparatorPtr(char *filename)
585 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
587 if (last_separator == NULL) /* also try DOS/Windows variant */
588 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
590 return last_separator;
593 char *getBaseNamePtr(char *filename)
595 char *last_separator = getLastPathSeparatorPtr(filename);
597 if (last_separator != NULL)
598 return last_separator + 1; /* separator found: strip base path */
600 return filename; /* no separator found: filename has no path */
603 char *getBaseName(char *filename)
605 return getStringCopy(getBaseNamePtr(filename));
608 char *getBasePath(char *filename)
610 char *basepath = getStringCopy(filename);
611 char *last_separator = getLastPathSeparatorPtr(basepath);
613 if (last_separator != NULL)
614 *last_separator = '\0'; /* separator found: strip basename */
616 basepath = "."; /* no separator found: use current path */
621 static char *getProgramMainDataPath()
623 char *main_data_path = getStringCopy(program.command_basepath);
625 #if defined(PLATFORM_MACOSX)
626 static char *main_data_binary_subdir = NULL;
628 if (main_data_binary_subdir == NULL)
630 main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
632 strlen(MAC_APP_BINARY_SUBDIR) + 1);
634 sprintf(main_data_binary_subdir, "%s.app/%s",
635 program.program_title, MAC_APP_BINARY_SUBDIR);
638 // cut relative path to Mac OS X application binary directory from path
639 if (strSuffix(main_data_path, main_data_binary_subdir))
640 main_data_path[strlen(main_data_path) -
641 strlen(main_data_binary_subdir)] = '\0';
643 // cut trailing path separator from path (but not if path is root directory)
644 if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
645 main_data_path[strlen(main_data_path) - 1] = '\0';
648 return main_data_path;
652 /* ------------------------------------------------------------------------- */
653 /* various string functions */
654 /* ------------------------------------------------------------------------- */
656 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
658 if (s1 == NULL || s2 == NULL || sep == NULL)
661 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
664 sprintf(complete_string, "%s%s%s", s1, sep, s2);
666 return complete_string;
669 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
671 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
674 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
675 strlen(s2) + strlen(sep) +
678 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
680 return complete_string;
683 char *getStringCat2(char *s1, char *s2)
685 return getStringCat2WithSeparator(s1, s2, "");
688 char *getStringCat3(char *s1, char *s2, char *s3)
690 return getStringCat3WithSeparator(s1, s2, s3, "");
693 char *getPath2(char *path1, char *path2)
695 #if defined(PLATFORM_ANDROID)
696 // workaround for reading from assets directory -- skip "." subdirs in path
697 if (strEqual(path1, "."))
698 return getStringCopy(path2);
699 else if (strEqual(path2, "."))
700 return getStringCopy(path1);
703 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
706 char *getPath3(char *path1, char *path2, char *path3)
708 #if defined(PLATFORM_ANDROID)
709 // workaround for reading from assets directory -- skip "." subdirs in path
710 if (strEqual(path1, "."))
711 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
712 else if (strEqual(path2, "."))
713 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
714 else if (strEqual(path3, "."))
715 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
718 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
721 char *getImg2(char *path1, char *path2)
723 char *filename = getPath2(path1, path2);
725 if (!fileExists(filename) && strSuffix(path2, ".png"))
727 // backward compatibility: if PNG file not found, check for PCX file
728 char *path2pcx = getStringCopy(path2);
730 strcpy(&path2pcx[strlen(path2pcx) - 3], "pcx");
734 filename = getPath2(path1, path2pcx);
742 char *getImg3(char *path1, char *path2, char *path3)
744 char *filename = getPath3(path1, path2, path3);
746 if (!fileExists(filename) && strSuffix(path3, ".png"))
748 // backward compatibility: if PNG file not found, check for PCX file
749 char *path3pcx = getStringCopy(path3);
751 strcpy(&path3pcx[strlen(path3pcx) - 3], "pcx");
755 filename = getPath3(path1, path2, path3pcx);
763 char *getStringCopy(const char *s)
770 s_copy = checked_malloc(strlen(s) + 1);
776 char *getStringCopyN(const char *s, int n)
779 int s_len = MAX(0, n);
784 s_copy = checked_malloc(s_len + 1);
785 strncpy(s_copy, s, s_len);
786 s_copy[s_len] = '\0';
791 char *getStringCopyNStatic(const char *s, int n)
793 static char *s_copy = NULL;
795 checked_free(s_copy);
797 s_copy = getStringCopyN(s, n);
802 char *getStringToLower(const char *s)
804 char *s_copy = checked_malloc(strlen(s) + 1);
805 char *s_ptr = s_copy;
808 *s_ptr++ = tolower(*s++);
814 void setString(char **old_value, char *new_value)
816 checked_free(*old_value);
818 *old_value = getStringCopy(new_value);
821 boolean strEqual(char *s1, char *s2)
823 return (s1 == NULL && s2 == NULL ? TRUE :
824 s1 == NULL && s2 != NULL ? FALSE :
825 s1 != NULL && s2 == NULL ? FALSE :
826 strcmp(s1, s2) == 0);
829 boolean strEqualN(char *s1, char *s2, int n)
831 return (s1 == NULL && s2 == NULL ? TRUE :
832 s1 == NULL && s2 != NULL ? FALSE :
833 s1 != NULL && s2 == NULL ? FALSE :
834 strncmp(s1, s2, n) == 0);
837 boolean strPrefix(char *s, char *prefix)
839 return (s == NULL && prefix == NULL ? TRUE :
840 s == NULL && prefix != NULL ? FALSE :
841 s != NULL && prefix == NULL ? FALSE :
842 strncmp(s, prefix, strlen(prefix)) == 0);
845 boolean strSuffix(char *s, char *suffix)
847 return (s == NULL && suffix == NULL ? TRUE :
848 s == NULL && suffix != NULL ? FALSE :
849 s != NULL && suffix == NULL ? FALSE :
850 strlen(s) < strlen(suffix) ? FALSE :
851 strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
854 boolean strPrefixLower(char *s, char *prefix)
856 char *s_lower = getStringToLower(s);
857 boolean match = strPrefix(s_lower, prefix);
864 boolean strSuffixLower(char *s, char *suffix)
866 char *s_lower = getStringToLower(s);
867 boolean match = strSuffix(s_lower, suffix);
875 /* ------------------------------------------------------------------------- */
876 /* command line option handling functions */
877 /* ------------------------------------------------------------------------- */
879 void GetOptions(char *argv[],
880 void (*print_usage_function)(void),
881 void (*print_version_function)(void))
883 char *ro_base_path = RO_BASE_PATH;
884 char *rw_base_path = RW_BASE_PATH;
885 char **options_left = &argv[1];
887 /* if the program is configured to start from current directory (default),
888 determine program package directory from program binary (some versions
889 of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
890 set the current working directory to the program package directory) */
892 if (strEqual(ro_base_path, "."))
893 ro_base_path = getProgramMainDataPath();
894 if (strEqual(rw_base_path, "."))
895 rw_base_path = getProgramMainDataPath();
897 /* initialize global program options */
898 options.display_name = NULL;
899 options.server_host = NULL;
900 options.server_port = 0;
902 options.ro_base_directory = ro_base_path;
903 options.rw_base_directory = rw_base_path;
904 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
905 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
906 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
907 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
908 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
910 options.execute_command = NULL;
911 options.special_flags = NULL;
913 options.serveronly = FALSE;
914 options.network = FALSE;
915 options.verbose = FALSE;
916 options.debug = FALSE;
919 options.verbose = TRUE;
921 #if !defined(PLATFORM_UNIX)
922 if (*options_left == NULL) /* no options given -- enable verbose mode */
923 options.verbose = TRUE;
927 while (*options_left)
929 char option_str[MAX_OPTION_LEN];
930 char *option = options_left[0];
931 char *next_option = options_left[1];
932 char *option_arg = NULL;
933 int option_len = strlen(option);
935 if (option_len >= MAX_OPTION_LEN)
936 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
938 strcpy(option_str, option); /* copy argument into buffer */
941 if (strEqual(option, "--")) /* stop scanning arguments */
944 if (strPrefix(option, "--")) /* treat '--' like '-' */
947 option_arg = strchr(option, '=');
948 if (option_arg == NULL) /* no '=' in option */
949 option_arg = next_option;
952 *option_arg++ = '\0'; /* cut argument from option */
953 if (*option_arg == '\0') /* no argument after '=' */
954 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
957 option_len = strlen(option);
959 if (strEqual(option, "-"))
961 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
963 else if (strncmp(option, "-help", option_len) == 0)
965 print_usage_function();
969 else if (strncmp(option, "-display", option_len) == 0)
971 if (option_arg == NULL)
972 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
974 options.display_name = option_arg;
975 if (option_arg == next_option)
978 else if (strncmp(option, "-basepath", option_len) == 0)
980 if (option_arg == NULL)
981 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
983 /* this should be extended to separate options for ro and rw data */
984 options.ro_base_directory = ro_base_path = option_arg;
985 options.rw_base_directory = rw_base_path = option_arg;
986 if (option_arg == next_option)
989 /* adjust paths for sub-directories in base directory accordingly */
990 options.level_directory = getPath2(ro_base_path, LEVELS_DIRECTORY);
991 options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
992 options.sounds_directory = getPath2(ro_base_path, SOUNDS_DIRECTORY);
993 options.music_directory = getPath2(ro_base_path, MUSIC_DIRECTORY);
994 options.docs_directory = getPath2(ro_base_path, DOCS_DIRECTORY);
996 else if (strncmp(option, "-levels", option_len) == 0)
998 if (option_arg == NULL)
999 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1001 options.level_directory = option_arg;
1002 if (option_arg == next_option)
1005 else if (strncmp(option, "-graphics", option_len) == 0)
1007 if (option_arg == NULL)
1008 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1010 options.graphics_directory = option_arg;
1011 if (option_arg == next_option)
1014 else if (strncmp(option, "-sounds", option_len) == 0)
1016 if (option_arg == NULL)
1017 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1019 options.sounds_directory = option_arg;
1020 if (option_arg == next_option)
1023 else if (strncmp(option, "-music", option_len) == 0)
1025 if (option_arg == NULL)
1026 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1028 options.music_directory = option_arg;
1029 if (option_arg == next_option)
1032 else if (strncmp(option, "-network", option_len) == 0)
1034 options.network = TRUE;
1036 else if (strncmp(option, "-serveronly", option_len) == 0)
1038 options.serveronly = TRUE;
1040 else if (strncmp(option, "-debug", option_len) == 0)
1042 options.debug = TRUE;
1044 else if (strncmp(option, "-verbose", option_len) == 0)
1046 options.verbose = TRUE;
1048 else if (strncmp(option, "-version", option_len) == 0 ||
1049 strncmp(option, "-V", option_len) == 0)
1051 print_version_function();
1055 else if (strPrefix(option, "-D"))
1057 options.special_flags = getStringCopy(&option[2]);
1059 else if (strncmp(option, "-execute", option_len) == 0)
1061 if (option_arg == NULL)
1062 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
1064 options.execute_command = option_arg;
1065 if (option_arg == next_option)
1068 /* when doing batch processing, always enable verbose mode (warnings) */
1069 options.verbose = TRUE;
1071 else if (*option == '-')
1073 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
1075 else if (options.server_host == NULL)
1077 options.server_host = *options_left;
1079 else if (options.server_port == 0)
1081 options.server_port = atoi(*options_left);
1082 if (options.server_port < 1024)
1083 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
1086 Error(ERR_EXIT_HELP, "too many arguments");
1093 /* ------------------------------------------------------------------------- */
1094 /* error handling functions */
1095 /* ------------------------------------------------------------------------- */
1097 #define MAX_INTERNAL_ERROR_SIZE 1024
1099 /* used by SetError() and GetError() to store internal error messages */
1100 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
1102 void SetError(char *format, ...)
1106 va_start(ap, format);
1107 vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
1113 return internal_error;
1116 void Error(int mode, char *format, ...)
1118 static boolean last_line_was_separator = FALSE;
1119 char *process_name = "";
1121 if (program.log_file[LOG_ERR_ID] == NULL)
1124 #if defined(PLATFORM_ANDROID)
1125 android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
1126 mode & ERR_INFO ? ANDROID_LOG_INFO :
1127 mode & ERR_WARN ? ANDROID_LOG_WARN :
1128 mode & ERR_EXIT ? ANDROID_LOG_FATAL :
1129 ANDROID_LOG_UNKNOWN);
1132 /* display warnings only when running in verbose mode */
1133 if (mode & ERR_WARN && !options.verbose)
1136 if (mode == ERR_INFO_LINE)
1138 if (!last_line_was_separator)
1139 printf_log_line(format, 79);
1141 last_line_was_separator = TRUE;
1146 last_line_was_separator = FALSE;
1148 if (mode & ERR_SOUND_SERVER)
1149 process_name = " sound server";
1150 else if (mode & ERR_NETWORK_SERVER)
1151 process_name = " network server";
1152 else if (mode & ERR_NETWORK_CLIENT)
1153 process_name = " network client **";
1157 #if !defined(PLATFORM_ANDROID)
1158 printf_log_nonewline("%s%s: ", program.command_basename, process_name);
1161 if (mode & ERR_WARN)
1162 printf_log_nonewline("warning: ");
1164 if (mode & ERR_EXIT)
1165 printf_log_nonewline("fatal error: ");
1169 va_start(ap, format);
1170 vprintf_log(format, ap);
1173 if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1175 va_start(ap, format);
1176 program.exit_message_function(format, ap);
1181 if (mode & ERR_HELP)
1182 printf_log("%s: Try option '--help' for more information.",
1183 program.command_basename);
1185 if (mode & ERR_EXIT)
1186 printf_log("%s%s: aborting", program.command_basename, process_name);
1188 if (mode & ERR_EXIT)
1190 if (mode & ERR_FROM_SERVER)
1191 exit(1); /* child process: normal exit */
1193 program.exit_function(1); /* main process: clean up stuff */
1198 /* ------------------------------------------------------------------------- */
1199 /* checked memory allocation and freeing functions */
1200 /* ------------------------------------------------------------------------- */
1202 void *checked_malloc(unsigned int size)
1209 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1214 void *checked_calloc(unsigned int size)
1218 ptr = calloc(1, size);
1221 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1226 void *checked_realloc(void *ptr, unsigned int size)
1228 ptr = realloc(ptr, size);
1231 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1236 void checked_free(void *ptr)
1238 if (ptr != NULL) /* this check should be done by free() anyway */
1242 void clear_mem(void *ptr, unsigned int size)
1244 #if defined(PLATFORM_WIN32)
1245 /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1246 char *cptr = (char *)ptr;
1251 memset(ptr, 0, size);
1256 /* ------------------------------------------------------------------------- */
1257 /* various helper functions */
1258 /* ------------------------------------------------------------------------- */
1260 inline void swap_numbers(int *i1, int *i2)
1268 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1280 /* the "put" variants of the following file access functions check for the file
1281 pointer being != NULL and return the number of bytes they have or would have
1282 written; this allows for chunk writing functions to first determine the size
1283 of the (not yet written) chunk, write the correct chunk size and finally
1284 write the chunk itself */
1286 int getFile8BitInteger(File *file)
1288 return getByteFromFile(file);
1291 int putFile8BitInteger(FILE *file, int value)
1299 int getFile16BitInteger(File *file, int byte_order)
1301 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1302 return ((getByteFromFile(file) << 8) |
1303 (getByteFromFile(file) << 0));
1304 else /* BYTE_ORDER_LITTLE_ENDIAN */
1305 return ((getByteFromFile(file) << 0) |
1306 (getByteFromFile(file) << 8));
1309 int putFile16BitInteger(FILE *file, int value, int byte_order)
1313 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1315 fputc((value >> 8) & 0xff, file);
1316 fputc((value >> 0) & 0xff, file);
1318 else /* BYTE_ORDER_LITTLE_ENDIAN */
1320 fputc((value >> 0) & 0xff, file);
1321 fputc((value >> 8) & 0xff, file);
1328 int getFile32BitInteger(File *file, int byte_order)
1330 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1331 return ((getByteFromFile(file) << 24) |
1332 (getByteFromFile(file) << 16) |
1333 (getByteFromFile(file) << 8) |
1334 (getByteFromFile(file) << 0));
1335 else /* BYTE_ORDER_LITTLE_ENDIAN */
1336 return ((getByteFromFile(file) << 0) |
1337 (getByteFromFile(file) << 8) |
1338 (getByteFromFile(file) << 16) |
1339 (getByteFromFile(file) << 24));
1342 int putFile32BitInteger(FILE *file, int value, int byte_order)
1346 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1348 fputc((value >> 24) & 0xff, file);
1349 fputc((value >> 16) & 0xff, file);
1350 fputc((value >> 8) & 0xff, file);
1351 fputc((value >> 0) & 0xff, file);
1353 else /* BYTE_ORDER_LITTLE_ENDIAN */
1355 fputc((value >> 0) & 0xff, file);
1356 fputc((value >> 8) & 0xff, file);
1357 fputc((value >> 16) & 0xff, file);
1358 fputc((value >> 24) & 0xff, file);
1365 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1368 const int chunk_name_length = 4;
1370 /* read chunk name */
1371 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1374 if (chunk_size != NULL)
1376 /* read chunk size */
1377 *chunk_size = getFile32BitInteger(file, byte_order);
1380 return (checkEndOfFile(file) ? FALSE : TRUE);
1383 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1388 /* write chunk name */
1390 fputs(chunk_name, file);
1392 num_bytes += strlen(chunk_name);
1394 if (chunk_size >= 0)
1396 /* write chunk size */
1398 putFile32BitInteger(file, chunk_size, byte_order);
1406 int getFileVersion(File *file)
1408 int version_major = getByteFromFile(file);
1409 int version_minor = getByteFromFile(file);
1410 int version_patch = getByteFromFile(file);
1411 int version_build = getByteFromFile(file);
1413 return VERSION_IDENT(version_major, version_minor, version_patch,
1417 int putFileVersion(FILE *file, int version)
1421 int version_major = VERSION_MAJOR(version);
1422 int version_minor = VERSION_MINOR(version);
1423 int version_patch = VERSION_PATCH(version);
1424 int version_build = VERSION_BUILD(version);
1426 fputc(version_major, file);
1427 fputc(version_minor, file);
1428 fputc(version_patch, file);
1429 fputc(version_build, file);
1435 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1439 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1440 buffer[i] = getByteFromFile(file);
1443 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1447 for(i = 0; i < bytes; i++)
1448 fputc(buffer[i], file);
1451 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1453 while (bytes-- && !checkEndOfFile(file))
1454 getByteFromFile(file);
1457 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1464 /* ------------------------------------------------------------------------- */
1465 /* functions to translate key identifiers between different format */
1466 /* ------------------------------------------------------------------------- */
1468 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1469 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1470 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1471 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1473 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1482 /* normal cursor keys */
1483 { KSYM_Left, "XK_Left", "cursor left" },
1484 { KSYM_Right, "XK_Right", "cursor right" },
1485 { KSYM_Up, "XK_Up", "cursor up" },
1486 { KSYM_Down, "XK_Down", "cursor down" },
1488 /* keypad cursor keys */
1490 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1491 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1492 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1493 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1496 /* other keypad keys */
1497 #ifdef KSYM_KP_Enter
1498 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1499 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1500 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1501 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1502 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1503 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1507 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1508 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1509 { KSYM_Control_L, "XK_Control_L", "left control" },
1510 { KSYM_Control_R, "XK_Control_R", "right control" },
1511 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1512 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1513 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1514 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1515 #if !defined(TARGET_SDL2)
1516 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1517 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1519 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1520 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1522 /* some special keys */
1523 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1524 { KSYM_Delete, "XK_Delete", "delete" },
1525 { KSYM_Insert, "XK_Insert", "insert" },
1526 { KSYM_Tab, "XK_Tab", "tab" },
1527 { KSYM_Home, "XK_Home", "home" },
1528 { KSYM_End, "XK_End", "end" },
1529 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1530 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1532 #if defined(TARGET_SDL2)
1533 { KSYM_Menu, "XK_Menu", "menu" }, /* menu key */
1534 { KSYM_Back, "XK_Back", "back" }, /* back key */
1537 /* ASCII 0x20 to 0x40 keys (except numbers) */
1538 { KSYM_space, "XK_space", "space" },
1539 { KSYM_exclam, "XK_exclam", "!" },
1540 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1541 { KSYM_numbersign, "XK_numbersign", "#" },
1542 { KSYM_dollar, "XK_dollar", "$" },
1543 { KSYM_percent, "XK_percent", "%" },
1544 { KSYM_ampersand, "XK_ampersand", "&" },
1545 { KSYM_apostrophe, "XK_apostrophe", "'" },
1546 { KSYM_parenleft, "XK_parenleft", "(" },
1547 { KSYM_parenright, "XK_parenright", ")" },
1548 { KSYM_asterisk, "XK_asterisk", "*" },
1549 { KSYM_plus, "XK_plus", "+" },
1550 { KSYM_comma, "XK_comma", "," },
1551 { KSYM_minus, "XK_minus", "-" },
1552 { KSYM_period, "XK_period", "." },
1553 { KSYM_slash, "XK_slash", "/" },
1554 { KSYM_colon, "XK_colon", ":" },
1555 { KSYM_semicolon, "XK_semicolon", ";" },
1556 { KSYM_less, "XK_less", "<" },
1557 { KSYM_equal, "XK_equal", "=" },
1558 { KSYM_greater, "XK_greater", ">" },
1559 { KSYM_question, "XK_question", "?" },
1560 { KSYM_at, "XK_at", "@" },
1562 /* more ASCII keys */
1563 { KSYM_bracketleft, "XK_bracketleft", "[" },
1564 { KSYM_backslash, "XK_backslash", "\\" },
1565 { KSYM_bracketright,"XK_bracketright", "]" },
1566 { KSYM_asciicircum, "XK_asciicircum", "^" },
1567 { KSYM_underscore, "XK_underscore", "_" },
1568 { KSYM_grave, "XK_grave", "grave" },
1569 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1570 { KSYM_braceleft, "XK_braceleft", "brace left" },
1571 { KSYM_bar, "XK_bar", "bar" },
1572 { KSYM_braceright, "XK_braceright", "brace right" },
1573 { KSYM_asciitilde, "XK_asciitilde", "~" },
1575 /* special (non-ASCII) keys */
1576 { KSYM_degree, "XK_degree", "degree" },
1577 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
1578 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
1579 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
1580 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
1581 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
1582 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
1583 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1585 #if defined(TARGET_SDL2)
1586 /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1587 { KSYM_degree, "XK_degree", "\xc2\xb0" },
1588 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
1589 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
1590 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
1591 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
1592 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
1593 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
1594 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
1596 /* other keys (for reverse mapping only) */
1597 { KSYM_space, "XK_space", " " },
1600 #if defined(TARGET_SDL2)
1601 /* keypad keys are not in numerical order in SDL2 */
1602 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
1603 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
1604 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
1605 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
1606 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
1607 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
1608 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
1609 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
1610 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
1611 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
1614 /* end-of-array identifier */
1620 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1622 static char name_buffer[30];
1625 if (key >= KSYM_A && key <= KSYM_Z)
1626 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1627 else if (key >= KSYM_a && key <= KSYM_z)
1628 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1629 else if (key >= KSYM_0 && key <= KSYM_9)
1630 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1631 #if !defined(TARGET_SDL2)
1632 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1633 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1635 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1636 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1637 else if (key == KSYM_UNDEFINED)
1638 strcpy(name_buffer, "(undefined)");
1645 if (key == translate_key[i].key)
1647 strcpy(name_buffer, translate_key[i].name);
1651 while (translate_key[++i].name);
1653 if (!translate_key[i].name)
1654 strcpy(name_buffer, "(unknown)");
1657 *name = name_buffer;
1659 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1661 static char name_buffer[30];
1664 if (key >= KSYM_A && key <= KSYM_Z)
1665 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1666 else if (key >= KSYM_a && key <= KSYM_z)
1667 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1668 else if (key >= KSYM_0 && key <= KSYM_9)
1669 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1670 #if !defined(TARGET_SDL2)
1671 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1672 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1674 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1675 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1676 else if (key == KSYM_UNDEFINED)
1677 strcpy(name_buffer, "[undefined]");
1684 if (key == translate_key[i].key)
1686 strcpy(name_buffer, translate_key[i].x11name);
1690 while (translate_key[++i].x11name);
1692 if (!translate_key[i].x11name)
1693 sprintf(name_buffer, "0x%04x", (unsigned int)key);
1696 *x11name = name_buffer;
1698 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1700 Key key = KSYM_UNDEFINED;
1701 char *name_ptr = *name;
1703 if (strlen(*name) == 1)
1705 char c = name_ptr[0];
1707 if (c >= 'A' && c <= 'Z')
1708 key = KSYM_A + (Key)(c - 'A');
1709 else if (c >= 'a' && c <= 'z')
1710 key = KSYM_a + (Key)(c - 'a');
1711 else if (c >= '0' && c <= '9')
1712 key = KSYM_0 + (Key)(c - '0');
1715 if (key == KSYM_UNDEFINED)
1721 if (strEqual(translate_key[i].name, *name))
1723 key = translate_key[i].key;
1727 while (translate_key[++i].x11name);
1730 if (key == KSYM_UNDEFINED)
1731 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1735 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1737 Key key = KSYM_UNDEFINED;
1738 char *name_ptr = *x11name;
1740 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1742 char c = name_ptr[3];
1744 if (c >= 'A' && c <= 'Z')
1745 key = KSYM_A + (Key)(c - 'A');
1746 else if (c >= 'a' && c <= 'z')
1747 key = KSYM_a + (Key)(c - 'a');
1748 else if (c >= '0' && c <= '9')
1749 key = KSYM_0 + (Key)(c - '0');
1751 #if !defined(TARGET_SDL2)
1752 else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1754 char c = name_ptr[6];
1756 if (c >= '0' && c <= '9')
1757 key = KSYM_KP_0 + (Key)(c - '0');
1760 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1762 char c1 = name_ptr[4];
1763 char c2 = name_ptr[5];
1766 if ((c1 >= '0' && c1 <= '9') &&
1767 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1768 d = atoi(&name_ptr[4]);
1770 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1771 key = KSYM_F1 + (Key)(d - 1);
1773 else if (strPrefix(name_ptr, "XK_"))
1779 if (strEqual(name_ptr, translate_key[i].x11name))
1781 key = translate_key[i].key;
1785 while (translate_key[++i].x11name);
1787 else if (strPrefix(name_ptr, "0x"))
1789 unsigned int value = 0;
1795 char c = *name_ptr++;
1798 if (c >= '0' && c <= '9')
1800 else if (c >= 'a' && c <= 'f')
1801 d = (int)(c - 'a' + 10);
1802 else if (c >= 'A' && c <= 'F')
1803 d = (int)(c - 'A' + 10);
1811 value = value * 16 + d;
1822 char *getKeyNameFromKey(Key key)
1826 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1830 char *getX11KeyNameFromKey(Key key)
1834 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1838 Key getKeyFromKeyName(char *name)
1842 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1846 Key getKeyFromX11KeyName(char *x11name)
1850 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1854 char getCharFromKey(Key key)
1860 } translate_key_char[] =
1862 /* special (non-ASCII) keys (ISO-8859-1) */
1863 { KSYM_degree, CHAR_BYTE_DEGREE },
1864 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
1865 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
1866 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
1867 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
1868 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
1869 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
1870 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
1872 /* end-of-array identifier */
1876 char *keyname = getKeyNameFromKey(key);
1879 if (strlen(keyname) == 1)
1881 else if (strEqual(keyname, "space"))
1889 if (key == translate_key_char[i].key)
1891 c = translate_key_char[i].key_char;
1896 while (translate_key_char[++i].key_char);
1902 char getValidConfigValueChar(char c)
1904 if (c == '#' || /* used to mark comments */
1905 c == '\\') /* used to mark continued lines */
1912 /* ------------------------------------------------------------------------- */
1913 /* functions to translate string identifiers to integer or boolean value */
1914 /* ------------------------------------------------------------------------- */
1916 int get_integer_from_string(char *s)
1918 static char *number_text[][3] =
1920 { "0", "zero", "null", },
1921 { "1", "one", "first" },
1922 { "2", "two", "second" },
1923 { "3", "three", "third" },
1924 { "4", "four", "fourth" },
1925 { "5", "five", "fifth" },
1926 { "6", "six", "sixth" },
1927 { "7", "seven", "seventh" },
1928 { "8", "eight", "eighth" },
1929 { "9", "nine", "ninth" },
1930 { "10", "ten", "tenth" },
1931 { "11", "eleven", "eleventh" },
1932 { "12", "twelve", "twelfth" },
1934 { NULL, NULL, NULL },
1938 char *s_lower = getStringToLower(s);
1941 for (i = 0; number_text[i][0] != NULL; i++)
1942 for (j = 0; j < 3; j++)
1943 if (strEqual(s_lower, number_text[i][j]))
1948 if (strEqual(s_lower, "false") ||
1949 strEqual(s_lower, "no") ||
1950 strEqual(s_lower, "off"))
1952 else if (strEqual(s_lower, "true") ||
1953 strEqual(s_lower, "yes") ||
1954 strEqual(s_lower, "on"))
1965 boolean get_boolean_from_string(char *s)
1967 char *s_lower = getStringToLower(s);
1968 boolean result = FALSE;
1970 if (strEqual(s_lower, "true") ||
1971 strEqual(s_lower, "yes") ||
1972 strEqual(s_lower, "on") ||
1973 get_integer_from_string(s) == 1)
1981 int get_switch3_from_string(char *s)
1983 char *s_lower = getStringToLower(s);
1986 if (strEqual(s_lower, "true") ||
1987 strEqual(s_lower, "yes") ||
1988 strEqual(s_lower, "on") ||
1989 get_integer_from_string(s) == 1)
1991 else if (strEqual(s_lower, "auto"))
2000 /* ------------------------------------------------------------------------- */
2001 /* functions for generic lists */
2002 /* ------------------------------------------------------------------------- */
2004 ListNode *newListNode()
2006 return checked_calloc(sizeof(ListNode));
2009 void addNodeToList(ListNode **node_first, char *key, void *content)
2011 ListNode *node_new = newListNode();
2013 node_new->key = getStringCopy(key);
2014 node_new->content = content;
2015 node_new->next = *node_first;
2018 (*node_first)->prev = node_new;
2020 *node_first = node_new;
2023 void deleteNodeFromList(ListNode **node_first, char *key,
2024 void (*destructor_function)(void *))
2026 if (node_first == NULL || *node_first == NULL)
2029 if (strEqual((*node_first)->key, key))
2031 checked_free((*node_first)->key);
2033 if (destructor_function)
2034 destructor_function((*node_first)->content);
2036 if ((*node_first)->next)
2037 (*node_first)->next->prev = (*node_first)->prev;
2039 checked_free(*node_first);
2041 *node_first = (*node_first)->next;
2044 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
2047 ListNode *getNodeFromKey(ListNode *node_first, char *key)
2049 if (node_first == NULL)
2052 if (strEqual(node_first->key, key))
2055 return getNodeFromKey(node_first->next, key);
2058 int getNumNodes(ListNode *node_first)
2060 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
2063 void dumpList(ListNode *node_first)
2065 ListNode *node = node_first;
2069 printf("['%s' (%d)]\n", node->key,
2070 ((struct ListNodeInfo *)node->content)->num_references);
2074 printf("[%d nodes]\n", getNumNodes(node_first));
2078 /* ------------------------------------------------------------------------- */
2079 /* functions for file handling */
2080 /* ------------------------------------------------------------------------- */
2082 File *openFile(char *filename, char *mode)
2084 File *file = checked_calloc(sizeof(File));
2086 file->file = fopen(filename, mode);
2088 if (file->file != NULL)
2090 file->filename = getStringCopy(filename);
2095 #if defined(PLATFORM_ANDROID)
2096 file->asset_file = SDL_RWFromFile(filename, mode);
2098 if (file->asset_file != NULL)
2100 file->file_is_asset = TRUE;
2101 file->filename = getStringCopy(filename);
2112 int closeFile(File *file)
2119 #if defined(PLATFORM_ANDROID)
2120 if (file->asset_file)
2121 result = SDL_RWclose(file->asset_file);
2125 result = fclose(file->file);
2127 checked_free(file->filename);
2133 int checkEndOfFile(File *file)
2135 #if defined(PLATFORM_ANDROID)
2136 if (file->file_is_asset)
2137 return file->end_of_file;
2140 return feof(file->file);
2143 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
2145 #if defined(PLATFORM_ANDROID)
2146 if (file->file_is_asset)
2148 if (file->end_of_file)
2151 size_t num_items_read =
2152 SDL_RWread(file->asset_file, buffer, item_size, num_items);
2154 if (num_items_read < num_items)
2155 file->end_of_file = TRUE;
2157 return num_items_read;
2161 return fread(buffer, item_size, num_items, file->file);
2164 int seekFile(File *file, long offset, int whence)
2166 #if defined(PLATFORM_ANDROID)
2167 if (file->file_is_asset)
2169 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2170 whence == SEEK_CUR ? RW_SEEK_CUR :
2171 whence == SEEK_END ? RW_SEEK_END : 0);
2173 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2177 return fseek(file->file, offset, whence);
2180 int getByteFromFile(File *file)
2182 #if defined(PLATFORM_ANDROID)
2183 if (file->file_is_asset)
2185 if (file->end_of_file)
2189 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2191 if (num_bytes_read < 1)
2192 file->end_of_file = TRUE;
2194 return (file->end_of_file ? EOF : (int)c);
2198 return fgetc(file->file);
2201 char *getStringFromFile(File *file, char *line, int size)
2203 #if defined(PLATFORM_ANDROID)
2204 if (file->file_is_asset)
2206 if (file->end_of_file)
2209 char *line_ptr = line;
2210 int num_bytes_read = 0;
2212 while (num_bytes_read < size - 1 &&
2213 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2214 *line_ptr++ != '\n')
2219 if (strlen(line) == 0)
2221 file->end_of_file = TRUE;
2230 return fgets(line, size, file->file);
2234 /* ------------------------------------------------------------------------- */
2235 /* functions for directory handling */
2236 /* ------------------------------------------------------------------------- */
2238 Directory *openDirectory(char *dir_name)
2240 Directory *dir = checked_calloc(sizeof(Directory));
2242 dir->dir = opendir(dir_name);
2244 if (dir->dir != NULL)
2246 dir->filename = getStringCopy(dir_name);
2251 #if defined(PLATFORM_ANDROID)
2252 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2254 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2256 checked_free(asset_toc_filename);
2258 if (dir->asset_toc_file != NULL)
2260 dir->directory_is_asset = TRUE;
2261 dir->filename = getStringCopy(dir_name);
2272 int closeDirectory(Directory *dir)
2279 #if defined(PLATFORM_ANDROID)
2280 if (dir->asset_toc_file)
2281 result = SDL_RWclose(dir->asset_toc_file);
2285 result = closedir(dir->dir);
2288 freeDirectoryEntry(dir->dir_entry);
2290 checked_free(dir->filename);
2296 DirectoryEntry *readDirectory(Directory *dir)
2299 freeDirectoryEntry(dir->dir_entry);
2301 dir->dir_entry = NULL;
2303 #if defined(PLATFORM_ANDROID)
2304 if (dir->directory_is_asset)
2306 char line[MAX_LINE_LEN];
2307 char *line_ptr = line;
2308 int num_bytes_read = 0;
2310 while (num_bytes_read < MAX_LINE_LEN - 1 &&
2311 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2320 if (strlen(line) == 0)
2323 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2325 dir->dir_entry->is_directory = FALSE;
2326 if (line[strlen(line) - 1] == '/')
2328 dir->dir_entry->is_directory = TRUE;
2330 line[strlen(line) - 1] = '\0';
2333 dir->dir_entry->basename = getStringCopy(line);
2334 dir->dir_entry->filename = getPath2(dir->filename, line);
2336 return dir->dir_entry;
2340 struct dirent *dir_entry = readdir(dir->dir);
2342 if (dir_entry == NULL)
2345 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2347 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2348 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2350 struct stat file_status;
2352 dir->dir_entry->is_directory =
2353 (stat(dir->dir_entry->filename, &file_status) == 0 &&
2354 (file_status.st_mode & S_IFMT) == S_IFDIR);
2356 return dir->dir_entry;
2359 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2361 if (dir_entry == NULL)
2364 checked_free(dir_entry->basename);
2365 checked_free(dir_entry->filename);
2366 checked_free(dir_entry);
2370 /* ------------------------------------------------------------------------- */
2371 /* functions for checking files and filenames */
2372 /* ------------------------------------------------------------------------- */
2374 boolean directoryExists(char *dir_name)
2376 if (dir_name == NULL)
2379 struct stat file_status;
2380 boolean success = (stat(dir_name, &file_status) == 0 &&
2381 (file_status.st_mode & S_IFMT) == S_IFDIR);
2383 #if defined(PLATFORM_ANDROID)
2386 // this might be an asset directory; check by trying to open toc file
2387 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2388 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2390 checked_free(asset_toc_filename);
2392 success = (file != NULL);
2402 boolean fileExists(char *filename)
2404 if (filename == NULL)
2407 boolean success = (access(filename, F_OK) == 0);
2409 #if defined(PLATFORM_ANDROID)
2412 // this might be an asset file; check by trying to open it
2413 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2415 success = (file != NULL);
2425 boolean fileHasPrefix(char *basename, char *prefix)
2427 static char *basename_lower = NULL;
2428 int basename_length, prefix_length;
2430 checked_free(basename_lower);
2432 if (basename == NULL || prefix == NULL)
2435 basename_lower = getStringToLower(basename);
2436 basename_length = strlen(basename_lower);
2437 prefix_length = strlen(prefix);
2439 if (basename_length > prefix_length + 1 &&
2440 basename_lower[prefix_length] == '.' &&
2441 strncmp(basename_lower, prefix, prefix_length) == 0)
2447 boolean fileHasSuffix(char *basename, char *suffix)
2449 static char *basename_lower = NULL;
2450 int basename_length, suffix_length;
2452 checked_free(basename_lower);
2454 if (basename == NULL || suffix == NULL)
2457 basename_lower = getStringToLower(basename);
2458 basename_length = strlen(basename_lower);
2459 suffix_length = strlen(suffix);
2461 if (basename_length > suffix_length + 1 &&
2462 basename_lower[basename_length - suffix_length - 1] == '.' &&
2463 strEqual(&basename_lower[basename_length - suffix_length], suffix))
2469 static boolean FileCouldBeArtwork(char *filename)
2471 char *basename = getBaseNamePtr(filename);
2473 return (!strEqual(basename, ".") &&
2474 !strEqual(basename, "..") &&
2475 !fileHasSuffix(basename, "txt") &&
2476 !fileHasSuffix(basename, "conf") &&
2477 !directoryExists(filename));
2480 boolean FileIsGraphic(char *filename)
2482 return FileCouldBeArtwork(filename);
2485 boolean FileIsSound(char *filename)
2487 return FileCouldBeArtwork(filename);
2490 boolean FileIsMusic(char *filename)
2492 return FileCouldBeArtwork(filename);
2495 boolean FileIsArtworkType(char *filename, int type)
2497 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2498 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2499 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2505 /* ------------------------------------------------------------------------- */
2506 /* functions for loading artwork configuration information */
2507 /* ------------------------------------------------------------------------- */
2509 char *get_mapped_token(char *token)
2511 /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2512 static char *map_token_prefix[][2] =
2514 { "char_procent", "char_percent" },
2519 for (i = 0; map_token_prefix[i][0] != NULL; i++)
2521 int len_token_prefix = strlen(map_token_prefix[i][0]);
2523 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2524 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2530 /* This function checks if a string <s> of the format "string1, string2, ..."
2531 exactly contains a string <s_contained>. */
2533 static boolean string_has_parameter(char *s, char *s_contained)
2537 if (s == NULL || s_contained == NULL)
2540 if (strlen(s_contained) > strlen(s))
2543 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2545 char next_char = s[strlen(s_contained)];
2547 /* check if next character is delimiter or whitespace */
2548 return (next_char == ',' || next_char == '\0' ||
2549 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2552 /* check if string contains another parameter string after a comma */
2553 substring = strchr(s, ',');
2554 if (substring == NULL) /* string does not contain a comma */
2557 /* advance string pointer to next character after the comma */
2560 /* skip potential whitespaces after the comma */
2561 while (*substring == ' ' || *substring == '\t')
2564 return string_has_parameter(substring, s_contained);
2567 int get_parameter_value(char *value_raw, char *suffix, int type)
2569 char *value = getStringToLower(value_raw);
2570 int result = 0; /* probably a save default value */
2572 if (strEqual(suffix, ".direction"))
2574 result = (strEqual(value, "left") ? MV_LEFT :
2575 strEqual(value, "right") ? MV_RIGHT :
2576 strEqual(value, "up") ? MV_UP :
2577 strEqual(value, "down") ? MV_DOWN : MV_NONE);
2579 else if (strEqual(suffix, ".align"))
2581 result = (strEqual(value, "left") ? ALIGN_LEFT :
2582 strEqual(value, "right") ? ALIGN_RIGHT :
2583 strEqual(value, "center") ? ALIGN_CENTER :
2584 strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2586 else if (strEqual(suffix, ".valign"))
2588 result = (strEqual(value, "top") ? VALIGN_TOP :
2589 strEqual(value, "bottom") ? VALIGN_BOTTOM :
2590 strEqual(value, "middle") ? VALIGN_MIDDLE :
2591 strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2593 else if (strEqual(suffix, ".anim_mode"))
2595 result = (string_has_parameter(value, "none") ? ANIM_NONE :
2596 string_has_parameter(value, "loop") ? ANIM_LOOP :
2597 string_has_parameter(value, "linear") ? ANIM_LINEAR :
2598 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
2599 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
2600 string_has_parameter(value, "random") ? ANIM_RANDOM :
2601 string_has_parameter(value, "ce_value") ? ANIM_CE_VALUE :
2602 string_has_parameter(value, "ce_score") ? ANIM_CE_SCORE :
2603 string_has_parameter(value, "ce_delay") ? ANIM_CE_DELAY :
2604 string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2605 string_has_parameter(value, "vertical") ? ANIM_VERTICAL :
2606 string_has_parameter(value, "centered") ? ANIM_CENTERED :
2609 if (string_has_parameter(value, "reverse"))
2610 result |= ANIM_REVERSE;
2612 if (string_has_parameter(value, "opaque_player"))
2613 result |= ANIM_OPAQUE_PLAYER;
2615 if (string_has_parameter(value, "static_panel"))
2616 result |= ANIM_STATIC_PANEL;
2618 else if (strEqual(suffix, ".class"))
2620 result = get_hash_from_key(value);
2622 else if (strEqual(suffix, ".style"))
2624 result = STYLE_DEFAULT;
2626 if (string_has_parameter(value, "accurate_borders"))
2627 result |= STYLE_ACCURATE_BORDERS;
2629 if (string_has_parameter(value, "inner_corners"))
2630 result |= STYLE_INNER_CORNERS;
2632 else if (strEqual(suffix, ".fade_mode"))
2634 result = (string_has_parameter(value, "none") ? FADE_MODE_NONE :
2635 string_has_parameter(value, "fade") ? FADE_MODE_FADE :
2636 string_has_parameter(value, "crossfade") ? FADE_MODE_CROSSFADE :
2637 string_has_parameter(value, "melt") ? FADE_MODE_MELT :
2640 else if (strPrefix(suffix, ".font")) /* (may also be ".font_xyz") */
2642 result = gfx.get_font_from_token_function(value);
2644 else /* generic parameter of type integer or boolean */
2646 result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2647 type == TYPE_INTEGER ? get_integer_from_string(value) :
2648 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2649 ARG_UNDEFINED_VALUE);
2657 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2659 static struct ScreenModeInfo screen_mode;
2660 char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2661 char *screen_mode_string_copy;
2662 char *screen_mode_string_pos_w;
2663 char *screen_mode_string_pos_h;
2665 if (screen_mode_string_x == NULL) /* invalid screen mode format */
2668 screen_mode_string_copy = getStringCopy(screen_mode_string);
2670 screen_mode_string_pos_w = screen_mode_string_copy;
2671 screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2672 *screen_mode_string_pos_h++ = '\0';
2674 screen_mode.width = atoi(screen_mode_string_pos_w);
2675 screen_mode.height = atoi(screen_mode_string_pos_h);
2677 return &screen_mode;
2680 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2683 float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2684 float aspect_ratio_new;
2689 *x = i * aspect_ratio + 0.000001;
2692 aspect_ratio_new = (float)*x / (float)*y;
2696 while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2699 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2700 struct ListNodeInfo ***, int *);
2702 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2703 struct ConfigTypeInfo *suffix_list,
2704 char **ignore_tokens,
2705 int num_file_list_entries)
2707 struct FileInfo *file_list;
2708 int num_file_list_entries_found = 0;
2709 int num_suffix_list_entries = 0;
2713 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2715 for (i = 0; suffix_list[i].token != NULL; i++)
2716 num_suffix_list_entries++;
2718 /* always start with reliable default values */
2719 for (i = 0; i < num_file_list_entries; i++)
2721 file_list[i].token = NULL;
2723 file_list[i].default_filename = NULL;
2724 file_list[i].filename = NULL;
2726 if (num_suffix_list_entries > 0)
2728 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2730 file_list[i].default_parameter = checked_calloc(parameter_array_size);
2731 file_list[i].parameter = checked_calloc(parameter_array_size);
2733 for (j = 0; j < num_suffix_list_entries; j++)
2735 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2736 setString(&file_list[i].parameter[j], suffix_list[j].value);
2739 file_list[i].redefined = FALSE;
2740 file_list[i].fallback_to_default = FALSE;
2741 file_list[i].default_is_cloned = FALSE;
2747 for (i = 0; config_list[i].token != NULL; i++)
2749 int len_config_token = strlen(config_list[i].token);
2750 boolean is_file_entry = TRUE;
2752 for (j = 0; suffix_list[j].token != NULL; j++)
2754 int len_suffix = strlen(suffix_list[j].token);
2756 if (len_suffix < len_config_token &&
2757 strEqual(&config_list[i].token[len_config_token - len_suffix],
2758 suffix_list[j].token))
2760 setString(&file_list[list_pos].default_parameter[j],
2761 config_list[i].value);
2763 is_file_entry = FALSE;
2769 /* the following tokens are no file definitions, but other config tokens */
2770 for (j = 0; ignore_tokens[j] != NULL; j++)
2771 if (strEqual(config_list[i].token, ignore_tokens[j]))
2772 is_file_entry = FALSE;
2779 if (list_pos >= num_file_list_entries)
2782 file_list[list_pos].token = config_list[i].token;
2783 file_list[list_pos].default_filename = config_list[i].value;
2786 if (strSuffix(config_list[i].token, ".clone_from"))
2787 file_list[list_pos].default_is_cloned = TRUE;
2790 num_file_list_entries_found = list_pos + 1;
2791 if (num_file_list_entries_found != num_file_list_entries)
2793 Error(ERR_INFO_LINE, "-");
2794 Error(ERR_INFO, "inconsistant config list information:");
2795 Error(ERR_INFO, "- should be: %d (according to 'src/conf_xxx.h')",
2796 num_file_list_entries);
2797 Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2798 num_file_list_entries_found);
2799 Error(ERR_EXIT, "please fix");
2805 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2807 int len_token = strlen(token);
2808 int len_suffix = strlen(suffix);
2810 if (start_pos < 0) /* compare suffix from end of string */
2811 start_pos += len_token;
2813 if (start_pos < 0 || start_pos + len_suffix > len_token)
2816 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2819 if (token[start_pos + len_suffix] == '\0')
2822 if (token[start_pos + len_suffix] == '.')
2828 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
2830 static void read_token_parameters(SetupFileHash *setup_file_hash,
2831 struct ConfigTypeInfo *suffix_list,
2832 struct FileInfo *file_list_entry)
2834 /* check for config token that is the base token without any suffixes */
2835 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2836 char *known_token_value = KNOWN_TOKEN_VALUE;
2839 if (filename != NULL)
2841 setString(&file_list_entry->filename, filename);
2843 /* when file definition found, set all parameters to default values */
2844 for (i = 0; suffix_list[i].token != NULL; i++)
2845 setString(&file_list_entry->parameter[i], suffix_list[i].value);
2847 file_list_entry->redefined = TRUE;
2849 /* mark config file token as well known from default config */
2850 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2853 /* check for config tokens that can be build by base token and suffixes */
2854 for (i = 0; suffix_list[i].token != NULL; i++)
2856 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2857 char *value = getHashEntry(setup_file_hash, token);
2861 setString(&file_list_entry->parameter[i], value);
2863 /* mark config file token as well known from default config */
2864 setHashEntry(setup_file_hash, token, known_token_value);
2871 static void add_dynamic_file_list_entry(struct FileInfo **list,
2872 int *num_list_entries,
2873 SetupFileHash *extra_file_hash,
2874 struct ConfigTypeInfo *suffix_list,
2875 int num_suffix_list_entries,
2878 struct FileInfo *new_list_entry;
2879 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2881 (*num_list_entries)++;
2882 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2883 new_list_entry = &(*list)[*num_list_entries - 1];
2885 new_list_entry->token = getStringCopy(token);
2886 new_list_entry->default_filename = NULL;
2887 new_list_entry->filename = NULL;
2888 new_list_entry->parameter = checked_calloc(parameter_array_size);
2890 new_list_entry->redefined = FALSE;
2891 new_list_entry->fallback_to_default = FALSE;
2892 new_list_entry->default_is_cloned = FALSE;
2894 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2897 static void add_property_mapping(struct PropertyMapping **list,
2898 int *num_list_entries,
2899 int base_index, int ext1_index,
2900 int ext2_index, int ext3_index,
2903 struct PropertyMapping *new_list_entry;
2905 (*num_list_entries)++;
2906 *list = checked_realloc(*list,
2907 *num_list_entries * sizeof(struct PropertyMapping));
2908 new_list_entry = &(*list)[*num_list_entries - 1];
2910 new_list_entry->base_index = base_index;
2911 new_list_entry->ext1_index = ext1_index;
2912 new_list_entry->ext2_index = ext2_index;
2913 new_list_entry->ext3_index = ext3_index;
2915 new_list_entry->artwork_index = artwork_index;
2918 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2921 struct FileInfo *file_list = artwork_info->file_list;
2922 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2923 char **base_prefixes = artwork_info->base_prefixes;
2924 char **ext1_suffixes = artwork_info->ext1_suffixes;
2925 char **ext2_suffixes = artwork_info->ext2_suffixes;
2926 char **ext3_suffixes = artwork_info->ext3_suffixes;
2927 char **ignore_tokens = artwork_info->ignore_tokens;
2928 int num_file_list_entries = artwork_info->num_file_list_entries;
2929 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2930 int num_base_prefixes = artwork_info->num_base_prefixes;
2931 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2932 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2933 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2934 int num_ignore_tokens = artwork_info->num_ignore_tokens;
2935 SetupFileHash *setup_file_hash, *valid_file_hash;
2936 SetupFileHash *extra_file_hash, *empty_file_hash;
2937 char *known_token_value = KNOWN_TOKEN_VALUE;
2940 if (filename == NULL)
2943 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2946 /* separate valid (defined) from empty (undefined) config token values */
2947 valid_file_hash = newSetupFileHash();
2948 empty_file_hash = newSetupFileHash();
2949 BEGIN_HASH_ITERATION(setup_file_hash, itr)
2951 char *value = HASH_ITERATION_VALUE(itr);
2953 setHashEntry(*value ? valid_file_hash : empty_file_hash,
2954 HASH_ITERATION_TOKEN(itr), value);
2956 END_HASH_ITERATION(setup_file_hash, itr)
2958 /* at this point, we do not need the setup file hash anymore -- free it */
2959 freeSetupFileHash(setup_file_hash);
2961 /* map deprecated to current tokens (using prefix match and replace) */
2962 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2964 char *token = HASH_ITERATION_TOKEN(itr);
2965 char *mapped_token = get_mapped_token(token);
2967 if (mapped_token != NULL)
2969 char *value = HASH_ITERATION_VALUE(itr);
2971 /* add mapped token */
2972 setHashEntry(valid_file_hash, mapped_token, value);
2974 /* ignore old token (by setting it to "known" keyword) */
2975 setHashEntry(valid_file_hash, token, known_token_value);
2980 END_HASH_ITERATION(valid_file_hash, itr)
2982 /* read parameters for all known config file tokens */
2983 for (i = 0; i < num_file_list_entries; i++)
2984 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2986 /* set all tokens that can be ignored here to "known" keyword */
2987 for (i = 0; i < num_ignore_tokens; i++)
2988 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2990 /* copy all unknown config file tokens to extra config hash */
2991 extra_file_hash = newSetupFileHash();
2992 BEGIN_HASH_ITERATION(valid_file_hash, itr)
2994 char *value = HASH_ITERATION_VALUE(itr);
2996 if (!strEqual(value, known_token_value))
2997 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2999 END_HASH_ITERATION(valid_file_hash, itr)
3001 /* at this point, we do not need the valid file hash anymore -- free it */
3002 freeSetupFileHash(valid_file_hash);
3004 /* now try to determine valid, dynamically defined config tokens */
3006 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3008 struct FileInfo **dynamic_file_list =
3009 &artwork_info->dynamic_file_list;
3010 int *num_dynamic_file_list_entries =
3011 &artwork_info->num_dynamic_file_list_entries;
3012 struct PropertyMapping **property_mapping =
3013 &artwork_info->property_mapping;
3014 int *num_property_mapping_entries =
3015 &artwork_info->num_property_mapping_entries;
3016 int current_summarized_file_list_entry =
3017 artwork_info->num_file_list_entries +
3018 artwork_info->num_dynamic_file_list_entries;
3019 char *token = HASH_ITERATION_TOKEN(itr);
3020 int len_token = strlen(token);
3022 boolean base_prefix_found = FALSE;
3023 boolean parameter_suffix_found = FALSE;
3025 /* skip all parameter definitions (handled by read_token_parameters()) */
3026 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
3028 int len_suffix = strlen(suffix_list[i].token);
3030 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
3031 parameter_suffix_found = TRUE;
3034 if (parameter_suffix_found)
3037 /* ---------- step 0: search for matching base prefix ---------- */
3040 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
3042 char *base_prefix = base_prefixes[i];
3043 int len_base_prefix = strlen(base_prefix);
3044 boolean ext1_suffix_found = FALSE;
3045 boolean ext2_suffix_found = FALSE;
3046 boolean ext3_suffix_found = FALSE;
3047 boolean exact_match = FALSE;
3048 int base_index = -1;
3049 int ext1_index = -1;
3050 int ext2_index = -1;
3051 int ext3_index = -1;
3053 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
3055 if (!base_prefix_found)
3060 if (start_pos + len_base_prefix == len_token) /* exact match */
3064 add_dynamic_file_list_entry(dynamic_file_list,
3065 num_dynamic_file_list_entries,
3068 num_suffix_list_entries,
3070 add_property_mapping(property_mapping,
3071 num_property_mapping_entries,
3072 base_index, -1, -1, -1,
3073 current_summarized_file_list_entry);
3077 /* ---------- step 1: search for matching first suffix ---------- */
3079 start_pos += len_base_prefix;
3080 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
3082 char *ext1_suffix = ext1_suffixes[j];
3083 int len_ext1_suffix = strlen(ext1_suffix);
3085 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
3087 if (!ext1_suffix_found)
3092 if (start_pos + len_ext1_suffix == len_token) /* exact match */
3096 add_dynamic_file_list_entry(dynamic_file_list,
3097 num_dynamic_file_list_entries,
3100 num_suffix_list_entries,
3102 add_property_mapping(property_mapping,
3103 num_property_mapping_entries,
3104 base_index, ext1_index, -1, -1,
3105 current_summarized_file_list_entry);
3109 start_pos += len_ext1_suffix;
3115 /* ---------- step 2: search for matching second suffix ---------- */
3117 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
3119 char *ext2_suffix = ext2_suffixes[k];
3120 int len_ext2_suffix = strlen(ext2_suffix);
3122 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
3124 if (!ext2_suffix_found)
3129 if (start_pos + len_ext2_suffix == len_token) /* exact match */
3133 add_dynamic_file_list_entry(dynamic_file_list,
3134 num_dynamic_file_list_entries,
3137 num_suffix_list_entries,
3139 add_property_mapping(property_mapping,
3140 num_property_mapping_entries,
3141 base_index, ext1_index, ext2_index, -1,
3142 current_summarized_file_list_entry);
3146 start_pos += len_ext2_suffix;
3152 /* ---------- step 3: search for matching third suffix ---------- */
3154 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
3156 char *ext3_suffix = ext3_suffixes[l];
3157 int len_ext3_suffix = strlen(ext3_suffix);
3159 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
3161 if (!ext3_suffix_found)
3166 if (start_pos + len_ext3_suffix == len_token) /* exact match */
3170 add_dynamic_file_list_entry(dynamic_file_list,
3171 num_dynamic_file_list_entries,
3174 num_suffix_list_entries,
3176 add_property_mapping(property_mapping,
3177 num_property_mapping_entries,
3178 base_index, ext1_index, ext2_index, ext3_index,
3179 current_summarized_file_list_entry);
3185 END_HASH_ITERATION(extra_file_hash, itr)
3187 if (artwork_info->num_dynamic_file_list_entries > 0)
3189 artwork_info->dynamic_artwork_list =
3190 checked_calloc(artwork_info->num_dynamic_file_list_entries *
3191 artwork_info->sizeof_artwork_list_entry);
3194 if (options.verbose && IS_PARENT_PROCESS())
3196 SetupFileList *setup_file_list, *list;
3197 boolean dynamic_tokens_found = FALSE;
3198 boolean unknown_tokens_found = FALSE;
3199 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3201 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3202 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3204 BEGIN_HASH_ITERATION(extra_file_hash, itr)
3206 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3207 dynamic_tokens_found = TRUE;
3209 unknown_tokens_found = TRUE;
3211 END_HASH_ITERATION(extra_file_hash, itr)
3213 if (options.debug && dynamic_tokens_found)
3215 Error(ERR_INFO_LINE, "-");
3216 Error(ERR_INFO, "dynamic token(s) found in config file:");
3217 Error(ERR_INFO, "- config file: '%s'", filename);
3219 for (list = setup_file_list; list != NULL; list = list->next)
3221 char *value = getHashEntry(extra_file_hash, list->token);
3223 if (value != NULL && strEqual(value, known_token_value))
3224 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3227 Error(ERR_INFO_LINE, "-");
3230 if (unknown_tokens_found)
3232 Error(ERR_INFO_LINE, "-");
3233 Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3234 Error(ERR_INFO, "- config file: '%s'", filename);
3236 for (list = setup_file_list; list != NULL; list = list->next)
3238 char *value = getHashEntry(extra_file_hash, list->token);
3240 if (value != NULL && !strEqual(value, known_token_value))
3241 Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3244 Error(ERR_INFO_LINE, "-");
3247 if (undefined_values_found)
3249 Error(ERR_INFO_LINE, "-");
3250 Error(ERR_INFO, "warning: undefined values found in config file:");
3251 Error(ERR_INFO, "- config file: '%s'", filename);
3253 for (list = setup_file_list; list != NULL; list = list->next)
3255 char *value = getHashEntry(empty_file_hash, list->token);
3258 Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3261 Error(ERR_INFO_LINE, "-");
3264 freeSetupFileList(setup_file_list);
3267 freeSetupFileHash(extra_file_hash);
3268 freeSetupFileHash(empty_file_hash);
3271 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3273 struct FileInfo *file_list = artwork_info->file_list;
3274 int num_file_list_entries = artwork_info->num_file_list_entries;
3275 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3276 char *filename_base = UNDEFINED_FILENAME, *filename_local;
3279 DrawInitText("Loading artwork config", 120, FC_GREEN);
3280 DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3282 /* always start with reliable default values */
3283 for (i = 0; i < num_file_list_entries; i++)
3285 setString(&file_list[i].filename, file_list[i].default_filename);
3287 for (j = 0; j < num_suffix_list_entries; j++)
3288 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3290 file_list[i].redefined = FALSE;
3291 file_list[i].fallback_to_default = FALSE;
3294 /* free previous dynamic artwork file array */
3295 if (artwork_info->dynamic_file_list != NULL)
3297 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3299 free(artwork_info->dynamic_file_list[i].token);
3300 free(artwork_info->dynamic_file_list[i].filename);
3301 free(artwork_info->dynamic_file_list[i].parameter);
3304 free(artwork_info->dynamic_file_list);
3305 artwork_info->dynamic_file_list = NULL;
3307 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3308 &artwork_info->num_dynamic_file_list_entries);
3311 /* free previous property mapping */
3312 if (artwork_info->property_mapping != NULL)
3314 free(artwork_info->property_mapping);
3316 artwork_info->property_mapping = NULL;
3317 artwork_info->num_property_mapping_entries = 0;
3320 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3322 /* first look for special artwork configured in level series config */
3323 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3325 if (fileExists(filename_base))
3326 LoadArtworkConfigFromFilename(artwork_info, filename_base);
3329 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3331 if (filename_local != NULL && !strEqual(filename_base, filename_local))
3332 LoadArtworkConfigFromFilename(artwork_info, filename_local);
3335 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3336 struct ListNodeInfo **listnode)
3340 char *filename = (*listnode)->source_filename;
3342 if (--(*listnode)->num_references <= 0)
3343 deleteNodeFromList(&artwork_info->content_list, filename,
3344 artwork_info->free_artwork);
3350 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3351 struct ListNodeInfo **listnode,
3352 struct FileInfo *file_list_entry)
3362 char *basename = file_list_entry->filename;
3363 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3365 if (filename == NULL)
3367 Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3369 basename = file_list_entry->default_filename;
3371 /* fail for cloned default artwork that has no default filename defined */
3372 if (file_list_entry->default_is_cloned &&
3373 strEqual(basename, UNDEFINED_FILENAME))
3375 int error_mode = ERR_WARN;
3377 /* we can get away without sounds and music, but not without graphics */
3378 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3379 error_mode = ERR_EXIT;
3381 Error(error_mode, "token '%s' was cloned and has no default filename",
3382 file_list_entry->token);
3387 /* dynamic artwork has no default filename / skip empty default artwork */
3388 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3391 file_list_entry->fallback_to_default = TRUE;
3393 Error(ERR_WARN, "trying default artwork file '%s'", basename);
3395 filename = getCustomArtworkFilename(basename, artwork_info->type);
3397 if (filename == NULL)
3399 int error_mode = ERR_WARN;
3401 /* we can get away without sounds and music, but not without graphics */
3402 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3403 error_mode = ERR_EXIT;
3405 Error(error_mode, "cannot find default artwork file '%s'", basename);
3411 /* check if the old and the new artwork file are the same */
3412 if (*listnode && strEqual((*listnode)->source_filename, filename))
3414 /* The old and new artwork are the same (have the same filename and path).
3415 This usually means that this artwork does not exist in this artwork set
3416 and a fallback to the existing artwork is done. */
3421 /* delete existing artwork file entry */
3422 deleteArtworkListEntry(artwork_info, listnode);
3424 /* check if the new artwork file already exists in the list of artwork */
3425 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3427 *listnode = (struct ListNodeInfo *)node->content;
3428 (*listnode)->num_references++;
3433 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3434 DrawInitText(basename, 150, FC_YELLOW);
3436 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3438 /* add new artwork file entry to the list of artwork files */
3439 (*listnode)->num_references = 1;
3440 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3445 int error_mode = ERR_WARN;
3447 /* we can get away without sounds and music, but not without graphics */
3448 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3449 error_mode = ERR_EXIT;
3451 Error(error_mode, "cannot load artwork file '%s'", basename);
3457 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3458 struct ListNodeInfo **listnode,
3459 struct FileInfo *file_list_entry)
3461 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3463 deleteArtworkListEntry(artwork_info, listnode);
3468 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3471 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3473 struct FileInfo *file_list = artwork_info->file_list;
3474 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3475 int num_file_list_entries = artwork_info->num_file_list_entries;
3476 int num_dynamic_file_list_entries =
3477 artwork_info->num_dynamic_file_list_entries;
3480 print_timestamp_init("ReloadCustomArtworkList");
3482 for (i = 0; i < num_file_list_entries; i++)
3483 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3486 for (i = 0; i < num_dynamic_file_list_entries; i++)
3487 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3488 &dynamic_file_list[i]);
3490 print_timestamp_done("ReloadCustomArtworkList");
3493 dumpList(artwork_info->content_list);
3497 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3498 struct ListNodeInfo ***list,
3499 int *num_list_entries)
3506 for (i = 0; i < *num_list_entries; i++)
3507 deleteArtworkListEntry(artwork_info, &(*list)[i]);
3511 *num_list_entries = 0;
3514 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3516 if (artwork_info == NULL)
3519 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3520 &artwork_info->num_file_list_entries);
3522 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3523 &artwork_info->num_dynamic_file_list_entries);
3527 /* ------------------------------------------------------------------------- */
3528 /* functions only needed for non-Unix (non-command-line) systems */
3529 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
3530 /* (now also added for Windows, to create files in user data directory) */
3531 /* ------------------------------------------------------------------------- */
3533 char *getLogFilename(char *basename)
3535 return getPath2(getUserGameDataDir(), basename);
3542 InitUserDataDirectory();
3544 for (i = 0; i < NUM_LOGS; i++)
3546 if ((program.log_file[i] = fopen(program.log_filename[i], MODE_WRITE))
3549 program.log_file[i] = program.log_file_default[i]; // reset to default
3551 Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3552 program.log_filename[i], strerror(errno));
3555 /* output should be unbuffered so it is not truncated in a crash */
3556 setbuf(program.log_file[i], NULL);
3560 void CloseLogFiles()
3564 for (i = 0; i < NUM_LOGS; i++)
3565 if (program.log_file[i] != program.log_file_default[i])
3566 fclose(program.log_file[i]);
3569 void DumpLogFile(int nr)
3571 FILE *log_file = fopen(program.log_filename[nr], MODE_READ);
3573 if (log_file == NULL)
3576 while (!feof(log_file))
3577 fputc(fgetc(log_file), stdout);
3582 void NotifyUserAboutErrorFile()
3584 #if defined(PLATFORM_WIN32)
3585 char *title_text = getStringCat2(program.program_title, " Error Message");
3586 char *error_text = getStringCat2("The program was aborted due to an error; "
3587 "for details, see the following error file:"
3589 program.log_filename[LOG_ERR_ID]);
3591 MessageBox(NULL, error_text, title_text, MB_OK);
3596 /* ------------------------------------------------------------------------- */
3597 /* the following is only for debugging purpose and normally not used */
3598 /* ------------------------------------------------------------------------- */
3602 #define DEBUG_PRINT_INIT_TIMESTAMPS FALSE
3603 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
3605 #define DEBUG_NUM_TIMESTAMPS 10
3606 #define DEBUG_TIME_IN_MICROSECONDS 0
3608 #if DEBUG_TIME_IN_MICROSECONDS
3609 static double Counter_Microseconds()
3611 static struct timeval base_time = { 0, 0 };
3612 struct timeval current_time;
3615 gettimeofday(¤t_time, NULL);
3617 /* reset base time in case of wrap-around */
3618 if (current_time.tv_sec < base_time.tv_sec)
3619 base_time = current_time;
3622 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
3623 ((double)(current_time.tv_usec - base_time.tv_usec));
3625 return counter; /* return microseconds since last init */
3629 char *debug_print_timestamp_get_padding(int padding_size)
3631 static char *padding = NULL;
3632 int max_padding_size = 100;
3634 if (padding == NULL)
3636 padding = checked_calloc(max_padding_size + 1);
3637 memset(padding, ' ', max_padding_size);
3640 return &padding[MAX(0, max_padding_size - padding_size)];
3643 void debug_print_timestamp(int counter_nr, char *message)
3645 int indent_size = 8;
3646 int padding_size = 40;
3647 float timestamp_interval;
3650 Error(ERR_EXIT, "debugging: invalid negative counter");
3651 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3652 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3654 #if DEBUG_TIME_IN_MICROSECONDS
3655 static double counter[DEBUG_NUM_TIMESTAMPS][2];
3658 counter[counter_nr][0] = Counter_Microseconds();
3660 static int counter[DEBUG_NUM_TIMESTAMPS][2];
3663 counter[counter_nr][0] = Counter();
3666 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3667 counter[counter_nr][1] = counter[counter_nr][0];
3670 Error(ERR_DEBUG, "%s%s%s %.3f %s",
3671 debug_print_timestamp_get_padding(counter_nr * indent_size),
3673 debug_print_timestamp_get_padding(padding_size - strlen(message)),
3674 timestamp_interval / 1000,
3678 void debug_print_parent_only(char *format, ...)
3680 if (!IS_PARENT_PROCESS())
3687 va_start(ap, format);
3688 vprintf(format, ap);
3697 void print_timestamp_ext(char *message, char *mode)
3699 #if DEBUG_PRINT_INIT_TIMESTAMPS
3700 static char *debug_message = NULL;
3701 static char *last_message = NULL;
3702 static int counter_nr = 0;
3703 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3705 checked_free(debug_message);
3706 debug_message = getStringCat3(mode, " ", message);
3708 if (strEqual(mode, "INIT"))
3710 debug_print_timestamp(counter_nr, NULL);
3712 if (counter_nr + 1 < max_depth)
3713 debug_print_timestamp(counter_nr, debug_message);
3717 debug_print_timestamp(counter_nr, NULL);
3719 else if (strEqual(mode, "DONE"))
3723 if (counter_nr + 1 < max_depth ||
3724 (counter_nr == 0 && max_depth == 1))
3726 last_message = message;
3728 if (counter_nr == 0 && max_depth == 1)
3730 checked_free(debug_message);
3731 debug_message = getStringCat3("TIME", " ", message);
3734 debug_print_timestamp(counter_nr, debug_message);
3737 else if (!strEqual(mode, "TIME") ||
3738 !strEqual(message, last_message))
3740 if (counter_nr < max_depth)
3741 debug_print_timestamp(counter_nr, debug_message);
3746 void print_timestamp_init(char *message)
3748 print_timestamp_ext(message, "INIT");
3751 void print_timestamp_time(char *message)
3753 print_timestamp_ext(message, "TIME");
3756 void print_timestamp_done(char *message)
3758 print_timestamp_ext(message, "DONE");