1 /***********************************************************
2 * Artsoft Retro-Game Library *
3 *----------------------------------------------------------*
4 * (c) 1994-2002 Artsoft Entertainment *
6 * Detmolder Strasse 189 *
9 * e-mail: info@artsoft.org *
10 *----------------------------------------------------------*
12 ***********************************************************/
16 #include <sys/types.h>
24 #if !defined(PLATFORM_WIN32)
26 #include <sys/param.h>
36 /* ------------------------------------------------------------------------- */
37 /* some generic helper functions */
38 /* ------------------------------------------------------------------------- */
40 void fprintf_line(FILE *stream, char *line_string, int line_length)
44 for (i=0; i<line_length; i++)
45 fprintf(stream, "%s", line_string);
47 fprintf(stream, "\n");
50 void printf_line(char *line_string, int line_length)
52 fprintf_line(stdout, line_string, line_length);
55 /* int2str() returns a number converted to a string;
56 the used memory is static, but will be overwritten by later calls,
57 so if you want to save the result, copy it to a private string buffer;
58 there can be 10 local calls of int2str() without buffering the result --
59 the 11th call will then destroy the result from the first call and so on.
62 char *int2str(int number, int size)
64 static char shift_array[10][40];
65 static int shift_counter = 0;
66 char *s = shift_array[shift_counter];
68 shift_counter = (shift_counter + 1) % 10;
75 sprintf(s, " %09d", number);
76 return &s[strlen(s) - size];
80 sprintf(s, "%d", number);
86 /* ------------------------------------------------------------------------- */
87 /* counter functions */
88 /* ------------------------------------------------------------------------- */
90 #if defined(PLATFORM_MSDOS)
91 volatile unsigned long counter = 0;
93 void increment_counter()
98 END_OF_FUNCTION(increment_counter);
102 /* maximal allowed length of a command line option */
103 #define MAX_OPTION_LEN 256
106 static unsigned long mainCounter(int mode)
108 static unsigned long base_ms = 0;
109 unsigned long current_ms;
110 unsigned long counter_ms;
112 current_ms = SDL_GetTicks();
114 /* reset base time in case of counter initializing or wrap-around */
115 if (mode == INIT_COUNTER || current_ms < base_ms)
116 base_ms = current_ms;
118 counter_ms = current_ms - base_ms;
120 return counter_ms; /* return milliseconds since last init */
123 #else /* !TARGET_SDL */
125 #if defined(PLATFORM_UNIX)
126 static unsigned long mainCounter(int mode)
128 static struct timeval base_time = { 0, 0 };
129 struct timeval current_time;
130 unsigned long counter_ms;
132 gettimeofday(¤t_time, NULL);
134 /* reset base time in case of counter initializing or wrap-around */
135 if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
136 base_time = current_time;
138 counter_ms = (current_time.tv_sec - base_time.tv_sec) * 1000
139 + (current_time.tv_usec - base_time.tv_usec) / 1000;
141 return counter_ms; /* return milliseconds since last init */
143 #endif /* PLATFORM_UNIX */
144 #endif /* !TARGET_SDL */
146 void InitCounter() /* set counter back to zero */
148 #if !defined(PLATFORM_MSDOS)
149 mainCounter(INIT_COUNTER);
151 LOCK_VARIABLE(counter);
152 LOCK_FUNCTION(increment_counter);
153 install_int_ex(increment_counter, BPS_TO_TIMER(100));
157 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
159 #if !defined(PLATFORM_MSDOS)
160 return mainCounter(READ_COUNTER);
162 return (counter * 10);
166 static void sleep_milliseconds(unsigned long milliseconds_delay)
168 boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
171 #if defined(PLATFORM_MSDOS)
172 /* don't use select() to perform waiting operations under DOS
173 environment; always use a busy loop for waiting instead */
174 do_busy_waiting = TRUE;
180 /* we want to wait only a few ms -- if we assume that we have a
181 kernel timer resolution of 10 ms, we would wait far to long;
182 therefore it's better to do a short interval of busy waiting
183 to get our sleeping time more accurate */
185 unsigned long base_counter = Counter(), actual_counter = Counter();
187 while (actual_counter < base_counter + milliseconds_delay &&
188 actual_counter >= base_counter)
189 actual_counter = Counter();
193 #if defined(TARGET_SDL)
194 SDL_Delay(milliseconds_delay);
195 #elif defined(TARGET_ALLEGRO)
196 rest(milliseconds_delay);
198 struct timeval delay;
200 delay.tv_sec = milliseconds_delay / 1000;
201 delay.tv_usec = 1000 * (milliseconds_delay % 1000);
203 if (select(0, NULL, NULL, NULL, &delay) != 0)
204 Error(ERR_WARN, "sleep_milliseconds(): select() failed");
209 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
211 sleep_milliseconds(delay);
214 boolean FrameReached(unsigned long *frame_counter_var,
215 unsigned long frame_delay)
217 unsigned long actual_frame_counter = FrameCounter;
219 if (actual_frame_counter >= *frame_counter_var &&
220 actual_frame_counter < *frame_counter_var + frame_delay)
223 *frame_counter_var = actual_frame_counter;
228 boolean DelayReached(unsigned long *counter_var,
231 unsigned long actual_counter = Counter();
233 if (actual_counter >= *counter_var &&
234 actual_counter < *counter_var + delay)
237 *counter_var = actual_counter;
242 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
244 unsigned long actual_counter;
248 actual_counter = Counter();
250 if (actual_counter >= *counter_var &&
251 actual_counter < *counter_var + delay)
252 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
257 *counter_var = actual_counter;
261 /* ------------------------------------------------------------------------- */
262 /* random generator functions */
263 /* ------------------------------------------------------------------------- */
266 unsigned int SimpleRND(unsigned int max)
268 return (random_linux_libc(RND_FREE) % max);
271 unsigned int InitSimpleRND(long seed)
273 if (seed == NEW_RANDOMIZE)
275 struct timeval current_time;
277 gettimeofday(¤t_time, NULL);
278 seed = (long)current_time.tv_usec;
281 srandom_linux_libc(RND_FREE, (unsigned int) seed);
283 return (unsigned int) seed;
286 unsigned int RND(unsigned int max)
288 return (random_linux_libc(RND_GAME) % max);
291 unsigned int InitRND(long seed)
293 if (seed == NEW_RANDOMIZE)
295 struct timeval current_time;
297 gettimeofday(¤t_time, NULL);
298 seed = (long)current_time.tv_usec;
301 srandom_linux_libc(RND_GAME, (unsigned int) seed);
303 return (unsigned int) seed;
307 unsigned int init_random_number(int nr, long seed)
309 if (seed == NEW_RANDOMIZE)
311 #if defined(TARGET_SDL)
312 seed = (long)SDL_GetTicks();
314 struct timeval current_time;
316 gettimeofday(¤t_time, NULL);
317 seed = (long)current_time.tv_usec;
321 srandom_linux_libc(nr, (unsigned int) seed);
323 return (unsigned int) seed;
326 unsigned int get_random_number(int nr, unsigned int max)
328 return (max > 0 ? random_linux_libc(nr) % max : 0);
332 /* ------------------------------------------------------------------------- */
333 /* system info functions */
334 /* ------------------------------------------------------------------------- */
336 static char *get_corrected_real_name(char *real_name)
338 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
339 char *from_ptr = real_name;
340 char *to_ptr = real_name_new;
342 if (strchr(real_name, 'ß') == NULL) /* name does not contain 'ß' */
344 strncpy(real_name_new, real_name, MAX_USERNAME_LEN);
345 real_name_new[MAX_USERNAME_LEN] = '\0';
347 return real_name_new;
350 /* the user's real name may contain a 'ß' character (german sharp s),
351 which has no equivalent in upper case letters (which our fonts use) */
352 while (*from_ptr && (long)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
354 if (*from_ptr != 'ß')
355 *to_ptr++ = *from_ptr++;
366 return real_name_new;
371 static char *login_name = NULL;
373 #if defined(PLATFORM_WIN32)
374 if (login_name == NULL)
376 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
377 login_name = checked_malloc(buffer_size);
379 if (GetUserName(login_name, &buffer_size) == 0)
380 strcpy(login_name, ANONYMOUS_NAME);
383 if (login_name == NULL)
387 if ((pwd = getpwuid(getuid())) == NULL)
388 login_name = ANONYMOUS_NAME;
390 login_name = getStringCopy(pwd->pw_name);
399 static char *real_name = NULL;
401 #if defined(PLATFORM_WIN32)
402 if (real_name == NULL)
404 static char buffer[MAX_USERNAME_LEN + 1];
405 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
407 if (GetUserName(buffer, &buffer_size) != 0)
408 real_name = get_corrected_real_name(buffer);
410 real_name = ANONYMOUS_NAME;
412 #elif defined(PLATFORM_UNIX)
413 if (real_name == NULL)
417 if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
418 real_name = get_corrected_real_name(pwd->pw_gecos);
420 real_name = ANONYMOUS_NAME;
423 real_name = ANONYMOUS_NAME;
431 static char *dir = NULL;
433 #if defined(PLATFORM_WIN32)
436 dir = checked_malloc(MAX_PATH + 1);
438 if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, dir)))
441 #elif defined(PLATFORM_UNIX)
444 if ((dir = getenv("HOME")) == NULL)
448 if ((pwd = getpwuid(getuid())) != NULL)
449 dir = getStringCopy(pwd->pw_dir);
462 /* ------------------------------------------------------------------------- */
463 /* various string functions */
464 /* ------------------------------------------------------------------------- */
466 char *getPath2(char *path1, char *path2)
468 char *complete_path = checked_malloc(strlen(path1) + 1 +
471 sprintf(complete_path, "%s/%s", path1, path2);
473 return complete_path;
476 char *getPath3(char *path1, char *path2, char *path3)
478 char *complete_path = checked_malloc(strlen(path1) + 1 +
482 sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
484 return complete_path;
487 char *getStringCat2(char *s1, char *s2)
489 char *complete_string = checked_malloc(strlen(s1) + strlen(s2) + 1);
491 sprintf(complete_string, "%s%s", s1, s2);
493 return complete_string;
496 char *getStringCopy(char *s)
503 s_copy = checked_malloc(strlen(s) + 1);
509 char *getStringToLower(char *s)
511 char *s_copy = checked_malloc(strlen(s) + 1);
512 char *s_ptr = s_copy;
515 *s_ptr++ = tolower(*s++);
521 void setString(char **old_value, char *new_value)
523 if (*old_value != NULL)
526 *old_value = getStringCopy(new_value);
530 /* ------------------------------------------------------------------------- */
531 /* command line option handling functions */
532 /* ------------------------------------------------------------------------- */
534 static void printUsage()
537 "Usage: %s [OPTION]... [HOSTNAME [PORT]]\n"
540 " -d, --display HOSTNAME[:SCREEN] specify X server display\n"
541 " -b, --basepath DIRECTORY alternative base DIRECTORY\n"
542 " -l, --level DIRECTORY alternative level DIRECTORY\n"
543 " -g, --graphics DIRECTORY alternative graphics DIRECTORY\n"
544 " -s, --sounds DIRECTORY alternative sounds DIRECTORY\n"
545 " -m, --music DIRECTORY alternative music DIRECTORY\n"
546 " -n, --network network multiplayer game\n"
547 " --serveronly only start network server\n"
548 " -v, --verbose verbose mode\n"
549 " --debug display debugging information\n"
550 " -e, --execute COMMAND execute batch COMMAND:\n"
552 "Valid commands for '--execute' option:\n"
553 " \"print graphicsinfo.conf\" print default graphics config\n"
554 " \"print soundsinfo.conf\" print default sounds config\n"
555 " \"print musicinfo.conf\" print default music config\n"
556 " \"dump level FILE\" dump level data from FILE\n"
557 " \"dump tape FILE\" dump tape data from FILE\n"
558 " \"autoplay LEVELDIR\" play level tapes for LEVELDIR\n"
560 program.command_basename);
563 void GetOptions(char *argv[])
565 char **options_left = &argv[1];
567 /* initialize global program options */
568 options.display_name = NULL;
569 options.server_host = NULL;
570 options.server_port = 0;
571 options.ro_base_directory = RO_BASE_PATH;
572 options.rw_base_directory = RW_BASE_PATH;
573 options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
574 options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
575 options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
576 options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
577 options.docs_directory = RO_BASE_PATH "/" DOCS_DIRECTORY;
578 options.execute_command = NULL;
579 options.serveronly = FALSE;
580 options.network = FALSE;
581 options.verbose = FALSE;
582 options.debug = FALSE;
584 #if !defined(PLATFORM_UNIX)
585 if (*options_left == NULL) /* no options given -- enable verbose mode */
586 options.verbose = TRUE;
589 while (*options_left)
591 char option_str[MAX_OPTION_LEN];
592 char *option = options_left[0];
593 char *next_option = options_left[1];
594 char *option_arg = NULL;
595 int option_len = strlen(option);
597 if (option_len >= MAX_OPTION_LEN)
598 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
600 strcpy(option_str, option); /* copy argument into buffer */
603 if (strcmp(option, "--") == 0) /* stop scanning arguments */
606 if (strncmp(option, "--", 2) == 0) /* treat '--' like '-' */
609 option_arg = strchr(option, '=');
610 if (option_arg == NULL) /* no '=' in option */
611 option_arg = next_option;
614 *option_arg++ = '\0'; /* cut argument from option */
615 if (*option_arg == '\0') /* no argument after '=' */
616 Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
619 option_len = strlen(option);
621 if (strcmp(option, "-") == 0)
622 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
623 else if (strncmp(option, "-help", option_len) == 0)
629 else if (strncmp(option, "-display", option_len) == 0)
631 if (option_arg == NULL)
632 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
634 options.display_name = option_arg;
635 if (option_arg == next_option)
638 else if (strncmp(option, "-basepath", option_len) == 0)
640 if (option_arg == NULL)
641 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
643 /* this should be extended to separate options for ro and rw data */
644 options.ro_base_directory = option_arg;
645 options.rw_base_directory = option_arg;
646 if (option_arg == next_option)
649 /* adjust path for level directory accordingly */
650 options.level_directory =
651 getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
653 else if (strncmp(option, "-levels", option_len) == 0)
655 if (option_arg == NULL)
656 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
658 options.level_directory = option_arg;
659 if (option_arg == next_option)
662 else if (strncmp(option, "-graphics", option_len) == 0)
664 if (option_arg == NULL)
665 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
667 options.graphics_directory = option_arg;
668 if (option_arg == next_option)
671 else if (strncmp(option, "-sounds", option_len) == 0)
673 if (option_arg == NULL)
674 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
676 options.sounds_directory = option_arg;
677 if (option_arg == next_option)
680 else if (strncmp(option, "-music", option_len) == 0)
682 if (option_arg == NULL)
683 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
685 options.music_directory = option_arg;
686 if (option_arg == next_option)
689 else if (strncmp(option, "-network", option_len) == 0)
691 options.network = TRUE;
693 else if (strncmp(option, "-serveronly", option_len) == 0)
695 options.serveronly = TRUE;
697 else if (strncmp(option, "-verbose", option_len) == 0)
699 options.verbose = TRUE;
701 else if (strncmp(option, "-debug", option_len) == 0)
703 options.debug = TRUE;
705 else if (strncmp(option, "-execute", option_len) == 0)
707 if (option_arg == NULL)
708 Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
710 options.execute_command = option_arg;
711 if (option_arg == next_option)
714 else if (*option == '-')
716 Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
718 else if (options.server_host == NULL)
720 options.server_host = *options_left;
722 else if (options.server_port == 0)
724 options.server_port = atoi(*options_left);
725 if (options.server_port < 1024)
726 Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
729 Error(ERR_EXIT_HELP, "too many arguments");
736 /* ------------------------------------------------------------------------- */
737 /* error handling functions */
738 /* ------------------------------------------------------------------------- */
740 /* used by SetError() and GetError() to store internal error messages */
741 static char internal_error[1024]; /* this is bad */
743 void SetError(char *format, ...)
747 va_start(ap, format);
748 vsprintf(internal_error, format, ap);
754 return internal_error;
757 void Error(int mode, char *format, ...)
759 static boolean last_line_was_separator = FALSE;
760 char *process_name = "";
761 FILE *error = stderr;
762 char *newline = "\n";
764 /* display warnings only when running in verbose mode */
765 if (mode & ERR_WARN && !options.verbose)
768 if (mode == ERR_RETURN_LINE)
770 if (!last_line_was_separator)
771 fprintf_line(error, format, 79);
773 last_line_was_separator = TRUE;
778 last_line_was_separator = FALSE;
780 #if defined(PLATFORM_MSDOS)
783 if ((error = openErrorFile()) == NULL)
785 printf("Cannot write to error output file!%s", newline);
786 program.exit_function(1);
790 if (mode & ERR_SOUND_SERVER)
791 process_name = " sound server";
792 else if (mode & ERR_NETWORK_SERVER)
793 process_name = " network server";
794 else if (mode & ERR_NETWORK_CLIENT)
795 process_name = " network client **";
801 fprintf(error, "%s%s: ", program.command_basename, process_name);
804 fprintf(error, "warning: ");
806 va_start(ap, format);
807 vfprintf(error, format, ap);
810 fprintf(error, "%s", newline);
814 fprintf(error, "%s: Try option '--help' for more information.%s",
815 program.command_basename, newline);
818 fprintf(error, "%s%s: aborting%s",
819 program.command_basename, process_name, newline);
826 if (mode & ERR_FROM_SERVER)
827 exit(1); /* child process: normal exit */
829 program.exit_function(1); /* main process: clean up stuff */
834 /* ------------------------------------------------------------------------- */
835 /* memory allocation functions */
836 /* ------------------------------------------------------------------------- */
838 void *checked_malloc(unsigned long size)
845 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
850 void *checked_calloc(unsigned long size)
854 ptr = calloc(1, size);
857 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
862 void *checked_realloc(void *ptr, unsigned long size)
864 ptr = realloc(ptr, size);
867 Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
873 /* ------------------------------------------------------------------------- */
874 /* various helper functions */
875 /* ------------------------------------------------------------------------- */
877 inline void swap_numbers(int *i1, int *i2)
885 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
897 short getFile16BitInteger(FILE *file, int byte_order)
899 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
900 return ((fgetc(file) << 8) |
902 else /* BYTE_ORDER_LITTLE_ENDIAN */
903 return ((fgetc(file) << 0) |
907 void putFile16BitInteger(FILE *file, short value, int byte_order)
909 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
911 fputc((value >> 8) & 0xff, file);
912 fputc((value >> 0) & 0xff, file);
914 else /* BYTE_ORDER_LITTLE_ENDIAN */
916 fputc((value >> 0) & 0xff, file);
917 fputc((value >> 8) & 0xff, file);
921 int getFile32BitInteger(FILE *file, int byte_order)
923 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
924 return ((fgetc(file) << 24) |
925 (fgetc(file) << 16) |
928 else /* BYTE_ORDER_LITTLE_ENDIAN */
929 return ((fgetc(file) << 0) |
931 (fgetc(file) << 16) |
932 (fgetc(file) << 24));
935 void putFile32BitInteger(FILE *file, int value, int byte_order)
937 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
939 fputc((value >> 24) & 0xff, file);
940 fputc((value >> 16) & 0xff, file);
941 fputc((value >> 8) & 0xff, file);
942 fputc((value >> 0) & 0xff, file);
944 else /* BYTE_ORDER_LITTLE_ENDIAN */
946 fputc((value >> 0) & 0xff, file);
947 fputc((value >> 8) & 0xff, file);
948 fputc((value >> 16) & 0xff, file);
949 fputc((value >> 24) & 0xff, file);
953 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
956 const int chunk_name_length = 4;
958 /* read chunk name */
959 fgets(chunk_name, chunk_name_length + 1, file);
961 if (chunk_size != NULL)
963 /* read chunk size */
964 *chunk_size = getFile32BitInteger(file, byte_order);
967 return (feof(file) || ferror(file) ? FALSE : TRUE);
970 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
973 /* write chunk name */
974 fputs(chunk_name, file);
978 /* write chunk size */
979 putFile32BitInteger(file, chunk_size, byte_order);
983 int getFileVersion(FILE *file)
985 int version_major, version_minor, version_patch, version_release;
987 version_major = fgetc(file);
988 version_minor = fgetc(file);
989 version_patch = fgetc(file);
990 version_release = fgetc(file);
992 return RELEASE_IDENT(version_major, version_minor, version_patch,
996 void putFileVersion(FILE *file, int version)
998 int version_major = VERSION_MAJOR(version);
999 int version_minor = VERSION_MINOR(version);
1000 int version_patch = VERSION_PATCH(version);
1001 int version_release = VERSION_RELEASE(version);
1003 fputc(version_major, file);
1004 fputc(version_minor, file);
1005 fputc(version_patch, file);
1006 fputc(version_release, file);
1009 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
1011 while (bytes-- && !feof(file))
1015 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
1022 /* ------------------------------------------------------------------------- */
1023 /* functions to translate key identifiers between different format */
1024 /* ------------------------------------------------------------------------- */
1026 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
1027 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
1028 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
1029 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
1031 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1040 /* normal cursor keys */
1041 { KSYM_Left, "XK_Left", "cursor left" },
1042 { KSYM_Right, "XK_Right", "cursor right" },
1043 { KSYM_Up, "XK_Up", "cursor up" },
1044 { KSYM_Down, "XK_Down", "cursor down" },
1046 /* keypad cursor keys */
1048 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
1049 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
1050 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
1051 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
1054 /* other keypad keys */
1055 #ifdef KSYM_KP_Enter
1056 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
1057 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
1058 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
1059 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
1060 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
1061 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
1065 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
1066 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
1067 { KSYM_Control_L, "XK_Control_L", "left control" },
1068 { KSYM_Control_R, "XK_Control_R", "right control" },
1069 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
1070 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
1071 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
1072 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
1073 { KSYM_Super_L, "XK_Super_L", "left super" }, /* Win-L */
1074 { KSYM_Super_R, "XK_Super_R", "right super" }, /* Win-R */
1075 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, /* Alt-R */
1076 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, /* Ctrl-R */
1078 /* some special keys */
1079 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
1080 { KSYM_Delete, "XK_Delete", "delete" },
1081 { KSYM_Insert, "XK_Insert", "insert" },
1082 { KSYM_Tab, "XK_Tab", "tab" },
1083 { KSYM_Home, "XK_Home", "home" },
1084 { KSYM_End, "XK_End", "end" },
1085 { KSYM_Page_Up, "XK_Page_Up", "page up" },
1086 { KSYM_Page_Down, "XK_Page_Down", "page down" },
1087 { KSYM_Menu, "XK_Menu", "menu" }, /* Win-Menu */
1089 /* ASCII 0x20 to 0x40 keys (except numbers) */
1090 { KSYM_space, "XK_space", "space" },
1091 { KSYM_exclam, "XK_exclam", "!" },
1092 { KSYM_quotedbl, "XK_quotedbl", "\"" },
1093 { KSYM_numbersign, "XK_numbersign", "#" },
1094 { KSYM_dollar, "XK_dollar", "$" },
1095 { KSYM_percent, "XK_percent", "%" },
1096 { KSYM_ampersand, "XK_ampersand", "&" },
1097 { KSYM_apostrophe, "XK_apostrophe", "'" },
1098 { KSYM_parenleft, "XK_parenleft", "(" },
1099 { KSYM_parenright, "XK_parenright", ")" },
1100 { KSYM_asterisk, "XK_asterisk", "*" },
1101 { KSYM_plus, "XK_plus", "+" },
1102 { KSYM_comma, "XK_comma", "," },
1103 { KSYM_minus, "XK_minus", "-" },
1104 { KSYM_period, "XK_period", "." },
1105 { KSYM_slash, "XK_slash", "/" },
1106 { KSYM_colon, "XK_colon", ":" },
1107 { KSYM_semicolon, "XK_semicolon", ";" },
1108 { KSYM_less, "XK_less", "<" },
1109 { KSYM_equal, "XK_equal", "=" },
1110 { KSYM_greater, "XK_greater", ">" },
1111 { KSYM_question, "XK_question", "?" },
1112 { KSYM_at, "XK_at", "@" },
1114 /* more ASCII keys */
1115 { KSYM_bracketleft, "XK_bracketleft", "[" },
1116 { KSYM_backslash, "XK_backslash", "backslash" },
1117 { KSYM_bracketright,"XK_bracketright", "]" },
1118 { KSYM_asciicircum, "XK_asciicircum", "circumflex" },
1119 { KSYM_underscore, "XK_underscore", "_" },
1120 { KSYM_grave, "XK_grave", "grave" },
1121 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
1122 { KSYM_braceleft, "XK_braceleft", "brace left" },
1123 { KSYM_bar, "XK_bar", "bar" },
1124 { KSYM_braceright, "XK_braceright", "brace right" },
1125 { KSYM_asciitilde, "XK_asciitilde", "ascii tilde" },
1127 /* special (non-ASCII) keys */
1128 { KSYM_Adiaeresis, "XK_Adiaeresis", "Ä" },
1129 { KSYM_Odiaeresis, "XK_Odiaeresis", "Ö" },
1130 { KSYM_Udiaeresis, "XK_Udiaeresis", "Ü" },
1131 { KSYM_adiaeresis, "XK_adiaeresis", "ä" },
1132 { KSYM_odiaeresis, "XK_odiaeresis", "ö" },
1133 { KSYM_udiaeresis, "XK_udiaeresis", "ü" },
1134 { KSYM_ssharp, "XK_ssharp", "sharp s" },
1136 /* end-of-array identifier */
1142 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1144 static char name_buffer[30];
1147 if (key >= KSYM_A && key <= KSYM_Z)
1148 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1149 else if (key >= KSYM_a && key <= KSYM_z)
1150 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1151 else if (key >= KSYM_0 && key <= KSYM_9)
1152 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1153 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1154 sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1155 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1156 sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1157 else if (key == KSYM_UNDEFINED)
1158 strcpy(name_buffer, "(undefined)");
1165 if (key == translate_key[i].key)
1167 strcpy(name_buffer, translate_key[i].name);
1171 while (translate_key[++i].name);
1173 if (!translate_key[i].name)
1174 strcpy(name_buffer, "(unknown)");
1177 *name = name_buffer;
1179 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1181 static char name_buffer[30];
1184 if (key >= KSYM_A && key <= KSYM_Z)
1185 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1186 else if (key >= KSYM_a && key <= KSYM_z)
1187 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1188 else if (key >= KSYM_0 && key <= KSYM_9)
1189 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1190 else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1191 sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1192 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1193 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1194 else if (key == KSYM_UNDEFINED)
1195 strcpy(name_buffer, "[undefined]");
1202 if (key == translate_key[i].key)
1204 strcpy(name_buffer, translate_key[i].x11name);
1208 while (translate_key[++i].x11name);
1210 if (!translate_key[i].x11name)
1211 sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1214 *x11name = name_buffer;
1216 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1218 Key key = KSYM_UNDEFINED;
1223 if (strcmp(translate_key[i].name, *name) == 0)
1225 key = translate_key[i].key;
1229 while (translate_key[++i].x11name);
1231 if (key == KSYM_UNDEFINED)
1232 Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1236 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1238 Key key = KSYM_UNDEFINED;
1239 char *name_ptr = *x11name;
1241 if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1243 char c = name_ptr[3];
1245 if (c >= 'A' && c <= 'Z')
1246 key = KSYM_A + (Key)(c - 'A');
1247 else if (c >= 'a' && c <= 'z')
1248 key = KSYM_a + (Key)(c - 'a');
1249 else if (c >= '0' && c <= '9')
1250 key = KSYM_0 + (Key)(c - '0');
1252 else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1254 char c = name_ptr[6];
1256 if (c >= '0' && c <= '9')
1257 key = KSYM_0 + (Key)(c - '0');
1259 else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1261 char c1 = name_ptr[4];
1262 char c2 = name_ptr[5];
1265 if ((c1 >= '0' && c1 <= '9') &&
1266 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1267 d = atoi(&name_ptr[4]);
1269 if (d >= 1 && d <= KSYM_NUM_FKEYS)
1270 key = KSYM_F1 + (Key)(d - 1);
1272 else if (strncmp(name_ptr, "XK_", 3) == 0)
1278 if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1280 key = translate_key[i].key;
1284 while (translate_key[++i].x11name);
1286 else if (strncmp(name_ptr, "0x", 2) == 0)
1288 unsigned long value = 0;
1294 char c = *name_ptr++;
1297 if (c >= '0' && c <= '9')
1299 else if (c >= 'a' && c <= 'f')
1300 d = (int)(c - 'a' + 10);
1301 else if (c >= 'A' && c <= 'F')
1302 d = (int)(c - 'A' + 10);
1310 value = value * 16 + d;
1321 char *getKeyNameFromKey(Key key)
1325 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1329 char *getX11KeyNameFromKey(Key key)
1333 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1337 Key getKeyFromKeyName(char *name)
1341 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1345 Key getKeyFromX11KeyName(char *x11name)
1349 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1353 char getCharFromKey(Key key)
1355 char *keyname = getKeyNameFromKey(key);
1358 if (strlen(keyname) == 1)
1359 letter = keyname[0];
1360 else if (strcmp(keyname, "space") == 0)
1362 else if (strcmp(keyname, "circumflex") == 0)
1369 /* ------------------------------------------------------------------------- */
1370 /* functions to translate string identifiers to integer or boolean value */
1371 /* ------------------------------------------------------------------------- */
1373 int get_integer_from_string(char *s)
1375 static char *number_text[][3] =
1377 { "0", "zero", "null", },
1378 { "1", "one", "first" },
1379 { "2", "two", "second" },
1380 { "3", "three", "third" },
1381 { "4", "four", "fourth" },
1382 { "5", "five", "fifth" },
1383 { "6", "six", "sixth" },
1384 { "7", "seven", "seventh" },
1385 { "8", "eight", "eighth" },
1386 { "9", "nine", "ninth" },
1387 { "10", "ten", "tenth" },
1388 { "11", "eleven", "eleventh" },
1389 { "12", "twelve", "twelfth" },
1393 char *s_lower = getStringToLower(s);
1396 for (i=0; i<13; i++)
1398 if (strcmp(s_lower, number_text[i][j]) == 0)
1409 boolean get_boolean_from_string(char *s)
1411 char *s_lower = getStringToLower(s);
1412 boolean result = FALSE;
1414 if (strcmp(s_lower, "true") == 0 ||
1415 strcmp(s_lower, "yes") == 0 ||
1416 strcmp(s_lower, "on") == 0 ||
1417 get_integer_from_string(s) == 1)
1426 /* ------------------------------------------------------------------------- */
1427 /* functions for generic lists */
1428 /* ------------------------------------------------------------------------- */
1430 ListNode *newListNode()
1432 return checked_calloc(sizeof(ListNode));
1435 void addNodeToList(ListNode **node_first, char *key, void *content)
1437 ListNode *node_new = newListNode();
1440 printf("LIST: adding node with key '%s'\n", key);
1443 node_new->key = getStringCopy(key);
1444 node_new->content = content;
1445 node_new->next = *node_first;
1446 *node_first = node_new;
1449 void deleteNodeFromList(ListNode **node_first, char *key,
1450 void (*destructor_function)(void *))
1452 if (node_first == NULL || *node_first == NULL)
1456 printf("[CHECKING LIST KEY '%s' == '%s']\n",
1457 (*node_first)->key, key);
1460 if (strcmp((*node_first)->key, key) == 0)
1463 printf("[DELETING LIST ENTRY]\n");
1466 free((*node_first)->key);
1467 if (destructor_function)
1468 destructor_function((*node_first)->content);
1469 *node_first = (*node_first)->next;
1472 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1475 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1477 if (node_first == NULL)
1480 if (strcmp(node_first->key, key) == 0)
1483 return getNodeFromKey(node_first->next, key);
1486 int getNumNodes(ListNode *node_first)
1488 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1491 void dumpList(ListNode *node_first)
1493 ListNode *node = node_first;
1497 printf("['%s' (%d)]\n", node->key,
1498 ((struct ListNodeInfo *)node->content)->num_references);
1502 printf("[%d nodes]\n", getNumNodes(node_first));
1506 /* ------------------------------------------------------------------------- */
1507 /* functions for checking files and filenames */
1508 /* ------------------------------------------------------------------------- */
1510 boolean fileExists(char *filename)
1513 printf("checking file '%s'\n", filename);
1516 return (access(filename, F_OK) == 0);
1519 boolean FileIsGraphic(char *filename)
1521 if (strlen(filename) > 4 &&
1522 strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1528 boolean FileIsSound(char *basename)
1530 if (strlen(basename) > 4 &&
1531 strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1537 boolean FileIsMusic(char *basename)
1539 /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1541 if (FileIsSound(basename))
1544 #if defined(TARGET_SDL)
1545 if (strlen(basename) > 4 &&
1546 (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1547 strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1548 strncmp(basename, "mod.", 4) == 0 ||
1549 strncmp(basename, "MOD.", 4) == 0))
1556 boolean FileIsArtworkType(char *basename, int type)
1558 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1559 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1560 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1566 /* ------------------------------------------------------------------------- */
1567 /* functions for loading artwork configuration information */
1568 /* ------------------------------------------------------------------------- */
1570 /* This function checks if a string <s> of the format "string1, string2, ..."
1571 exactly contains a string <s_contained>. */
1573 static boolean string_has_parameter(char *s, char *s_contained)
1577 if (s == NULL || s_contained == NULL)
1580 if (strlen(s_contained) > strlen(s))
1583 if (strncmp(s, s_contained, strlen(s_contained)) == 0)
1585 char next_char = s[strlen(s_contained)];
1587 /* check if next character is delimiter or whitespace */
1588 return (next_char == ',' || next_char == '\0' ||
1589 next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
1592 /* check if string contains another parameter string after a comma */
1593 substring = strchr(s, ',');
1594 if (substring == NULL) /* string does not contain a comma */
1597 /* advance string pointer to next character after the comma */
1600 /* skip potential whitespaces after the comma */
1601 while (*substring == ' ' || *substring == '\t')
1604 return string_has_parameter(substring, s_contained);
1607 int get_parameter_value(char *token, char *value_raw, int type)
1609 char *value = getStringToLower(value_raw);
1610 int result = 0; /* probably a save default value */
1612 if (strcmp(token, ".direction") == 0)
1614 result = (strcmp(value, "left") == 0 ? MV_LEFT :
1615 strcmp(value, "right") == 0 ? MV_RIGHT :
1616 strcmp(value, "up") == 0 ? MV_UP :
1617 strcmp(value, "down") == 0 ? MV_DOWN : MV_NO_MOVING);
1619 else if (strcmp(token, ".anim_mode") == 0)
1621 result = (string_has_parameter(value, "loop") ? ANIM_LOOP :
1622 string_has_parameter(value, "linear") ? ANIM_LINEAR :
1623 string_has_parameter(value, "pingpong") ? ANIM_PINGPONG :
1624 string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
1625 string_has_parameter(value, "random") ? ANIM_RANDOM :
1626 string_has_parameter(value, "none") ? ANIM_NONE :
1629 if (string_has_parameter(value, "reverse"))
1630 result |= ANIM_REVERSE;
1632 else /* generic parameter of type integer or boolean */
1634 result = (strcmp(value, ARG_UNDEFINED) == 0 ? ARG_UNDEFINED_VALUE :
1635 type == TYPE_INTEGER ? get_integer_from_string(value) :
1636 type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
1637 ARG_UNDEFINED_VALUE);
1645 static void FreeCustomArtworkList(struct ArtworkListInfo *,
1646 struct ListNodeInfo ***, int *);
1648 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
1649 struct ConfigInfo *suffix_list,
1650 char **ignore_tokens,
1651 int num_file_list_entries)
1653 struct FileInfo *file_list;
1654 int num_file_list_entries_found = 0;
1655 int num_suffix_list_entries = 0;
1659 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
1661 for (i=0; suffix_list[i].token != NULL; i++)
1662 num_suffix_list_entries++;
1664 /* always start with reliable default values */
1665 for (i=0; i<num_file_list_entries; i++)
1667 file_list[i].token = NULL;
1669 file_list[i].default_filename = NULL;
1670 file_list[i].filename = NULL;
1672 if (num_suffix_list_entries > 0)
1674 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1676 file_list[i].default_parameter = checked_calloc(parameter_array_size);
1677 file_list[i].parameter = checked_calloc(parameter_array_size);
1679 for (j=0; j<num_suffix_list_entries; j++)
1681 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
1682 setString(&file_list[i].parameter[j], suffix_list[j].value);
1688 for (i=0; config_list[i].token != NULL; i++)
1690 int len_config_token = strlen(config_list[i].token);
1691 int len_config_value = strlen(config_list[i].value);
1692 boolean is_file_entry = TRUE;
1694 for (j=0; suffix_list[j].token != NULL; j++)
1696 int len_suffix = strlen(suffix_list[j].token);
1698 if (len_suffix < len_config_token &&
1699 strcmp(&config_list[i].token[len_config_token - len_suffix],
1700 suffix_list[j].token) == 0)
1702 setString(&file_list[list_pos].default_parameter[j],
1703 config_list[i].value);
1705 is_file_entry = FALSE;
1710 /* the following tokens are no file definitions, but other config tokens */
1711 for (j=0; ignore_tokens[j] != NULL; j++)
1712 if (strcmp(config_list[i].token, ignore_tokens[j]) == 0)
1713 is_file_entry = FALSE;
1720 if (list_pos >= num_file_list_entries)
1723 /* simple sanity check if this is really a file definition */
1724 if (strcmp(&config_list[i].value[len_config_value - 4], ".pcx") != 0 &&
1725 strcmp(&config_list[i].value[len_config_value - 4], ".wav") != 0 &&
1726 strcmp(config_list[i].value, UNDEFINED_FILENAME) != 0)
1728 Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
1729 config_list[i].token, config_list[i].value);
1730 Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
1733 file_list[list_pos].token = config_list[i].token;
1734 file_list[list_pos].default_filename = config_list[i].value;
1738 num_file_list_entries_found = list_pos + 1;
1739 if (num_file_list_entries_found != num_file_list_entries)
1741 Error(ERR_RETURN_LINE, "-");
1742 Error(ERR_RETURN, "inconsistant config list information:");
1743 Error(ERR_RETURN, "- should be: %d (according to 'src/conf_gfx.h')",
1744 num_file_list_entries);
1745 Error(ERR_RETURN, "- found to be: %d (according to 'src/conf_gfx.c')",
1746 num_file_list_entries_found);
1747 Error(ERR_EXIT, "please fix");
1753 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
1755 int len_token = strlen(token);
1756 int len_suffix = strlen(suffix);
1759 if (IS_PARENT_PROCESS())
1760 printf(":::::::::: check '%s' for '%s' ::::::::::\n", token, suffix);
1763 if (start_pos < 0) /* compare suffix from end of string */
1764 start_pos += len_token;
1766 if (start_pos < 0 || start_pos + len_suffix > len_token)
1769 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
1772 if (token[start_pos + len_suffix] == '\0')
1775 if (token[start_pos + len_suffix] == '.')
1781 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN]"
1783 static void read_token_parameters(SetupFileHash *setup_file_hash,
1784 struct ConfigInfo *suffix_list,
1785 struct FileInfo *file_list_entry)
1787 /* check for config token that is the base token without any suffixes */
1788 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
1789 char *known_token_value = KNOWN_TOKEN_VALUE;
1792 if (filename != NULL)
1794 setString(&file_list_entry->filename, filename);
1796 /* when file definition found, set all parameters to default values */
1797 for (i=0; suffix_list[i].token != NULL; i++)
1798 setString(&file_list_entry->parameter[i], suffix_list[i].value);
1800 file_list_entry->redefined = TRUE;
1802 /* mark config file token as well known from default config */
1803 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
1808 if (strcmp(file_list_entry->filename,
1809 file_list_entry->default_filename) != 0)
1810 printf("___ resetting '%s' to default\n", file_list_entry->token);
1812 setString(&file_list_entry->filename, file_list_entry->default_filename);
1816 /* check for config tokens that can be build by base token and suffixes */
1817 for (i=0; suffix_list[i].token != NULL; i++)
1819 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
1820 char *value = getHashEntry(setup_file_hash, token);
1824 setString(&file_list_entry->parameter[i], value);
1826 /* mark config file token as well known from default config */
1827 setHashEntry(setup_file_hash, token, known_token_value);
1834 static void add_dynamic_file_list_entry(struct FileInfo **list,
1835 int *num_list_entries,
1836 SetupFileHash *extra_file_hash,
1837 struct ConfigInfo *suffix_list,
1838 int num_suffix_list_entries,
1841 struct FileInfo *new_list_entry;
1842 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1845 if (IS_PARENT_PROCESS())
1846 printf("===> found dynamic definition '%s'\n", token);
1849 (*num_list_entries)++;
1850 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
1851 new_list_entry = &(*list)[*num_list_entries - 1];
1853 new_list_entry->token = getStringCopy(token);
1854 new_list_entry->filename = NULL;
1855 new_list_entry->parameter = checked_calloc(parameter_array_size);
1857 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
1860 static void add_property_mapping(struct PropertyMapping **list,
1861 int *num_list_entries,
1862 int base_index, int ext1_index,
1863 int ext2_index, int ext3_index,
1866 struct PropertyMapping *new_list_entry;
1868 (*num_list_entries)++;
1869 *list = checked_realloc(*list,
1870 *num_list_entries * sizeof(struct PropertyMapping));
1871 new_list_entry = &(*list)[*num_list_entries - 1];
1873 new_list_entry->base_index = base_index;
1874 new_list_entry->ext1_index = ext1_index;
1875 new_list_entry->ext2_index = ext2_index;
1876 new_list_entry->ext3_index = ext3_index;
1878 new_list_entry->artwork_index = artwork_index;
1881 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
1884 struct FileInfo *file_list = artwork_info->file_list;
1885 struct ConfigInfo *suffix_list = artwork_info->suffix_list;
1886 char **base_prefixes = artwork_info->base_prefixes;
1887 char **ext1_suffixes = artwork_info->ext1_suffixes;
1888 char **ext2_suffixes = artwork_info->ext2_suffixes;
1889 char **ext3_suffixes = artwork_info->ext3_suffixes;
1890 char **ignore_tokens = artwork_info->ignore_tokens;
1891 int num_file_list_entries = artwork_info->num_file_list_entries;
1892 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
1893 int num_base_prefixes = artwork_info->num_base_prefixes;
1894 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
1895 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
1896 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
1897 int num_ignore_tokens = artwork_info->num_ignore_tokens;
1898 SetupFileHash *setup_file_hash, *extra_file_hash;
1899 char *known_token_value = KNOWN_TOKEN_VALUE;
1902 if (filename == NULL)
1906 printf("::: LoadArtworkConfigFromFilename: '%s'\n", filename);
1909 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
1912 /* read parameters for all known config file tokens */
1913 for (i=0; i<num_file_list_entries; i++)
1914 read_token_parameters(setup_file_hash, suffix_list, &file_list[i]);
1916 /* set all tokens that can be ignored here to "known" keyword */
1917 for (i=0; i < num_ignore_tokens; i++)
1918 setHashEntry(setup_file_hash, ignore_tokens[i], known_token_value);
1920 /* copy all unknown config file tokens to extra config list */
1921 extra_file_hash = newSetupFileHash();
1922 BEGIN_HASH_ITERATION(setup_file_hash, itr)
1924 if (strcmp(HASH_ITERATION_VALUE(itr), known_token_value) != 0)
1925 setHashEntry(extra_file_hash,
1926 HASH_ITERATION_TOKEN(itr), HASH_ITERATION_VALUE(itr));
1928 END_HASH_ITERATION(setup_file_hash, itr)
1930 /* at this point, we do not need the config file hash anymore -- free it */
1931 freeSetupFileHash(setup_file_hash);
1933 /* now try to determine valid, dynamically defined config tokens */
1935 BEGIN_HASH_ITERATION(extra_file_hash, itr)
1937 struct FileInfo **dynamic_file_list =
1938 &artwork_info->dynamic_file_list;
1939 int *num_dynamic_file_list_entries =
1940 &artwork_info->num_dynamic_file_list_entries;
1941 struct PropertyMapping **property_mapping =
1942 &artwork_info->property_mapping;
1943 int *num_property_mapping_entries =
1944 &artwork_info->num_property_mapping_entries;
1945 int current_summarized_file_list_entry =
1946 artwork_info->num_file_list_entries +
1947 artwork_info->num_dynamic_file_list_entries;
1948 char *token = HASH_ITERATION_TOKEN(itr);
1949 int len_token = strlen(token);
1951 boolean base_prefix_found = FALSE;
1952 boolean parameter_suffix_found = FALSE;
1954 /* skip all parameter definitions (handled by read_token_parameters()) */
1955 for (i=0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
1957 int len_suffix = strlen(suffix_list[i].token);
1959 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
1960 parameter_suffix_found = TRUE;
1964 if (IS_PARENT_PROCESS())
1966 if (parameter_suffix_found)
1967 printf("---> skipping token '%s' (parameter token)\n", token);
1969 printf("---> examining token '%s': search prefix ...\n", token);
1973 if (parameter_suffix_found)
1976 /* ---------- step 0: search for matching base prefix ---------- */
1979 for (i=0; i<num_base_prefixes && !base_prefix_found; i++)
1981 char *base_prefix = base_prefixes[i];
1982 int len_base_prefix = strlen(base_prefix);
1983 boolean ext1_suffix_found = FALSE;
1984 boolean ext2_suffix_found = FALSE;
1985 boolean ext3_suffix_found = FALSE;
1986 boolean exact_match = FALSE;
1987 int base_index = -1;
1988 int ext1_index = -1;
1989 int ext2_index = -1;
1990 int ext3_index = -1;
1992 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
1994 if (!base_prefix_found)
1999 if (start_pos + len_base_prefix == len_token) /* exact match */
2003 add_dynamic_file_list_entry(dynamic_file_list,
2004 num_dynamic_file_list_entries,
2007 num_suffix_list_entries,
2009 add_property_mapping(property_mapping,
2010 num_property_mapping_entries,
2011 base_index, -1, -1, -1,
2012 current_summarized_file_list_entry);
2017 if (IS_PARENT_PROCESS())
2018 printf("---> examining token '%s': search 1st suffix ...\n", token);
2021 /* ---------- step 1: search for matching first suffix ---------- */
2023 start_pos += len_base_prefix;
2024 for (j=0; j<num_ext1_suffixes && !ext1_suffix_found; j++)
2026 char *ext1_suffix = ext1_suffixes[j];
2027 int len_ext1_suffix = strlen(ext1_suffix);
2029 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2031 if (!ext1_suffix_found)
2036 if (start_pos + len_ext1_suffix == len_token) /* exact match */
2040 add_dynamic_file_list_entry(dynamic_file_list,
2041 num_dynamic_file_list_entries,
2044 num_suffix_list_entries,
2046 add_property_mapping(property_mapping,
2047 num_property_mapping_entries,
2048 base_index, ext1_index, -1, -1,
2049 current_summarized_file_list_entry);
2053 start_pos += len_ext1_suffix;
2060 if (IS_PARENT_PROCESS())
2061 printf("---> examining token '%s': search 2nd suffix ...\n", token);
2064 /* ---------- step 2: search for matching second suffix ---------- */
2066 for (k=0; k<num_ext2_suffixes && !ext2_suffix_found; k++)
2068 char *ext2_suffix = ext2_suffixes[k];
2069 int len_ext2_suffix = strlen(ext2_suffix);
2071 ext2_suffix_found = token_suffix_match(token, ext2_suffix,start_pos);
2073 if (!ext2_suffix_found)
2078 if (start_pos + len_ext2_suffix == len_token) /* exact match */
2082 add_dynamic_file_list_entry(dynamic_file_list,
2083 num_dynamic_file_list_entries,
2086 num_suffix_list_entries,
2088 add_property_mapping(property_mapping,
2089 num_property_mapping_entries,
2090 base_index, ext1_index, ext2_index, -1,
2091 current_summarized_file_list_entry);
2095 start_pos += len_ext2_suffix;
2102 if (IS_PARENT_PROCESS())
2103 printf("---> examining token '%s': search 3rd suffix ...\n",token);
2106 /* ---------- step 3: search for matching third suffix ---------- */
2108 for (l=0; l<num_ext3_suffixes && !ext3_suffix_found; l++)
2110 char *ext3_suffix = ext3_suffixes[l];
2111 int len_ext3_suffix = strlen(ext3_suffix);
2113 ext3_suffix_found =token_suffix_match(token,ext3_suffix,start_pos);
2115 if (!ext3_suffix_found)
2120 if (start_pos + len_ext3_suffix == len_token) /* exact match */
2124 add_dynamic_file_list_entry(dynamic_file_list,
2125 num_dynamic_file_list_entries,
2128 num_suffix_list_entries,
2130 add_property_mapping(property_mapping,
2131 num_property_mapping_entries,
2132 base_index, ext1_index, ext2_index, ext3_index,
2133 current_summarized_file_list_entry);
2139 END_HASH_ITERATION(extra_file_hash, itr)
2141 if (artwork_info->num_dynamic_file_list_entries > 0)
2143 artwork_info->dynamic_artwork_list =
2144 checked_calloc(artwork_info->num_dynamic_file_list_entries *
2145 artwork_info->sizeof_artwork_list_entry);
2148 if (extra_file_hash != NULL && options.verbose && IS_PARENT_PROCESS())
2150 SetupFileList *setup_file_list, *list;
2151 boolean dynamic_tokens_found = FALSE;
2152 boolean unknown_tokens_found = FALSE;
2154 if ((setup_file_list = loadSetupFileList(filename)) == NULL)
2155 Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
2157 BEGIN_HASH_ITERATION(extra_file_hash, itr)
2159 if (strcmp(HASH_ITERATION_VALUE(itr), known_token_value) == 0)
2160 dynamic_tokens_found = TRUE;
2162 unknown_tokens_found = TRUE;
2164 END_HASH_ITERATION(extra_file_hash, itr)
2167 if (dynamic_tokens_found)
2169 Error(ERR_RETURN_LINE, "-");
2170 Error(ERR_RETURN, "dynamic token(s) found in config file:");
2171 Error(ERR_RETURN, "- config file: '%s'", filename);
2173 for (list = setup_file_list; list != NULL; list = list->next)
2175 char *value = getHashEntry(extra_file_hash, list->token);
2177 if (value != NULL && strcmp(value, known_token_value) == 0)
2178 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2181 Error(ERR_RETURN_LINE, "-");
2185 if (unknown_tokens_found)
2187 Error(ERR_RETURN_LINE, "-");
2188 Error(ERR_RETURN, "warning: unknown token(s) found in config file:");
2189 Error(ERR_RETURN, "- config file: '%s'", filename);
2191 for (list = setup_file_list; list != NULL; list = list->next)
2193 char *value = getHashEntry(extra_file_hash, list->token);
2195 if (value != NULL && strcmp(value, known_token_value) != 0)
2196 Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2199 Error(ERR_RETURN_LINE, "-");
2202 freeSetupFileList(setup_file_list);
2205 freeSetupFileHash(extra_file_hash);
2208 for (i=0; i<num_file_list_entries; i++)
2210 printf("'%s' ", file_list[i].token);
2211 if (file_list[i].filename)
2212 printf("-> '%s'\n", file_list[i].filename);
2214 printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
2219 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
2221 struct FileInfo *file_list = artwork_info->file_list;
2222 int num_file_list_entries = artwork_info->num_file_list_entries;
2223 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2224 char *filename_base = UNDEFINED_FILENAME, *filename_local;
2228 printf("GOT CUSTOM ARTWORK CONFIG FILE '%s'\n", filename);
2231 /* always start with reliable default values */
2232 for (i=0; i<num_file_list_entries; i++)
2234 setString(&file_list[i].filename, file_list[i].default_filename);
2236 for (j=0; j<num_suffix_list_entries; j++)
2237 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
2239 file_list[i].redefined = FALSE;
2242 /* free previous dynamic artwork file array */
2243 if (artwork_info->dynamic_file_list != NULL)
2245 for (i=0; i<artwork_info->num_dynamic_file_list_entries; i++)
2247 free(artwork_info->dynamic_file_list[i].token);
2248 free(artwork_info->dynamic_file_list[i].filename);
2249 free(artwork_info->dynamic_file_list[i].parameter);
2252 free(artwork_info->dynamic_file_list);
2253 artwork_info->dynamic_file_list = NULL;
2255 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2256 &artwork_info->num_dynamic_file_list_entries);
2259 /* free previous property mapping */
2260 if (artwork_info->property_mapping != NULL)
2262 free(artwork_info->property_mapping);
2264 artwork_info->property_mapping = NULL;
2265 artwork_info->num_property_mapping_entries = 0;
2268 if (!SETUP_OVERRIDE_ARTWORK(setup, artwork_info->type))
2270 /* first look for special artwork configured in level series config */
2271 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
2273 if (fileExists(filename_base))
2274 LoadArtworkConfigFromFilename(artwork_info, filename_base);
2277 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
2279 if (filename_local != NULL && strcmp(filename_base, filename_local) != 0)
2280 LoadArtworkConfigFromFilename(artwork_info, filename_local);
2283 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
2284 struct ListNodeInfo **listnode)
2288 char *filename = (*listnode)->source_filename;
2291 printf("[decrementing reference counter of artwork '%s']\n", filename);
2294 if (--(*listnode)->num_references <= 0)
2297 printf("[deleting artwork '%s']\n", filename);
2300 deleteNodeFromList(&artwork_info->content_list, filename,
2301 artwork_info->free_artwork);
2308 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
2309 struct ListNodeInfo **listnode,
2314 "Loading graphics:",
2320 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
2322 if (filename == NULL)
2324 int error_mode = ERR_WARN;
2327 /* we can get away without sounds and music, but not without graphics */
2328 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2329 error_mode = ERR_EXIT;
2332 Error(error_mode, "cannot find artwork file '%s'", basename);
2336 /* check if the old and the new artwork file are the same */
2337 if (*listnode && strcmp((*listnode)->source_filename, filename) == 0)
2339 /* The old and new artwork are the same (have the same filename and path).
2340 This usually means that this artwork does not exist in this artwork set
2341 and a fallback to the existing artwork is done. */
2344 printf("[artwork '%s' already exists (same list entry)]\n", filename);
2350 /* delete existing artwork file entry */
2351 deleteArtworkListEntry(artwork_info, listnode);
2353 /* check if the new artwork file already exists in the list of artworks */
2354 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
2357 printf("[artwork '%s' already exists (other list entry)]\n", filename);
2360 *listnode = (struct ListNodeInfo *)node->content;
2361 (*listnode)->num_references++;
2367 printf("::: %s: '%s'\n", init_text[artwork_info->type], basename);
2370 DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
2371 DrawInitText(basename, 150, FC_YELLOW);
2373 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
2376 printf("[adding new artwork '%s']\n", filename);
2379 (*listnode)->num_references = 1;
2380 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
2385 int error_mode = ERR_WARN;
2388 /* we can get away without sounds and music, but not without graphics */
2389 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2390 error_mode = ERR_EXIT;
2393 Error(error_mode, "cannot load artwork file '%s'", basename);
2398 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
2399 struct ListNodeInfo **listnode,
2403 printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
2406 if (strcmp(basename, UNDEFINED_FILENAME) == 0)
2408 deleteArtworkListEntry(artwork_info, listnode);
2412 replaceArtworkListEntry(artwork_info, listnode, basename);
2415 static void LoadArtworkToList(struct ArtworkListInfo *artwork_info,
2416 struct ListNodeInfo **listnode,
2417 char *basename, int list_pos)
2420 if (artwork_info->artwork_list == NULL ||
2421 list_pos >= artwork_info->num_file_list_entries)
2426 printf("loading artwork '%s' ... [%d]\n",
2427 basename, getNumNodes(artwork_info->content_list));
2431 LoadCustomArtwork(artwork_info, listnode, basename);
2433 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[list_pos],
2438 printf("loading artwork '%s' done [%d]\n",
2439 basename, getNumNodes(artwork_info->content_list));
2443 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
2445 struct FileInfo *file_list = artwork_info->file_list;
2446 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
2447 int num_file_list_entries = artwork_info->num_file_list_entries;
2448 int num_dynamic_file_list_entries =
2449 artwork_info->num_dynamic_file_list_entries;
2453 printf("DEBUG: reloading %d static artwork files ...\n",
2454 num_file_list_entries);
2457 for(i=0; i<num_file_list_entries; i++)
2460 if (strcmp(file_list[i].token, "background") == 0)
2461 printf("::: '%s' -> '%s'\n", file_list[i].token, file_list[i].filename);
2464 LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2465 file_list[i].filename, i);
2468 if (artwork_info->artwork_list[i] == NULL &&
2469 strcmp(file_list[i].default_filename, file_list[i].filename) != 0)
2471 Error(ERR_WARN, "trying default artwork file '%s'",
2472 file_list[i].default_filename);
2474 LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2475 file_list[i].default_filename, i);
2481 printf("DEBUG: reloading %d dynamic artwork files ...\n",
2482 num_dynamic_file_list_entries);
2485 for(i=0; i<num_dynamic_file_list_entries; i++)
2486 LoadArtworkToList(artwork_info, &artwork_info->dynamic_artwork_list[i],
2487 dynamic_file_list[i].filename, i);
2490 dumpList(artwork_info->content_list);
2494 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
2495 struct ListNodeInfo ***list,
2496 int *num_list_entries)
2503 for(i=0; i<*num_list_entries; i++)
2504 deleteArtworkListEntry(artwork_info, &(*list)[i]);
2508 *num_list_entries = 0;
2511 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
2513 if (artwork_info == NULL)
2517 printf("%s: FREEING ARTWORK ...\n",
2518 IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2521 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
2522 &artwork_info->num_file_list_entries);
2524 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2525 &artwork_info->num_dynamic_file_list_entries);
2528 printf("%s: FREEING ARTWORK -- DONE\n",
2529 IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2534 /* ------------------------------------------------------------------------- */
2535 /* functions only needed for non-Unix (non-command-line) systems */
2536 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt") */
2537 /* ------------------------------------------------------------------------- */
2539 #if defined(PLATFORM_MSDOS)
2541 #define ERROR_FILENAME "stderr.txt"
2543 void initErrorFile()
2545 unlink(ERROR_FILENAME);
2548 FILE *openErrorFile()
2550 return fopen(ERROR_FILENAME, MODE_APPEND);
2553 void dumpErrorFile()
2555 FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
2557 if (error_file != NULL)
2559 while (!feof(error_file))
2560 fputc(fgetc(error_file), stderr);
2568 /* ------------------------------------------------------------------------- */
2569 /* the following is only for debugging purpose and normally not used */
2570 /* ------------------------------------------------------------------------- */
2572 #define DEBUG_NUM_TIMESTAMPS 3
2574 void debug_print_timestamp(int counter_nr, char *message)
2576 static long counter[DEBUG_NUM_TIMESTAMPS][2];
2578 if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
2579 Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
2581 counter[counter_nr][0] = Counter();
2584 printf("%s %.2f seconds\n", message,
2585 (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
2587 counter[counter_nr][1] = Counter();
2590 void debug_print_parent_only(char *format, ...)
2592 if (!IS_PARENT_PROCESS())
2599 va_start(ap, format);
2600 vprintf(format, ap);