fixed bug with TAS snap keys sometimes moving the player (EM engine only)
[rocksndiamonds.git] / src / screens.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // screens.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "screens.h"
15 #include "events.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "editor.h"
19 #include "files.h"
20 #include "tape.h"
21 #include "anim.h"
22 #include "network.h"
23 #include "init.h"
24 #include "config.h"
25
26 /* screens on the info screen */
27 #define INFO_MODE_MAIN                  0
28 #define INFO_MODE_TITLE                 1
29 #define INFO_MODE_ELEMENTS              2
30 #define INFO_MODE_MUSIC                 3
31 #define INFO_MODE_CREDITS               4
32 #define INFO_MODE_PROGRAM               5
33 #define INFO_MODE_VERSION               6
34 #define INFO_MODE_LEVELSET              7
35
36 #define MAX_INFO_MODES                  8
37
38 /* screens on the setup screen */
39 /* (must match GFX_SPECIAL_ARG_SETUP_* values as defined in src/main.h) */
40 /* (should also match corresponding entries in src/conf_gfx.c) */
41 #define SETUP_MODE_MAIN                 0
42 #define SETUP_MODE_GAME                 1
43 #define SETUP_MODE_EDITOR               2
44 #define SETUP_MODE_GRAPHICS             3
45 #define SETUP_MODE_SOUND                4
46 #define SETUP_MODE_ARTWORK              5
47 #define SETUP_MODE_INPUT                6
48 #define SETUP_MODE_TOUCH                7
49 #define SETUP_MODE_SHORTCUTS            8
50 #define SETUP_MODE_SHORTCUTS_1          9
51 #define SETUP_MODE_SHORTCUTS_2          10
52 #define SETUP_MODE_SHORTCUTS_3          11
53 #define SETUP_MODE_SHORTCUTS_4          12
54 #define SETUP_MODE_SHORTCUTS_5          13
55
56 /* sub-screens on the setup screen (generic) */
57 #define SETUP_MODE_CHOOSE_ARTWORK       14
58 #define SETUP_MODE_CHOOSE_OTHER         15
59
60 /* sub-screens on the setup screen (specific) */
61 #define SETUP_MODE_CHOOSE_GAME_SPEED    16
62 #define SETUP_MODE_CHOOSE_SCROLL_DELAY  17
63 #define SETUP_MODE_CHOOSE_SNAPSHOT_MODE 18
64 #define SETUP_MODE_CHOOSE_WINDOW_SIZE   19
65 #define SETUP_MODE_CHOOSE_SCALING_TYPE  20
66 #define SETUP_MODE_CHOOSE_RENDERING     21
67 #define SETUP_MODE_CHOOSE_GRAPHICS      22
68 #define SETUP_MODE_CHOOSE_SOUNDS        23
69 #define SETUP_MODE_CHOOSE_MUSIC         24
70 #define SETUP_MODE_CHOOSE_VOLUME_SIMPLE 25
71 #define SETUP_MODE_CHOOSE_VOLUME_LOOPS  26
72 #define SETUP_MODE_CHOOSE_VOLUME_MUSIC  27
73 #define SETUP_MODE_CHOOSE_TOUCH_CONTROL 28
74 #define SETUP_MODE_CHOOSE_MOVE_DISTANCE 29
75 #define SETUP_MODE_CHOOSE_DROP_DISTANCE 30
76
77 #define MAX_SETUP_MODES                 31
78
79 #define MAX_MENU_MODES                  MAX(MAX_INFO_MODES, MAX_SETUP_MODES)
80
81 /* for input setup functions */
82 #define SETUPINPUT_SCREEN_POS_START     0
83 #define SETUPINPUT_SCREEN_POS_END       (SCR_FIELDY - 4)
84 #define SETUPINPUT_SCREEN_POS_EMPTY1    (SETUPINPUT_SCREEN_POS_START + 3)
85 #define SETUPINPUT_SCREEN_POS_EMPTY2    (SETUPINPUT_SCREEN_POS_END - 1)
86
87 /* for various menu stuff  */
88 #define MENU_SCREEN_START_XPOS          1
89 #define MENU_SCREEN_START_YPOS          2
90 #define MENU_SCREEN_VALUE_XPOS          (SCR_FIELDX - 3)
91 #define MENU_SCREEN_MAX_XPOS            (SCR_FIELDX - 1)
92 #define MENU_TITLE1_YPOS                8
93 #define MENU_TITLE2_YPOS                46
94 #define MENU_SCREEN_INFO_XSTART         16
95 #define MENU_SCREEN_INFO_YSTART1        100
96 #define MENU_SCREEN_INFO_YSTART2        128
97 #define MENU_SCREEN_INFO_YSTEP          (TILEY + 4)
98 #define MENU_SCREEN_INFO_YBOTTOM        (SYSIZE - 20)
99 #define MENU_SCREEN_INFO_YSIZE          (MENU_SCREEN_INFO_YBOTTOM -     \
100                                          MENU_SCREEN_INFO_YSTART2 -     \
101                                          TILEY / 2)
102 #define MAX_INFO_ELEMENTS_ON_SCREEN     128
103 #define STD_INFO_ELEMENTS_ON_SCREEN     (MENU_SCREEN_INFO_YSIZE /       \
104                                          MENU_SCREEN_INFO_YSTEP)
105 #define NUM_INFO_ELEMENTS_FROM_CONF     \
106   (menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] > 0 ?             \
107    menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] :                 \
108    MAX_MENU_ENTRIES_ON_SCREEN)
109 #define NUM_INFO_ELEMENTS_ON_SCREEN     MIN(MIN(STD_INFO_ELEMENTS_ON_SCREEN, \
110                                                 MAX_INFO_ELEMENTS_ON_SCREEN), \
111                                             NUM_INFO_ELEMENTS_FROM_CONF)
112 #define MAX_MENU_ENTRIES_ON_SCREEN      (SCR_FIELDY - MENU_SCREEN_START_YPOS)
113 #define MAX_MENU_TEXT_LENGTH_BIG        13
114 #define MAX_MENU_TEXT_LENGTH_MEDIUM     (MAX_MENU_TEXT_LENGTH_BIG * 2)
115
116 /* buttons and scrollbars identifiers */
117 #define SCREEN_CTRL_ID_PREV_LEVEL       0
118 #define SCREEN_CTRL_ID_NEXT_LEVEL       1
119 #define SCREEN_CTRL_ID_PREV_PLAYER      2
120 #define SCREEN_CTRL_ID_NEXT_PLAYER      3
121 #define SCREEN_CTRL_ID_SCROLL_UP        4
122 #define SCREEN_CTRL_ID_SCROLL_DOWN      5
123 #define SCREEN_CTRL_ID_SCROLL_VERTICAL  6
124
125 #define NUM_SCREEN_GADGETS              7
126
127 #define NUM_SCREEN_MENUBUTTONS          4
128 #define NUM_SCREEN_SCROLLBUTTONS        2
129 #define NUM_SCREEN_SCROLLBARS           1
130
131 #define SCREEN_MASK_MAIN                (1 << 0)
132 #define SCREEN_MASK_INPUT               (1 << 1)
133
134 /* graphic position and size values for buttons and scrollbars */
135 #define SC_MENUBUTTON_XSIZE             TILEX
136 #define SC_MENUBUTTON_YSIZE             TILEY
137
138 #define SC_SCROLLBUTTON_XSIZE           TILEX
139 #define SC_SCROLLBUTTON_YSIZE           TILEY
140
141 #define SC_SCROLLBAR_XPOS               (SXSIZE - SC_SCROLLBUTTON_XSIZE)
142
143 #define SC_SCROLL_VERTICAL_XSIZE        SC_SCROLLBUTTON_XSIZE
144 #define SC_SCROLL_VERTICAL_YSIZE        ((MAX_MENU_ENTRIES_ON_SCREEN - 2) * \
145                                          SC_SCROLLBUTTON_YSIZE)
146
147 #define SC_SCROLL_UP_XPOS               SC_SCROLLBAR_XPOS
148 #define SC_SCROLL_UP_YPOS               (2 * SC_SCROLLBUTTON_YSIZE)
149
150 #define SC_SCROLL_VERTICAL_XPOS         SC_SCROLLBAR_XPOS
151 #define SC_SCROLL_VERTICAL_YPOS         (SC_SCROLL_UP_YPOS + \
152                                          SC_SCROLLBUTTON_YSIZE)
153
154 #define SC_SCROLL_DOWN_XPOS             SC_SCROLLBAR_XPOS
155 #define SC_SCROLL_DOWN_YPOS             (SC_SCROLL_VERTICAL_YPOS + \
156                                          SC_SCROLL_VERTICAL_YSIZE)
157
158 #define SC_BORDER_SIZE                  14
159
160
161 /* forward declarations of internal functions */
162 static void HandleScreenGadgets(struct GadgetInfo *);
163 static void HandleSetupScreen_Generic(int, int, int, int, int);
164 static void HandleSetupScreen_Input(int, int, int, int, int);
165 static void CustomizeKeyboard(int);
166 static void ConfigureJoystick(int);
167 static void execSetupGame(void);
168 static void execSetupGraphics(void);
169 static void execSetupSound(void);
170 static void execSetupTouch(void);
171 static void execSetupArtwork(void);
172 static void HandleChooseTree(int, int, int, int, int, TreeInfo **);
173
174 static void DrawChooseLevelSet(void);
175 static void DrawChooseLevelNr(void);
176 static void DrawInfoScreen(void);
177 static void DrawSetupScreen(void);
178
179 static void DrawInfoScreen_NotAvailable(char *, char *);
180 static void DrawInfoScreen_HelpAnim(int, int, boolean);
181 static void DrawInfoScreen_HelpText(int, int, int, int);
182 static void HandleInfoScreen_Main(int, int, int, int, int);
183 static void HandleInfoScreen_TitleScreen(int);
184 static void HandleInfoScreen_Elements(int);
185 static void HandleInfoScreen_Music(int);
186 static void HandleInfoScreen_Credits(int);
187 static void HandleInfoScreen_Program(int);
188 static void HandleInfoScreen_Version(int);
189
190 static void MapScreenMenuGadgets(int);
191 static void MapScreenGadgets(int);
192 static void MapScreenTreeGadgets(TreeInfo *);
193
194 static struct GadgetInfo *screen_gadget[NUM_SCREEN_GADGETS];
195
196 static int info_mode = INFO_MODE_MAIN;
197 static int setup_mode = SETUP_MODE_MAIN;
198
199 static TreeInfo *window_sizes = NULL;
200 static TreeInfo *window_size_current = NULL;
201
202 static TreeInfo *scaling_types = NULL;
203 static TreeInfo *scaling_type_current = NULL;
204
205 static TreeInfo *rendering_modes = NULL;
206 static TreeInfo *rendering_mode_current = NULL;
207
208 static TreeInfo *scroll_delays = NULL;
209 static TreeInfo *scroll_delay_current = NULL;
210
211 static TreeInfo *snapshot_modes = NULL;
212 static TreeInfo *snapshot_mode_current = NULL;
213
214 static TreeInfo *game_speeds = NULL;
215 static TreeInfo *game_speed_current = NULL;
216
217 static TreeInfo *volumes_simple = NULL;
218 static TreeInfo *volume_simple_current = NULL;
219
220 static TreeInfo *volumes_loops = NULL;
221 static TreeInfo *volume_loops_current = NULL;
222
223 static TreeInfo *volumes_music = NULL;
224 static TreeInfo *volume_music_current = NULL;
225
226 static TreeInfo *touch_controls = NULL;
227 static TreeInfo *touch_control_current = NULL;
228
229 static TreeInfo *move_distances = NULL;
230 static TreeInfo *move_distance_current = NULL;
231
232 static TreeInfo *drop_distances = NULL;
233 static TreeInfo *drop_distance_current = NULL;
234
235 static TreeInfo *level_number = NULL;
236 static TreeInfo *level_number_current = NULL;
237
238 static struct
239 {
240   int value;
241   char *text;
242 } window_sizes_list[] =
243 {
244   {     50,     "50 %"                          },
245   {     80,     "80 %"                          },
246   {     90,     "90 %"                          },
247   {     100,    "100 % (Default)"               },
248   {     110,    "110 %"                         },
249   {     120,    "120 %"                         },
250   {     130,    "130 %"                         },
251   {     140,    "140 %"                         },
252   {     150,    "150 %"                         },
253   {     200,    "200 %"                         },
254   {     250,    "250 %"                         },
255   {     300,    "300 %"                         },
256
257   {     -1,     NULL                            },
258 };
259
260 static struct
261 {
262   char *value;
263   char *text;
264 } scaling_types_list[] =
265 {
266   {     SCALING_QUALITY_NEAREST, "None"         },
267   {     SCALING_QUALITY_LINEAR,  "Linear"       },
268   {     SCALING_QUALITY_BEST,    "Anisotropic"  },
269
270   {     NULL,                    NULL           },
271 };
272
273 static struct
274 {
275   char *value;
276   char *text;
277 } rendering_modes_list[] =
278 {
279   {     STR_SPECIAL_RENDERING_OFF,      "Off (May show artifacts, fast)" },
280   {     STR_SPECIAL_RENDERING_BITMAP,   "Bitmap/Texture mode (slower)"   },
281 #if DEBUG
282   // this mode may work under certain conditions, but does not work on Windows
283   {     STR_SPECIAL_RENDERING_TARGET,   "Target Texture mode (slower)"   },
284 #endif
285   {     STR_SPECIAL_RENDERING_DOUBLE,   "Double Texture mode (slower)"   },
286
287   {     NULL,                            NULL                            },
288 };
289
290 static struct
291 {
292   int value;
293   char *text;
294 } game_speeds_list[] =
295 {
296 #if 1
297   {     30,     "Very Slow"                     },
298   {     25,     "Slow"                          },
299   {     20,     "Normal"                        },
300   {     15,     "Fast"                          },
301   {     10,     "Very Fast"                     },
302 #else
303   {     1000,   "1/1s (Extremely Slow)"         },
304   {     500,    "1/2s"                          },
305   {     200,    "1/5s"                          },
306   {     100,    "1/10s"                         },
307   {     50,     "1/20s"                         },
308   {     29,     "1/35s (Original Supaplex)"     },
309   {     25,     "1/40s"                         },
310   {     20,     "1/50s (Normal Speed)"          },
311   {     14,     "1/70s (Maximum Supaplex)"      },
312   {     10,     "1/100s"                        },
313   {     5,      "1/200s"                        },
314   {     2,      "1/500s"                        },
315   {     1,      "1/1000s (Extremely Fast)"      },
316 #endif
317
318   {     -1,     NULL                            },
319 };
320
321 static struct
322 {
323   int value;
324   char *text;
325 } scroll_delays_list[] =
326 {
327   {     0,      "0 Tiles (No Scroll Delay)"     },
328   {     1,      "1 Tile"                        },
329   {     2,      "2 Tiles"                       },
330   {     3,      "3 Tiles (Default)"             },
331   {     4,      "4 Tiles"                       },
332   {     5,      "5 Tiles"                       },
333   {     6,      "6 Tiles"                       },
334   {     7,      "7 Tiles"                       },
335   {     8,      "8 Tiles (Maximum Scroll Delay)"},
336
337   {     -1,     NULL                            },
338 };
339
340 static struct
341 {
342   char *value;
343   char *text;
344 } snapshot_modes_list[] =
345 {
346   {     STR_SNAPSHOT_MODE_OFF,                  "Off"           },
347   {     STR_SNAPSHOT_MODE_EVERY_STEP,           "Every Step"    },
348   {     STR_SNAPSHOT_MODE_EVERY_MOVE,           "Every Move"    },
349   {     STR_SNAPSHOT_MODE_EVERY_COLLECT,        "Every Collect" },
350
351   {     NULL,                                   NULL            },
352 };
353
354 static struct
355 {
356   int value;
357   char *text;
358 } volumes_list[] =
359 {
360   {     0,      "0 %"                           },
361   {     1,      "1 %"                           },
362   {     2,      "2 %"                           },
363   {     5,      "5 %"                           },
364   {     10,     "10 %"                          },
365   {     20,     "20 %"                          },
366   {     30,     "30 %"                          },
367   {     40,     "40 %"                          },
368   {     50,     "50 %"                          },
369   {     60,     "60 %"                          },
370   {     70,     "70 %"                          },
371   {     80,     "80 %"                          },
372   {     90,     "90 %"                          },
373   {     100,    "100 %"                         },
374
375   {     -1,     NULL                            },
376 };
377
378 static struct
379 {
380   char *value;
381   char *text;
382 } touch_controls_list[] =
383 {
384   {     TOUCH_CONTROL_VIRTUAL_BUTTONS,  "Virtual Buttons"       },
385   {     TOUCH_CONTROL_WIPE_GESTURES,    "Wipe Gestures"         },
386   {     TOUCH_CONTROL_FOLLOW_FINGER,    "Follow Finger"         },
387
388   {     NULL,                           NULL                    },
389 };
390
391 static struct
392 {
393   int value;
394   char *text;
395 } distances_list[] =
396 {
397   {     1,      "1 %"                           },
398   {     2,      "2 %"                           },
399   {     3,      "3 %"                           },
400   {     4,      "4 %"                           },
401   {     5,      "5 %"                           },
402   {     10,     "10 %"                          },
403   {     15,     "15 %"                          },
404   {     20,     "20 %"                          },
405   {     25,     "25 %"                          },
406
407   {     -1,     NULL                            },
408 };
409
410 #define DRAW_MODE(s)            ((s) >= GAME_MODE_MAIN &&               \
411                                  (s) <= GAME_MODE_SETUP ? (s) :         \
412                                  (s) == GAME_MODE_PSEUDO_TYPENAME ?     \
413                                  GAME_MODE_MAIN : GAME_MODE_DEFAULT)
414
415 /* (there are no draw offset definitions needed for INFO_MODE_TITLE) */
416 #define DRAW_MODE_INFO(i)       ((i) >= INFO_MODE_ELEMENTS &&           \
417                                  (i) <= INFO_MODE_LEVELSET ? (i) :      \
418                                  INFO_MODE_MAIN)
419
420 #define DRAW_MODE_SETUP(i)      ((i) >= SETUP_MODE_MAIN &&              \
421                                  (i) <= SETUP_MODE_SHORTCUTS_5 ? (i) :  \
422                                  (i) >= SETUP_MODE_CHOOSE_GRAPHICS &&   \
423                                  (i) <= SETUP_MODE_CHOOSE_MUSIC ?       \
424                                  SETUP_MODE_CHOOSE_ARTWORK :            \
425                                  SETUP_MODE_CHOOSE_OTHER)
426
427 #define DRAW_XOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?  \
428                                  menu.draw_xoffset[GAME_MODE_INFO] :    \
429                                  menu.draw_xoffset_info[DRAW_MODE_INFO(i)])
430 #define DRAW_YOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?  \
431                                  menu.draw_yoffset[GAME_MODE_INFO] :    \
432                                  menu.draw_yoffset_info[DRAW_MODE_INFO(i)])
433
434 #define DRAW_XOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
435                                  menu.draw_xoffset[GAME_MODE_SETUP] :   \
436                                  menu.draw_xoffset_setup[DRAW_MODE_SETUP(i)])
437 #define DRAW_YOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
438                                  menu.draw_yoffset[GAME_MODE_SETUP] :   \
439                                  menu.draw_yoffset_setup[DRAW_MODE_SETUP(i)])
440
441 #define DRAW_XOFFSET(s)         ((s) == GAME_MODE_INFO ?                \
442                                  DRAW_XOFFSET_INFO(info_mode) :         \
443                                  (s) == GAME_MODE_SETUP ?               \
444                                  DRAW_XOFFSET_SETUP(setup_mode) :       \
445                                  menu.draw_xoffset[DRAW_MODE(s)])
446 #define DRAW_YOFFSET(s)         ((s) == GAME_MODE_INFO ?                \
447                                  DRAW_YOFFSET_INFO(info_mode) :         \
448                                  (s) == GAME_MODE_SETUP ?               \
449                                  DRAW_YOFFSET_SETUP(setup_mode) :       \
450                                  menu.draw_yoffset[DRAW_MODE(s)])
451
452 #define mSX                     (SX + DRAW_XOFFSET(game_status))
453 #define mSY                     (SY + DRAW_YOFFSET(game_status))
454
455 #define NUM_MENU_ENTRIES_ON_SCREEN (menu.list_size[game_status] > 2 ?   \
456                                     menu.list_size[game_status] :       \
457                                     MAX_MENU_ENTRIES_ON_SCREEN)
458
459 #define IN_VIS_MENU(x, y)       IN_FIELD(x, y, SCR_FIELDX,              \
460                                          NUM_MENU_ENTRIES_ON_SCREEN)
461
462
463 /* title display and control definitions */
464
465 #define MAX_NUM_TITLE_SCREENS   (2 * MAX_NUM_TITLE_IMAGES +             \
466                                  2 * MAX_NUM_TITLE_MESSAGES)
467
468 #define NO_DIRECT_LEVEL_SELECT  (-1)
469
470
471 static int num_title_screens = 0;
472
473 struct TitleControlInfo
474 {
475   boolean is_image;
476   boolean initial;
477   boolean first;
478   int local_nr;
479   int sort_priority;
480 };
481
482 struct TitleControlInfo title_controls[MAX_NUM_TITLE_SCREENS];
483
484 /* main menu display and control definitions */
485
486 #define MAIN_CONTROL_NAME                       0
487 #define MAIN_CONTROL_LEVELS                     1
488 #define MAIN_CONTROL_SCORES                     2
489 #define MAIN_CONTROL_EDITOR                     3
490 #define MAIN_CONTROL_INFO                       4
491 #define MAIN_CONTROL_GAME                       5
492 #define MAIN_CONTROL_SETUP                      6
493 #define MAIN_CONTROL_QUIT                       7
494 #define MAIN_CONTROL_PREV_LEVEL                 8
495 #define MAIN_CONTROL_NEXT_LEVEL                 9
496 #define MAIN_CONTROL_FIRST_LEVEL                10
497 #define MAIN_CONTROL_LAST_LEVEL                 11
498 #define MAIN_CONTROL_LEVEL_NUMBER               12
499 #define MAIN_CONTROL_LEVEL_INFO_1               13
500 #define MAIN_CONTROL_LEVEL_INFO_2               14
501 #define MAIN_CONTROL_LEVEL_NAME                 15
502 #define MAIN_CONTROL_LEVEL_AUTHOR               16
503 #define MAIN_CONTROL_LEVEL_YEAR                 17
504 #define MAIN_CONTROL_LEVEL_IMPORTED_FROM        18
505 #define MAIN_CONTROL_LEVEL_IMPORTED_BY          19
506 #define MAIN_CONTROL_LEVEL_TESTED_BY            20
507 #define MAIN_CONTROL_TITLE_1                    21
508 #define MAIN_CONTROL_TITLE_2                    22
509 #define MAIN_CONTROL_TITLE_3                    23
510
511 static char str_main_text_name[10];
512 static char str_main_text_first_level[10];
513 static char str_main_text_last_level[10];
514 static char str_main_text_level_number[10];
515
516 static char *main_text_name                     = str_main_text_name;
517 static char *main_text_first_level              = str_main_text_first_level;
518 static char *main_text_last_level               = str_main_text_last_level;
519 static char *main_text_level_number             = str_main_text_level_number;
520 static char *main_text_levels                   = "Levelset";
521 static char *main_text_scores                   = "Hall Of Fame";
522 static char *main_text_editor                   = "Level Creator";
523 static char *main_text_info                     = "Info Screen";
524 static char *main_text_game                     = "Start Game";
525 static char *main_text_setup                    = "Setup";
526 static char *main_text_quit                     = "Quit";
527 static char *main_text_level_name               = level.name;
528 static char *main_text_level_author             = level.author;
529 static char *main_text_level_year               = NULL;
530 static char *main_text_level_imported_from      = NULL;
531 static char *main_text_level_imported_by        = NULL;
532 static char *main_text_level_tested_by          = NULL;
533
534 struct MainControlInfo
535 {
536   int nr;
537
538   struct MenuPosInfo *pos_button;
539   int button_graphic;
540
541   struct TextPosInfo *pos_text;
542   char **text;
543
544   struct TextPosInfo *pos_input;
545   char **input;
546 };
547
548 static struct MainControlInfo main_controls[] =
549 {
550   {
551     MAIN_CONTROL_NAME,
552     &menu.main.button.name,             IMG_MENU_BUTTON_NAME,
553     &menu.main.text.name,               &main_text_name,
554     &menu.main.input.name,              &setup.player_name,
555   },
556   {
557     MAIN_CONTROL_LEVELS,
558     &menu.main.button.levels,           IMG_MENU_BUTTON_LEVELS,
559     &menu.main.text.levels,             &main_text_levels,
560     NULL,                               NULL,
561   },
562   {
563     MAIN_CONTROL_SCORES,
564     &menu.main.button.scores,           IMG_MENU_BUTTON_SCORES,
565     &menu.main.text.scores,             &main_text_scores,
566     NULL,                               NULL,
567   },
568   {
569     MAIN_CONTROL_EDITOR,
570     &menu.main.button.editor,           IMG_MENU_BUTTON_EDITOR,
571     &menu.main.text.editor,             &main_text_editor,
572     NULL,                               NULL,
573   },
574   {
575     MAIN_CONTROL_INFO,
576     &menu.main.button.info,             IMG_MENU_BUTTON_INFO,
577     &menu.main.text.info,               &main_text_info,
578     NULL,                               NULL,
579   },
580   {
581     MAIN_CONTROL_GAME,
582     &menu.main.button.game,             IMG_MENU_BUTTON_GAME,
583     &menu.main.text.game,               &main_text_game,
584     NULL,                               NULL,
585   },
586   {
587     MAIN_CONTROL_SETUP,
588     &menu.main.button.setup,            IMG_MENU_BUTTON_SETUP,
589     &menu.main.text.setup,              &main_text_setup,
590     NULL,                               NULL,
591   },
592   {
593     MAIN_CONTROL_QUIT,
594     &menu.main.button.quit,             IMG_MENU_BUTTON_QUIT,
595     &menu.main.text.quit,               &main_text_quit,
596     NULL,                               NULL,
597   },
598 #if 0
599   /* (these two buttons are real gadgets) */
600   {
601     MAIN_CONTROL_PREV_LEVEL,
602     &menu.main.button.prev_level,       IMG_MENU_BUTTON_PREV_LEVEL,
603     NULL,                               NULL,
604     NULL,                               NULL,
605   },
606   {
607     MAIN_CONTROL_NEXT_LEVEL,
608     &menu.main.button.next_level,       IMG_MENU_BUTTON_NEXT_LEVEL,
609     NULL,                               NULL,
610     NULL,                               NULL,
611   },
612 #endif
613   {
614     MAIN_CONTROL_FIRST_LEVEL,
615     NULL,                               -1,
616     &menu.main.text.first_level,        &main_text_first_level,
617     NULL,                               NULL,
618   },
619   {
620     MAIN_CONTROL_LAST_LEVEL,
621     NULL,                               -1,
622     &menu.main.text.last_level,         &main_text_last_level,
623     NULL,                               NULL,
624   },
625   {
626     MAIN_CONTROL_LEVEL_NUMBER,
627     NULL,                               -1,
628     &menu.main.text.level_number,       &main_text_level_number,
629     NULL,                               NULL,
630   },
631   {
632     MAIN_CONTROL_LEVEL_INFO_1,
633     NULL,                               -1,
634     &menu.main.text.level_info_1,       NULL,
635     NULL,                               NULL,
636   },
637   {
638     MAIN_CONTROL_LEVEL_INFO_2,
639     NULL,                               -1,
640     &menu.main.text.level_info_2,       NULL,
641     NULL,                               NULL,
642   },
643   {
644     MAIN_CONTROL_LEVEL_NAME,
645     NULL,                               -1,
646     &menu.main.text.level_name,         &main_text_level_name,
647     NULL,                               NULL,
648   },
649   {
650     MAIN_CONTROL_LEVEL_AUTHOR,
651     NULL,                               -1,
652     &menu.main.text.level_author,       &main_text_level_author,
653     NULL,                               NULL,
654   },
655   {
656     MAIN_CONTROL_LEVEL_YEAR,
657     NULL,                               -1,
658     &menu.main.text.level_year,         &main_text_level_year,
659     NULL,                               NULL,
660   },
661   {
662     MAIN_CONTROL_LEVEL_IMPORTED_FROM,
663     NULL,                               -1,
664     &menu.main.text.level_imported_from, &main_text_level_imported_from,
665     NULL,                               NULL,
666   },
667   {
668     MAIN_CONTROL_LEVEL_IMPORTED_BY,
669     NULL,                               -1,
670     &menu.main.text.level_imported_by,  &main_text_level_imported_by,
671     NULL,                               NULL,
672   },
673   {
674     MAIN_CONTROL_LEVEL_TESTED_BY,
675     NULL,                               -1,
676     &menu.main.text.level_tested_by,    &main_text_level_tested_by,
677     NULL,                               NULL,
678   },
679   {
680     MAIN_CONTROL_TITLE_1,
681     NULL,                               -1,
682     &menu.main.text.title_1,            &setup.internal.program_title,
683     NULL,                               NULL,
684   },
685   {
686     MAIN_CONTROL_TITLE_2,
687     NULL,                               -1,
688     &menu.main.text.title_2,            &setup.internal.program_copyright,
689     NULL,                               NULL,
690   },
691   {
692     MAIN_CONTROL_TITLE_3,
693     NULL,                               -1,
694     &menu.main.text.title_3,            &setup.internal.program_company,
695     NULL,                               NULL,
696   },
697
698   {
699     -1,
700     NULL,                               -1,
701     NULL,                               NULL,
702     NULL,                               NULL,
703   }
704 };
705
706
707 static int getTitleScreenGraphic(int nr, boolean initial)
708 {
709   return (initial ? IMG_TITLESCREEN_INITIAL_1 : IMG_TITLESCREEN_1) + nr;
710 }
711
712 static struct TitleMessageInfo *getTitleMessageInfo(int nr, boolean initial)
713 {
714   return (initial ? &titlemessage_initial[nr] : &titlemessage[nr]);
715 }
716
717 #if 0
718 static int getTitleScreenGameMode(boolean initial)
719 {
720   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
721 }
722 #endif
723
724 static int getTitleMessageGameMode(boolean initial)
725 {
726   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
727 }
728
729 static int getTitleAnimMode(struct TitleControlInfo *tci)
730 {
731   int base = (tci->initial ? GAME_MODE_TITLE_INITIAL_1 : GAME_MODE_TITLE_1);
732
733   return base + tci->local_nr;
734 }
735
736 #if 0
737 static int getTitleScreenBackground(boolean initial)
738 {
739   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
740 }
741 #endif
742
743 #if 0
744 static int getTitleMessageBackground(int nr, boolean initial)
745 {
746   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
747 }
748 #endif
749
750 static int getTitleBackground(int nr, boolean initial, boolean is_image)
751 {
752   int base = (is_image ?
753               (initial ? IMG_BACKGROUND_TITLESCREEN_INITIAL_1 :
754                          IMG_BACKGROUND_TITLESCREEN_1) :
755               (initial ? IMG_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
756                          IMG_BACKGROUND_TITLEMESSAGE_1));
757   int graphic_global = (initial ? IMG_BACKGROUND_TITLE_INITIAL :
758                                   IMG_BACKGROUND_TITLE);
759   int graphic_local = base + nr;
760
761   if (graphic_info[graphic_local].bitmap != NULL)
762     return graphic_local;
763
764   if (graphic_info[graphic_global].bitmap != NULL)
765     return graphic_global;
766
767   return IMG_UNDEFINED;
768 }
769
770 static int getTitleSound(struct TitleControlInfo *tci)
771 {
772   boolean is_image = tci->is_image;
773   int initial = tci->initial;
774   int nr = tci->local_nr;
775   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
776   int base = (is_image ?
777               (initial ? SND_BACKGROUND_TITLESCREEN_INITIAL_1 :
778                          SND_BACKGROUND_TITLESCREEN_1) :
779               (initial ? SND_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
780                          SND_BACKGROUND_TITLEMESSAGE_1));
781   int sound_global = menu.sound[mode];
782   int sound_local = base + nr;
783
784 #if 0
785   printf("::: %d, %d, %d: %d ['%s'], %d ['%s']\n",
786          nr, initial, is_image,
787          sound_global, getSoundListEntry(sound_global)->filename,
788          sound_local, getSoundListEntry(sound_local)->filename);
789 #endif
790
791   if (!strEqual(getSoundListEntry(sound_local)->filename, UNDEFINED_FILENAME))
792     return sound_local;
793
794   if (!strEqual(getSoundListEntry(sound_global)->filename, UNDEFINED_FILENAME))
795     return sound_global;
796
797   return SND_UNDEFINED;
798 }
799
800 static int getTitleMusic(struct TitleControlInfo *tci)
801 {
802   boolean is_image = tci->is_image;
803   int initial = tci->initial;
804   int nr = tci->local_nr;
805   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
806   int base = (is_image ?
807               (initial ? MUS_BACKGROUND_TITLESCREEN_INITIAL_1 :
808                          MUS_BACKGROUND_TITLESCREEN_1) :
809               (initial ? MUS_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
810                          MUS_BACKGROUND_TITLEMESSAGE_1));
811   int music_global = menu.music[mode];
812   int music_local = base + nr;
813
814 #if 0
815   printf("::: %d, %d, %d: %d ['%s'], %d ['%s']\n",
816          nr, initial, is_image,
817          music_global, getMusicListEntry(music_global)->filename,
818          music_local, getMusicListEntry(music_local)->filename);
819 #endif
820
821   if (!strEqual(getMusicListEntry(music_local)->filename, UNDEFINED_FILENAME))
822     return music_local;
823
824   if (!strEqual(getMusicListEntry(music_global)->filename, UNDEFINED_FILENAME))
825     return music_global;
826
827   return MUS_UNDEFINED;
828 }
829
830 static struct TitleFadingInfo getTitleFading(struct TitleControlInfo *tci)
831 {
832   boolean is_image = tci->is_image;
833   boolean initial = tci->initial;
834   boolean first = tci->first;
835   int nr = tci->local_nr;
836   struct TitleMessageInfo tmi;
837   struct TitleFadingInfo ti;
838
839   tmi = (is_image ? (initial ? (first ?
840                                 titlescreen_initial_first[nr] :
841                                 titlescreen_initial[nr])
842                              : (first ?
843                                 titlescreen_first[nr] :
844                                 titlescreen[nr]))
845                   : (initial ? (first ?
846                                 titlemessage_initial_first[nr] :
847                                 titlemessage_initial[nr])
848                              : (first ?
849                                 titlemessage_first[nr] :
850                                 titlemessage[nr])));
851
852   ti.fade_mode  = tmi.fade_mode;
853   ti.fade_delay = tmi.fade_delay;
854   ti.post_delay = tmi.post_delay;
855   ti.auto_delay = tmi.auto_delay;
856
857   return ti;
858 }
859
860 static int compareTitleControlInfo(const void *object1, const void *object2)
861 {
862   const struct TitleControlInfo *tci1 = (struct TitleControlInfo *)object1;
863   const struct TitleControlInfo *tci2 = (struct TitleControlInfo *)object2;
864   int compare_result;
865
866   if (tci1->initial != tci2->initial)
867     compare_result = (tci1->initial ? -1 : +1);
868   else if (tci1->sort_priority != tci2->sort_priority)
869     compare_result = tci1->sort_priority - tci2->sort_priority;
870   else if (tci1->is_image != tci2->is_image)
871     compare_result = (tci1->is_image ? -1 : +1);
872   else
873     compare_result = tci1->local_nr - tci2->local_nr;
874
875   return compare_result;
876 }
877
878 static void InitializeTitleControlsExt_AddTitleInfo(boolean is_image,
879                                                     boolean initial,
880                                                     int nr, int sort_priority)
881 {
882   title_controls[num_title_screens].is_image = is_image;
883   title_controls[num_title_screens].initial = initial;
884   title_controls[num_title_screens].local_nr = nr;
885   title_controls[num_title_screens].sort_priority = sort_priority;
886
887   title_controls[num_title_screens].first = FALSE;      /* will be set later */
888
889   num_title_screens++;
890 }
891
892 static void InitializeTitleControls_CheckTitleInfo(boolean initial)
893 {
894   int i;
895
896   for (i = 0; i < MAX_NUM_TITLE_IMAGES; i++)
897   {
898     int graphic = getTitleScreenGraphic(i, initial);
899     Bitmap *bitmap = graphic_info[graphic].bitmap;
900     int sort_priority = graphic_info[graphic].sort_priority;
901
902     if (bitmap != NULL)
903       InitializeTitleControlsExt_AddTitleInfo(TRUE, initial, i, sort_priority);
904   }
905
906   for (i = 0; i < MAX_NUM_TITLE_MESSAGES; i++)
907   {
908     struct TitleMessageInfo *tmi = getTitleMessageInfo(i, initial);
909     char *filename = getLevelSetTitleMessageFilename(i, initial);
910     int sort_priority = tmi->sort_priority;
911
912     if (filename != NULL)
913       InitializeTitleControlsExt_AddTitleInfo(FALSE, initial, i, sort_priority);
914   }
915 }
916
917 static void InitializeTitleControls(boolean show_title_initial)
918 {
919   num_title_screens = 0;
920
921   /* 1st step: initialize title screens for game start (only when starting) */
922   if (show_title_initial)
923     InitializeTitleControls_CheckTitleInfo(TRUE);
924
925   /* 2nd step: initialize title screens for current level set */
926   InitializeTitleControls_CheckTitleInfo(FALSE);
927
928   /* sort title screens according to sort_priority and title number */
929   qsort(title_controls, num_title_screens, sizeof(struct TitleControlInfo),
930         compareTitleControlInfo);
931
932   /* mark first title screen */
933   title_controls[0].first = TRUE;
934 }
935
936 static boolean visibleMenuPos(struct MenuPosInfo *pos)
937 {
938   return (pos != NULL && pos->x != -1 && pos->y != -1);
939 }
940
941 static boolean visibleTextPos(struct TextPosInfo *pos)
942 {
943   return (pos != NULL && pos->x != -1 && pos->y != -1);
944 }
945
946 static void InitializeMainControls()
947 {
948   boolean local_team_mode = (!options.network && setup.team_mode);
949   int i;
950
951   /* set main control text values to dynamically determined values */
952   sprintf(main_text_name,         "%s",   local_team_mode ? "Team:" : "Name:");
953
954   strcpy(main_text_first_level,  int2str(leveldir_current->first_level,
955                                          menu.main.text.first_level.size));
956   strcpy(main_text_last_level,   int2str(leveldir_current->last_level,
957                                          menu.main.text.last_level.size));
958   strcpy(main_text_level_number, int2str(level_nr,
959                                          menu.main.text.level_number.size));
960
961   main_text_level_year          = leveldir_current->year;
962   main_text_level_imported_from = leveldir_current->imported_from;
963   main_text_level_imported_by   = leveldir_current->imported_by;
964   main_text_level_tested_by     = leveldir_current->tested_by;
965
966   /* set main control screen positions to dynamically determined values */
967   for (i = 0; main_controls[i].nr != -1; i++)
968   {
969     struct MainControlInfo *mci = &main_controls[i];
970     int nr                         = mci->nr;
971     struct MenuPosInfo *pos_button = mci->pos_button;
972     struct TextPosInfo *pos_text   = mci->pos_text;
973     struct TextPosInfo *pos_input  = mci->pos_input;
974     char *text                     = (mci->text  ? *mci->text  : NULL);
975     char *input                    = (mci->input ? *mci->input : NULL);
976     int button_graphic             = mci->button_graphic;
977     int font_text                  = (pos_text  ? pos_text->font  : -1);
978     int font_input                 = (pos_input ? pos_input->font : -1);
979
980     int font_text_width   = (font_text  != -1 ? getFontWidth(font_text)   : 0);
981     int font_text_height  = (font_text  != -1 ? getFontHeight(font_text)  : 0);
982     int font_input_width  = (font_input != -1 ? getFontWidth(font_input)  : 0);
983     int font_input_height = (font_input != -1 ? getFontHeight(font_input) : 0);
984     int text_chars  = (text  != NULL ? strlen(text)  : 0);
985     int input_chars = (input != NULL ? strlen(input) : 0);
986
987     int button_width =
988       (button_graphic != -1 ? graphic_info[button_graphic].width  : 0);
989     int button_height =
990       (button_graphic != -1 ? graphic_info[button_graphic].height : 0);
991     int text_width   = font_text_width * text_chars;
992     int text_height  = font_text_height;
993     int input_width  = font_input_width * input_chars;
994     int input_height = font_input_height;
995
996     if (nr == MAIN_CONTROL_NAME)
997     {
998       menu.main.input.name.width  = input_width;
999       menu.main.input.name.height = input_height;
1000     }
1001
1002     if (pos_button != NULL)             /* (x/y may be -1/-1 here) */
1003     {
1004       pos_button->width  = button_width;
1005       pos_button->height = button_height;
1006     }
1007
1008     if (pos_text != NULL)               /* (x/y may be -1/-1 here) */
1009     {
1010       /* calculate size for non-clickable text -- needed for text alignment */
1011       boolean calculate_text_size = (pos_button == NULL && text != NULL);
1012
1013       if (pos_text->width == -1 || calculate_text_size)
1014         pos_text->width = text_width;
1015       if (pos_text->height == -1 || calculate_text_size)
1016         pos_text->height = text_height;
1017
1018       if (visibleMenuPos(pos_button))
1019       {
1020         if (pos_text->x == -1)
1021           pos_text->x = pos_button->x + pos_button->width;
1022         if (pos_text->y == -1)
1023           pos_text->y =
1024             pos_button->y + (pos_button->height - pos_text->height) / 2;
1025       }
1026     }
1027
1028     if (pos_input != NULL)              /* (x/y may be -1/-1 here) */
1029     {
1030       if (visibleTextPos(pos_text))
1031       {
1032         if (pos_input->x == -1)
1033           pos_input->x = pos_text->x + pos_text->width;
1034         if (pos_input->y == -1)
1035           pos_input->y = pos_text->y;
1036       }
1037
1038       if (pos_input->width == -1)
1039         pos_input->width = input_width;
1040       if (pos_input->height == -1)
1041         pos_input->height = input_height;
1042     }
1043   }
1044 }
1045
1046 static void DrawPressedGraphicThruMask(int dst_x, int dst_y,
1047                                        int graphic, boolean pressed)
1048 {
1049   struct GraphicInfo *g = &graphic_info[graphic];
1050   Bitmap *src_bitmap;
1051   int src_x, src_y;
1052   int xoffset = (pressed ? g->pressed_xoffset : 0);
1053   int yoffset = (pressed ? g->pressed_yoffset : 0);
1054
1055   getFixedGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
1056
1057   BlitBitmapMasked(src_bitmap, drawto, src_x + xoffset, src_y + yoffset,
1058                    g->width, g->height, dst_x, dst_y);
1059 }
1060
1061 static void DrawCursorAndText_Main_Ext(int nr, boolean active_text,
1062                                        boolean active_input,
1063                                        boolean pressed_button)
1064 {
1065   int i;
1066
1067   for (i = 0; main_controls[i].nr != -1; i++)
1068   {
1069     struct MainControlInfo *mci = &main_controls[i];
1070
1071     if (mci->nr == nr || nr == -1)
1072     {
1073       struct MenuPosInfo *pos_button = mci->pos_button;
1074       struct TextPosInfo *pos_text   = mci->pos_text;
1075       struct TextPosInfo *pos_input  = mci->pos_input;
1076       char *text                     = (mci->text  ? *mci->text  : NULL);
1077       char *input                    = (mci->input ? *mci->input : NULL);
1078       int button_graphic             = mci->button_graphic;
1079       int font_text                  = (pos_text  ? pos_text->font  : -1);
1080       int font_input                 = (pos_input ? pos_input->font : -1);
1081
1082       if (active_text)
1083       {
1084         button_graphic = BUTTON_ACTIVE(button_graphic);
1085         font_text = FONT_ACTIVE(font_text);
1086       }
1087
1088       if (active_input)
1089       {
1090         font_input = FONT_ACTIVE(font_input);
1091       }
1092
1093       if (visibleMenuPos(pos_button))
1094       {
1095         struct MenuPosInfo *pos = pos_button;
1096         int x = mSX + pos->x;
1097         int y = mSY + pos->y;
1098
1099         DrawBackgroundForGraphic(x, y, pos->width, pos->height, button_graphic);
1100         DrawPressedGraphicThruMask(x, y, button_graphic, pressed_button);
1101       }
1102
1103       if (visibleTextPos(pos_text) && text != NULL)
1104       {
1105         struct TextPosInfo *pos = pos_text;
1106         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1107         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1108
1109 #if 1
1110         /* (check why/if this is needed) */
1111         DrawBackgroundForFont(x, y, pos->width, pos->height, font_text);
1112 #endif
1113         DrawText(x, y, text, font_text);
1114       }
1115
1116       if (visibleTextPos(pos_input) && input != NULL)
1117       {
1118         struct TextPosInfo *pos = pos_input;
1119         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1120         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1121
1122 #if 1
1123         /* (check why/if this is needed) */
1124         DrawBackgroundForFont(x, y, pos->width, pos->height, font_input);
1125 #endif
1126         DrawText(x, y, input, font_input);
1127       }
1128     }
1129   }
1130 }
1131
1132 static void DrawCursorAndText_Main(int nr, boolean active_text,
1133                                    boolean pressed_button)
1134 {
1135   DrawCursorAndText_Main_Ext(nr, active_text, FALSE, pressed_button);
1136 }
1137
1138 #if 0
1139 static void DrawCursorAndText_Main_Input(int nr, boolean active_text,
1140                                          boolean pressed_button)
1141 {
1142   DrawCursorAndText_Main_Ext(nr, active_text, TRUE, pressed_button);
1143 }
1144 #endif
1145
1146 static struct MainControlInfo *getMainControlInfo(int nr)
1147 {
1148   int i;
1149
1150   for (i = 0; main_controls[i].nr != -1; i++)
1151     if (main_controls[i].nr == nr)
1152       return &main_controls[i];
1153
1154   return NULL;
1155 }
1156
1157 static boolean insideMenuPosRect(struct MenuPosInfo *rect, int x, int y)
1158 {
1159   if (rect == NULL)
1160     return FALSE;
1161
1162   int rect_x = ALIGNED_TEXT_XPOS(rect);
1163   int rect_y = ALIGNED_TEXT_YPOS(rect);
1164
1165   return (x >= rect_x && x < rect_x + rect->width &&
1166           y >= rect_y && y < rect_y + rect->height);
1167 }
1168
1169 static boolean insideTextPosRect(struct TextPosInfo *rect, int x, int y)
1170 {
1171   if (rect == NULL)
1172     return FALSE;
1173
1174   int rect_x = ALIGNED_TEXT_XPOS(rect);
1175   int rect_y = ALIGNED_TEXT_YPOS(rect);
1176
1177 #if 0
1178   printf("::: insideTextPosRect: (%d, %d), (%d, %d) [%d, %d] (%d, %d) => %d\n",
1179          x, y, rect_x, rect_y, rect->x, rect->y, rect->width, rect->height,
1180          (x >= rect_x && x < rect_x + rect->width &&
1181           y >= rect_y && y < rect_y + rect->height));
1182 #endif
1183
1184   return (x >= rect_x && x < rect_x + rect->width &&
1185           y >= rect_y && y < rect_y + rect->height);
1186 }
1187
1188 static boolean insidePreviewRect(struct PreviewInfo *preview, int x, int y)
1189 {
1190   int rect_width  = preview->xsize * preview->tile_size;
1191   int rect_height = preview->ysize * preview->tile_size;
1192   int rect_x = ALIGNED_XPOS(preview->x, rect_width,  preview->align);
1193   int rect_y = ALIGNED_YPOS(preview->y, rect_height, preview->valign);
1194
1195   return (x >= rect_x && x < rect_x + rect_width &&
1196           y >= rect_y && y < rect_y + rect_height);
1197 }
1198
1199 static void AdjustScrollbar(int id, int items_max, int items_visible,
1200                             int item_position)
1201 {
1202   struct GadgetInfo *gi = screen_gadget[id];
1203
1204   if (item_position > items_max - items_visible)
1205     item_position = items_max - items_visible;
1206
1207   ModifyGadget(gi, GDI_SCROLLBAR_ITEMS_MAX, items_max,
1208                GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
1209                GDI_SCROLLBAR_ITEM_POSITION, item_position, GDI_END);
1210 }
1211
1212 static void AdjustChooseTreeScrollbar(int id, int first_entry, TreeInfo *ti)
1213 {
1214   AdjustScrollbar(id, numTreeInfoInGroup(ti), NUM_MENU_ENTRIES_ON_SCREEN,
1215                   first_entry);
1216 }
1217
1218 static void clearMenuListArea()
1219 {
1220   int scrollbar_xpos = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
1221
1222   /* correct scrollbar position if placed outside menu (playfield) area */
1223   if (scrollbar_xpos > SX + SC_SCROLLBAR_XPOS)
1224     scrollbar_xpos = SX + SC_SCROLLBAR_XPOS;
1225
1226   /* clear menu list area, but not title or scrollbar */
1227   DrawBackground(mSX, mSY + MENU_SCREEN_START_YPOS * 32,
1228                  scrollbar_xpos - mSX, NUM_MENU_ENTRIES_ON_SCREEN * 32);
1229 }
1230
1231 static void drawCursorExt(int xpos, int ypos, boolean active, int graphic)
1232 {
1233   static int cursor_array[MAX_LEV_FIELDY];
1234   int x = mSX + TILEX * xpos;
1235   int y = mSY + TILEY * (MENU_SCREEN_START_YPOS + ypos);
1236
1237   if (xpos == 0)
1238   {
1239     if (graphic != -1)
1240       cursor_array[ypos] = graphic;
1241     else
1242       graphic = cursor_array[ypos];
1243   }
1244
1245   if (active)
1246     graphic = BUTTON_ACTIVE(graphic);
1247
1248   DrawBackgroundForGraphic(x, y, TILEX, TILEY, graphic);
1249   DrawFixedGraphicThruMaskExt(drawto, x, y, graphic, 0);
1250 }
1251
1252 static void initCursor(int ypos, int graphic)
1253 {
1254   drawCursorExt(0, ypos, FALSE, graphic);
1255 }
1256
1257 static void drawCursor(int ypos, boolean active)
1258 {
1259   drawCursorExt(0, ypos, active, -1);
1260 }
1261
1262 static void drawCursorXY(int xpos, int ypos, int graphic)
1263 {
1264   drawCursorExt(xpos, ypos, FALSE, graphic);
1265 }
1266
1267 static void drawChooseTreeCursor(int ypos, boolean active)
1268 {
1269   drawCursorExt(0, ypos, active, -1);
1270 }
1271
1272 void DrawHeadline()
1273 {
1274   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, getProgramTitleString());
1275   DrawTextSCentered(MENU_TITLE2_YPOS, FONT_TITLE_2,
1276                     setup.internal.program_copyright);
1277 }
1278
1279 void DrawTitleScreenImage(int nr, boolean initial)
1280 {
1281   int graphic = getTitleScreenGraphic(nr, initial);
1282   Bitmap *bitmap = graphic_info[graphic].bitmap;
1283   int width  = graphic_info[graphic].width;
1284   int height = graphic_info[graphic].height;
1285   int src_x = graphic_info[graphic].src_x;
1286   int src_y = graphic_info[graphic].src_y;
1287   int dst_x, dst_y;
1288
1289   if (bitmap == NULL)
1290     return;
1291
1292   if (width > WIN_XSIZE)
1293   {
1294     /* image width too large for window => center image horizontally */
1295     src_x = (width - WIN_XSIZE) / 2;
1296     width = WIN_XSIZE;
1297   }
1298
1299   if (height > WIN_YSIZE)
1300   {
1301     /* image height too large for window => center image vertically */
1302     src_y = (height - WIN_YSIZE) / 2;
1303     height = WIN_YSIZE;
1304   }
1305
1306   /* always display title screens centered */
1307   dst_x = (WIN_XSIZE - width) / 2;
1308   dst_y = (WIN_YSIZE - height) / 2;
1309
1310   SetDrawBackgroundMask(REDRAW_ALL);
1311   SetWindowBackgroundImage(getTitleBackground(nr, initial, TRUE));
1312
1313   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1314
1315   if (DrawingOnBackground(dst_x, dst_y))
1316     BlitBitmapMasked(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1317   else
1318     BlitBitmap(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1319
1320   redraw_mask = REDRAW_ALL;
1321 }
1322
1323 void DrawTitleScreenMessage(int nr, boolean initial)
1324 {
1325   char *filename = getLevelSetTitleMessageFilename(nr, initial);
1326   struct TitleMessageInfo *tmi = getTitleMessageInfo(nr, initial);
1327
1328   if (filename == NULL)
1329     return;
1330
1331   /* force TITLE font on title message screen */
1332   SetFontStatus(getTitleMessageGameMode(initial));
1333
1334   /* if chars *and* width set to "-1", automatically determine width */
1335   if (tmi->chars == -1 && tmi->width == -1)
1336     tmi->width = viewport.window[game_status].width;
1337
1338   /* if lines *and* height set to "-1", automatically determine height */
1339   if (tmi->lines == -1 && tmi->height == -1)
1340     tmi->height = viewport.window[game_status].height;
1341
1342   /* if chars set to "-1", automatically determine by text and font width */
1343   if (tmi->chars == -1)
1344     tmi->chars = tmi->width / getFontWidth(tmi->font);
1345   else
1346     tmi->width = tmi->chars * getFontWidth(tmi->font);
1347
1348   /* if lines set to "-1", automatically determine by text and font height */
1349   if (tmi->lines == -1)
1350     tmi->lines = tmi->height / getFontHeight(tmi->font);
1351   else
1352     tmi->height = tmi->lines * getFontHeight(tmi->font);
1353
1354   /* if x set to "-1", automatically determine by width and alignment */
1355   if (tmi->x == -1)
1356     tmi->x = -1 * ALIGNED_XPOS(0, tmi->width, tmi->align);
1357
1358   /* if y set to "-1", automatically determine by height and alignment */
1359   if (tmi->y == -1)
1360     tmi->y = -1 * ALIGNED_YPOS(0, tmi->height, tmi->valign);
1361
1362   SetDrawBackgroundMask(REDRAW_ALL);
1363   SetWindowBackgroundImage(getTitleBackground(nr, initial, FALSE));
1364
1365   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1366
1367   DrawTextFile(ALIGNED_TEXT_XPOS(tmi), ALIGNED_TEXT_YPOS(tmi),
1368                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
1369                tmi->autowrap, tmi->centered, tmi->parse_comments);
1370
1371   ResetFontStatus();
1372 }
1373
1374 void DrawTitleScreen()
1375 {
1376   KeyboardAutoRepeatOff();
1377
1378   HandleTitleScreen(0, 0, 0, 0, MB_MENU_INITIALIZE);
1379 }
1380
1381 boolean CheckTitleScreen(boolean levelset_has_changed)
1382 {
1383   static boolean show_title_initial = TRUE;
1384   boolean show_titlescreen = FALSE;
1385
1386   /* needed to be able to skip title screen, if no image or message defined */
1387   InitializeTitleControls(show_title_initial);
1388
1389   if (setup.show_titlescreen && (show_title_initial || levelset_has_changed))
1390     show_titlescreen = TRUE;
1391
1392   /* show initial title images and messages only once at program start */
1393   show_title_initial = FALSE;
1394
1395   return (show_titlescreen && num_title_screens > 0);
1396 }
1397
1398 void DrawMainMenu()
1399 {
1400   static LevelDirTree *leveldir_last_valid = NULL;
1401   boolean levelset_has_changed = FALSE;
1402   int fade_mask = REDRAW_FIELD;
1403
1404   LimitScreenUpdates(FALSE);
1405
1406   FadeSetLeaveScreen();
1407
1408   /* do not fade out here -- function may continue and fade on editor screen */
1409
1410   UnmapAllGadgets();
1411   FadeMenuSoundsAndMusic();
1412
1413   ExpireSoundLoops(FALSE);
1414
1415   KeyboardAutoRepeatOn();
1416
1417   audio.sound_deactivated = FALSE;
1418
1419   GetPlayerConfig();
1420
1421   /* needed if last screen was the playing screen, invoked from level editor */
1422   if (level_editor_test_game)
1423   {
1424     CloseDoor(DOOR_CLOSE_ALL);
1425
1426     SetGameStatus(GAME_MODE_EDITOR);
1427
1428     DrawLevelEd();
1429
1430     return;
1431   }
1432
1433   /* needed if last screen was the setup screen and fullscreen state changed */
1434   // (moved to "execSetupGraphics()" to change fullscreen state directly)
1435   // ToggleFullscreenOrChangeWindowScalingIfNeeded();
1436
1437   /* leveldir_current may be invalid (level group, parent link) */
1438   if (!validLevelSeries(leveldir_current))
1439     leveldir_current = getFirstValidTreeInfoEntry(leveldir_last_valid);
1440
1441   if (leveldir_current != leveldir_last_valid)
1442     levelset_has_changed = TRUE;
1443
1444   /* store valid level series information */
1445   leveldir_last_valid = leveldir_current;
1446
1447   init_last = init;                     /* switch to new busy animation */
1448
1449   /* needed if last screen (level choice) changed graphics, sounds or music */
1450   ReloadCustomArtwork(0);
1451
1452   if (CheckTitleScreen(levelset_has_changed))
1453   {
1454     SetGameStatus(GAME_MODE_TITLE);
1455
1456     DrawTitleScreen();
1457
1458     return;
1459   }
1460
1461   if (redraw_mask & REDRAW_ALL)
1462     fade_mask = REDRAW_ALL;
1463
1464   if (CheckIfGlobalBorderHasChanged())
1465     fade_mask = REDRAW_ALL;
1466
1467   FadeOut(fade_mask);
1468
1469   /* needed if different viewport properties defined for menues */
1470   ChangeViewportPropertiesIfNeeded();
1471
1472   SetDrawtoField(DRAW_TO_BACKBUFFER);
1473
1474   /* level_nr may have been set to value over handicap with level editor */
1475   if (setup.handicap && level_nr > leveldir_current->handicap_level)
1476     level_nr = leveldir_current->handicap_level;
1477
1478   LoadLevel(level_nr);
1479   LoadScore(level_nr);
1480
1481   // set this after "ChangeViewportPropertiesIfNeeded()" (which may reset it)
1482   SetDrawDeactivationMask(REDRAW_NONE);
1483   SetDrawBackgroundMask(REDRAW_FIELD);
1484
1485   SetMainBackgroundImage(IMG_BACKGROUND_MAIN);
1486
1487 #if 0
1488   if (fade_mask == REDRAW_ALL)
1489     RedrawGlobalBorder();
1490 #endif
1491
1492   ClearField();
1493
1494   InitializeMainControls();
1495
1496   DrawCursorAndText_Main(-1, FALSE, FALSE);
1497   DrawPreviewLevelInitial();
1498
1499   HandleMainMenu(0, 0, 0, 0, MB_MENU_INITIALIZE);
1500
1501   TapeStop();
1502   if (TAPE_IS_EMPTY(tape))
1503     LoadTape(level_nr);
1504   DrawCompleteVideoDisplay();
1505
1506   PlayMenuSoundsAndMusic();
1507
1508   /* create gadgets for main menu screen */
1509   FreeScreenGadgets();
1510   CreateScreenGadgets();
1511
1512   /* map gadgets for main menu screen */
1513   MapTapeButtons();
1514   MapScreenMenuGadgets(SCREEN_MASK_MAIN);
1515
1516   /* copy actual game door content to door double buffer for OpenDoor() */
1517   BlitBitmap(drawto, bitmap_db_door_1, DX, DY, DXSIZE, DYSIZE, 0, 0);
1518   BlitBitmap(drawto, bitmap_db_door_2, VX, VY, VXSIZE, VYSIZE, 0, 0);
1519
1520   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
1521
1522   DrawMaskedBorder(fade_mask);
1523
1524   FadeIn(fade_mask);
1525   FadeSetEnterMenu();
1526
1527   /* update screen area with special editor door */
1528   redraw_mask |= REDRAW_ALL;
1529   BackToFront();
1530
1531   SetMouseCursor(CURSOR_DEFAULT);
1532
1533   OpenDoor(DOOR_CLOSE_1 | DOOR_OPEN_2);
1534 }
1535
1536 static void gotoTopLevelDir()
1537 {
1538   /* move upwards until inside (but not above) top level directory */
1539   while (leveldir_current->node_parent &&
1540          !strEqual(leveldir_current->node_parent->subdir, STRING_TOP_DIRECTORY))
1541   {
1542     /* write a "path" into level tree for easy navigation to last level */
1543     if (leveldir_current->node_parent->node_group->cl_first == -1)
1544     {
1545       int num_leveldirs = numTreeInfoInGroup(leveldir_current);
1546       int leveldir_pos = posTreeInfo(leveldir_current);
1547       int num_page_entries;
1548       int cl_first, cl_cursor;
1549
1550       if (num_leveldirs <= NUM_MENU_ENTRIES_ON_SCREEN)
1551         num_page_entries = num_leveldirs;
1552       else
1553         num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
1554
1555       cl_first = MAX(0, leveldir_pos - num_page_entries + 1);
1556       cl_cursor = leveldir_pos - cl_first;
1557
1558       leveldir_current->node_parent->node_group->cl_first = cl_first;
1559       leveldir_current->node_parent->node_group->cl_cursor = cl_cursor;
1560     }
1561
1562     leveldir_current = leveldir_current->node_parent;
1563   }
1564 }
1565
1566 void HandleTitleScreen(int mx, int my, int dx, int dy, int button)
1567 {
1568   static unsigned int title_delay = 0;
1569   static int title_screen_nr = 0;
1570   static int last_sound = -1, last_music = -1;
1571   boolean return_to_main_menu = FALSE;
1572   struct TitleControlInfo *tci;
1573   int sound, music;
1574
1575   if (button == MB_MENU_INITIALIZE)
1576   {
1577     title_delay = 0;
1578     title_screen_nr = 0;
1579     tci = &title_controls[title_screen_nr];
1580
1581     SetAnimStatus(getTitleAnimMode(tci));
1582
1583     last_sound = SND_UNDEFINED;
1584     last_music = MUS_UNDEFINED;
1585
1586     if (num_title_screens != 0)
1587     {
1588       FadeSetEnterScreen();
1589
1590       /* use individual title fading instead of global "enter screen" fading */
1591       fading = getTitleFading(tci);
1592     }
1593
1594     if (game_status_last_screen == GAME_MODE_INFO)
1595     {
1596       if (num_title_screens == 0)
1597       {
1598         /* switch game mode from title screen mode back to info screen mode */
1599         SetGameStatus(GAME_MODE_INFO);
1600
1601         /* store that last screen was info screen, not main menu screen */
1602         game_status_last_screen = GAME_MODE_INFO;
1603
1604         DrawInfoScreen_NotAvailable("Title screen information:",
1605                                     "No title screen for this level set.");
1606         return;
1607       }
1608
1609       FadeMenuSoundsAndMusic();
1610     }
1611
1612     FadeOut(REDRAW_ALL);
1613
1614     /* title screens may have different window size */
1615     ChangeViewportPropertiesIfNeeded();
1616
1617     /* only required to update logic for redrawing global border */
1618     ClearField();
1619
1620     if (tci->is_image)
1621       DrawTitleScreenImage(tci->local_nr, tci->initial);
1622     else
1623       DrawTitleScreenMessage(tci->local_nr, tci->initial);
1624
1625     sound = getTitleSound(tci);
1626     music = getTitleMusic(tci);
1627
1628     if (sound != last_sound)
1629       PlayMenuSoundExt(sound);
1630     if (music != last_music)
1631       PlayMenuMusicExt(music);
1632
1633     last_sound = sound;
1634     last_music = music;
1635
1636     SetMouseCursor(CURSOR_NONE);
1637
1638     FadeIn(REDRAW_ALL);
1639
1640     DelayReached(&title_delay, 0);      /* reset delay counter */
1641
1642     return;
1643   }
1644
1645   if (fading.auto_delay > 0 && DelayReached(&title_delay, fading.auto_delay))
1646     button = MB_MENU_CHOICE;
1647
1648   if (button == MB_MENU_LEAVE)
1649   {
1650     return_to_main_menu = TRUE;
1651   }
1652   else if (button == MB_MENU_CHOICE)
1653   {
1654     if (game_status_last_screen == GAME_MODE_INFO && num_title_screens == 0)
1655     {
1656       SetGameStatus(GAME_MODE_INFO);
1657
1658       info_mode = INFO_MODE_MAIN;
1659
1660       DrawInfoScreen();
1661
1662       return;
1663     }
1664
1665     title_screen_nr++;
1666
1667     if (title_screen_nr < num_title_screens)
1668     {
1669       tci = &title_controls[title_screen_nr];
1670
1671       SetAnimStatus(getTitleAnimMode(tci));
1672
1673       sound = getTitleSound(tci);
1674       music = getTitleMusic(tci);
1675
1676       if (last_sound != SND_UNDEFINED && sound != last_sound)
1677         FadeSound(last_sound);
1678       if (last_music != MUS_UNDEFINED && music != last_music)
1679         FadeMusic();
1680
1681       fading = getTitleFading(tci);
1682
1683       FadeOut(REDRAW_ALL);
1684
1685       if (tci->is_image)
1686         DrawTitleScreenImage(tci->local_nr, tci->initial);
1687       else
1688         DrawTitleScreenMessage(tci->local_nr, tci->initial);
1689
1690       sound = getTitleSound(tci);
1691       music = getTitleMusic(tci);
1692
1693       if (sound != last_sound)
1694         PlayMenuSoundExt(sound);
1695       if (music != last_music)
1696         PlayMenuMusicExt(music);
1697
1698       last_sound = sound;
1699       last_music = music;
1700
1701       FadeIn(REDRAW_ALL);
1702
1703       DelayReached(&title_delay, 0);    /* reset delay counter */
1704     }
1705     else
1706     {
1707       FadeMenuSoundsAndMusic();
1708
1709       return_to_main_menu = TRUE;
1710     }
1711   }
1712
1713   if (return_to_main_menu)
1714   {
1715     SetMouseCursor(CURSOR_DEFAULT);
1716
1717     /* force full menu screen redraw after displaying title screens */
1718     redraw_mask = REDRAW_ALL;
1719
1720     if (game_status_last_screen == GAME_MODE_INFO)
1721     {
1722       SetGameStatus(GAME_MODE_INFO);
1723
1724       info_mode = INFO_MODE_MAIN;
1725
1726       DrawInfoScreen();
1727     }
1728     else        /* default: return to main menu */
1729     {
1730       SetGameStatus(GAME_MODE_MAIN);
1731
1732       DrawMainMenu();
1733     }
1734   }
1735 }
1736
1737 void HandleMainMenu_SelectLevel(int step, int direction, int selected_level_nr)
1738 {
1739   int old_level_nr = level_nr;
1740   int new_level_nr;
1741
1742   if (selected_level_nr != NO_DIRECT_LEVEL_SELECT)
1743     new_level_nr = selected_level_nr;
1744   else
1745     new_level_nr = old_level_nr + step * direction;
1746
1747   if (new_level_nr < leveldir_current->first_level)
1748     new_level_nr = leveldir_current->first_level;
1749   if (new_level_nr > leveldir_current->last_level)
1750     new_level_nr = leveldir_current->last_level;
1751
1752   if (setup.handicap && new_level_nr > leveldir_current->handicap_level)
1753   {
1754     /* skipping levels is only allowed when trying to skip single level */
1755     if (setup.skip_levels && new_level_nr == old_level_nr + 1 &&
1756         Request("Level still unsolved! Skip despite handicap?", REQ_ASK))
1757     {
1758       leveldir_current->handicap_level++;
1759       SaveLevelSetup_SeriesInfo();
1760     }
1761
1762     new_level_nr = leveldir_current->handicap_level;
1763   }
1764
1765   if (new_level_nr != old_level_nr)
1766   {
1767     struct MainControlInfo *mci= getMainControlInfo(MAIN_CONTROL_LEVEL_NUMBER);
1768
1769     PlaySound(SND_MENU_ITEM_SELECTING);
1770
1771     level_nr = new_level_nr;
1772
1773     DrawText(mSX + mci->pos_text->x, mSY + mci->pos_text->y,
1774              int2str(level_nr, menu.main.text.level_number.size),
1775              mci->pos_text->font);
1776
1777     LoadLevel(level_nr);
1778     DrawPreviewLevelInitial();
1779
1780     TapeErase();
1781     LoadTape(level_nr);
1782     DrawCompleteVideoDisplay();
1783
1784     /* needed because DrawPreviewLevelInitial() takes some time */
1785     BackToFront();
1786     /* SyncDisplay(); */
1787   }
1788 }
1789
1790 void HandleMainMenu(int mx, int my, int dx, int dy, int button)
1791 {
1792   static int choice = MAIN_CONTROL_GAME;
1793   static boolean button_pressed_last = FALSE;
1794   boolean button_pressed = FALSE;
1795   int pos = choice;
1796   int i;
1797
1798   if (button == MB_MENU_INITIALIZE)
1799   {
1800     DrawCursorAndText_Main(choice, TRUE, FALSE);
1801
1802     return;
1803   }
1804
1805   if (mx || my)         /* mouse input */
1806   {
1807     pos = -1;
1808
1809     for (i = 0; main_controls[i].nr != -1; i++)
1810     {
1811       if (insideMenuPosRect(main_controls[i].pos_button, mx - mSX, my - mSY) ||
1812           insideTextPosRect(main_controls[i].pos_text,   mx - mSX, my - mSY) ||
1813           insideTextPosRect(main_controls[i].pos_input,  mx - mSX, my - mSY))
1814       {
1815         pos = main_controls[i].nr;
1816
1817         break;
1818       }
1819     }
1820
1821     /* check if level preview was clicked */
1822     if (insidePreviewRect(&preview, mx - SX, my - SY))
1823       pos = MAIN_CONTROL_GAME;
1824
1825     // handle pressed/unpressed state for active/inactive menu buttons
1826     // (if pos != -1, "i" contains index position corresponding to "pos")
1827     if (button &&
1828         pos >= MAIN_CONTROL_NAME && pos <= MAIN_CONTROL_QUIT &&
1829         insideMenuPosRect(main_controls[i].pos_button, mx - mSX, my - mSY))
1830       button_pressed = TRUE;
1831
1832     if (button_pressed != button_pressed_last)
1833     {
1834       DrawCursorAndText_Main(choice, TRUE, button_pressed);
1835
1836       if (button_pressed)
1837         PlaySound(SND_MENU_BUTTON_PRESSING);
1838       else
1839         PlaySound(SND_MENU_BUTTON_RELEASING);
1840     }
1841   }
1842   else if (dx || dy)    /* keyboard input */
1843   {
1844     if (dx > 0 && (choice == MAIN_CONTROL_INFO ||
1845                    choice == MAIN_CONTROL_SETUP))
1846       button = MB_MENU_CHOICE;
1847     else if (dy)
1848       pos = choice + dy;
1849   }
1850
1851   if (pos == MAIN_CONTROL_FIRST_LEVEL && !button)
1852   {
1853     HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
1854   }
1855   else if (pos == MAIN_CONTROL_LAST_LEVEL && !button)
1856   {
1857     HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
1858   }
1859   else if (pos == MAIN_CONTROL_LEVEL_NUMBER && !button)
1860   {
1861     CloseDoor(DOOR_CLOSE_2);
1862
1863     SetGameStatus(GAME_MODE_LEVELNR);
1864
1865     DrawChooseLevelNr();
1866   }
1867   else if (pos >= MAIN_CONTROL_NAME && pos <= MAIN_CONTROL_QUIT)
1868   {
1869     if (button)
1870     {
1871       if (pos != choice)
1872       {
1873         PlaySound(SND_MENU_ITEM_ACTIVATING);
1874
1875         DrawCursorAndText_Main(choice, FALSE, FALSE);
1876         DrawCursorAndText_Main(pos, TRUE, button_pressed);
1877
1878         choice = pos;
1879       }
1880       else if (dx != 0)
1881       {
1882         if (choice != MAIN_CONTROL_INFO &&
1883             choice != MAIN_CONTROL_SETUP)
1884           HandleMainMenu_SelectLevel(1, dx, NO_DIRECT_LEVEL_SELECT);
1885       }
1886     }
1887     else
1888     {
1889       PlaySound(SND_MENU_ITEM_SELECTING);
1890
1891       if (pos == MAIN_CONTROL_NAME)
1892       {
1893         SetGameStatus(GAME_MODE_PSEUDO_TYPENAME);
1894
1895         HandleTypeName(strlen(setup.player_name), 0);
1896       }
1897       else if (pos == MAIN_CONTROL_LEVELS)
1898       {
1899         if (leveldir_first)
1900         {
1901           CloseDoor(DOOR_CLOSE_2);
1902
1903           SetGameStatus(GAME_MODE_LEVELS);
1904
1905           SaveLevelSetup_LastSeries();
1906           SaveLevelSetup_SeriesInfo();
1907
1908           if (setup.internal.choose_from_top_leveldir)
1909             gotoTopLevelDir();
1910
1911           DrawChooseLevelSet();
1912         }
1913       }
1914       else if (pos == MAIN_CONTROL_SCORES)
1915       {
1916         CloseDoor(DOOR_CLOSE_2);
1917
1918         SetGameStatus(GAME_MODE_SCORES);
1919
1920         DrawHallOfFame(-1);
1921       }
1922       else if (pos == MAIN_CONTROL_EDITOR)
1923       {
1924         if (leveldir_current->readonly &&
1925             !strEqual(setup.player_name, "Artsoft"))
1926           Request("This level is read only!", REQ_CONFIRM);
1927
1928         CloseDoor(DOOR_CLOSE_2);
1929
1930         SetGameStatus(GAME_MODE_EDITOR);
1931
1932         FadeSetEnterScreen();
1933
1934         DrawLevelEd();
1935       }
1936       else if (pos == MAIN_CONTROL_INFO)
1937       {
1938         CloseDoor(DOOR_CLOSE_2);
1939
1940         SetGameStatus(GAME_MODE_INFO);
1941
1942         info_mode = INFO_MODE_MAIN;
1943
1944         DrawInfoScreen();
1945       }
1946       else if (pos == MAIN_CONTROL_GAME)
1947       {
1948         StartGameActions(options.network, setup.autorecord, level.random_seed);
1949       }
1950       else if (pos == MAIN_CONTROL_SETUP)
1951       {
1952         CloseDoor(DOOR_CLOSE_2);
1953
1954         SetGameStatus(GAME_MODE_SETUP);
1955
1956         setup_mode = SETUP_MODE_MAIN;
1957
1958         DrawSetupScreen();
1959       }
1960       else if (pos == MAIN_CONTROL_QUIT)
1961       {
1962         SaveLevelSetup_LastSeries();
1963         SaveLevelSetup_SeriesInfo();
1964
1965         if (Request("Do you really want to quit?", REQ_ASK | REQ_STAY_CLOSED))
1966           SetGameStatus(GAME_MODE_QUIT);
1967       }
1968     }
1969   }
1970
1971   button_pressed_last = button_pressed;
1972 }
1973
1974
1975 /* ========================================================================= */
1976 /* info screen functions                                                     */
1977 /* ========================================================================= */
1978
1979 static struct TokenInfo *info_info;
1980 static int num_info_info;       /* number of info entries shown on screen */
1981 static int max_info_info;       /* total number of info entries in list */
1982
1983 static void execInfoTitleScreen()
1984 {
1985   info_mode = INFO_MODE_TITLE;
1986
1987   DrawInfoScreen();
1988 }
1989
1990 static void execInfoElements()
1991 {
1992   info_mode = INFO_MODE_ELEMENTS;
1993
1994   DrawInfoScreen();
1995 }
1996
1997 static void execInfoMusic()
1998 {
1999   info_mode = INFO_MODE_MUSIC;
2000
2001   DrawInfoScreen();
2002 }
2003
2004 static void execInfoCredits()
2005 {
2006   info_mode = INFO_MODE_CREDITS;
2007
2008   DrawInfoScreen();
2009 }
2010
2011 static void execInfoProgram()
2012 {
2013   info_mode = INFO_MODE_PROGRAM;
2014
2015   DrawInfoScreen();
2016 }
2017
2018 static void execInfoVersion()
2019 {
2020   info_mode = INFO_MODE_VERSION;
2021
2022   DrawInfoScreen();
2023 }
2024
2025 static void execInfoLevelSet()
2026 {
2027   info_mode = INFO_MODE_LEVELSET;
2028
2029   DrawInfoScreen();
2030 }
2031
2032 static void execExitInfo()
2033 {
2034   SetGameStatus(GAME_MODE_MAIN);
2035
2036   DrawMainMenu();
2037 }
2038
2039 static struct TokenInfo info_info_main[] =
2040 {
2041   { TYPE_ENTER_SCREEN,  execInfoTitleScreen,    "Title Screen"          },
2042   { TYPE_ENTER_SCREEN,  execInfoElements,       "Elements Info"         },
2043   { TYPE_ENTER_SCREEN,  execInfoMusic,          "Music Info"            },
2044   { TYPE_ENTER_SCREEN,  execInfoCredits,        "Credits"               },
2045   { TYPE_ENTER_SCREEN,  execInfoProgram,        "Program Info"          },
2046   { TYPE_ENTER_SCREEN,  execInfoVersion,        "Version Info"          },
2047   { TYPE_ENTER_SCREEN,  execInfoLevelSet,       "Level Set Info"        },
2048   { TYPE_EMPTY,         NULL,                   ""                      },
2049   { TYPE_LEAVE_MENU,    execExitInfo,           "Exit"                  },
2050
2051   { 0,                  NULL,                   NULL                    }
2052 };
2053
2054 static int getMenuTextFont(int type)
2055 {
2056   if (type & (TYPE_SWITCH       |
2057               TYPE_YES_NO       |
2058               TYPE_YES_NO_AUTO  |
2059               TYPE_STRING       |
2060               TYPE_ECS_AGA      |
2061               TYPE_KEYTEXT      |
2062               TYPE_ENTER_LIST))
2063     return FONT_MENU_2;
2064   else
2065     return FONT_MENU_1;
2066 }
2067
2068 static struct TokenInfo *setup_info;
2069 static struct TokenInfo setup_info_input[];
2070
2071 static struct TokenInfo *menu_info;
2072
2073 static void DrawCursorAndText_Menu_Ext(struct TokenInfo *token_info,
2074                                        int screen_pos, int menu_info_pos_raw,
2075                                        boolean active)
2076 {
2077   int pos = (menu_info_pos_raw < 0 ? screen_pos : menu_info_pos_raw);
2078   struct TokenInfo *ti = &token_info[pos];
2079   int xpos = MENU_SCREEN_START_XPOS;
2080   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
2081   int font_nr = getMenuTextFont(ti->type);
2082
2083   if (token_info == setup_info_input)
2084     font_nr = FONT_MENU_1;
2085
2086   if (active)
2087     font_nr = FONT_ACTIVE(font_nr);
2088
2089   DrawText(mSX + xpos * 32, mSY + ypos * 32, ti->text, font_nr);
2090
2091   if (ti->type & ~TYPE_SKIP_ENTRY)
2092     drawCursor(screen_pos, active);
2093 }
2094
2095 static void DrawCursorAndText_Menu(int screen_pos, int menu_info_pos_raw,
2096                                    boolean active)
2097 {
2098   DrawCursorAndText_Menu_Ext(menu_info, screen_pos, menu_info_pos_raw, active);
2099 }
2100
2101 static void DrawCursorAndText_Setup(int screen_pos, int menu_info_pos_raw,
2102                                     boolean active)
2103 {
2104   DrawCursorAndText_Menu_Ext(setup_info, screen_pos, menu_info_pos_raw, active);
2105 }
2106
2107 static char *window_size_text;
2108 static char *scaling_type_text;
2109
2110 static void drawSetupValue(int, int);
2111
2112 static void drawMenuInfoList(int first_entry, int num_page_entries,
2113                              int max_page_entries)
2114 {
2115   int i;
2116
2117   if (first_entry + num_page_entries > max_page_entries)
2118     first_entry = 0;
2119
2120   clearMenuListArea();
2121
2122   for (i = 0; i < num_page_entries; i++)
2123   {
2124     int menu_info_pos = first_entry + i;
2125     struct TokenInfo *si = &menu_info[menu_info_pos];
2126     void *value_ptr = si->value;
2127
2128     /* set some entries to "unchangeable" according to other variables */
2129     if ((value_ptr == &setup.sound_simple && !audio.sound_available) ||
2130         (value_ptr == &setup.sound_loops  && !audio.loops_available) ||
2131         (value_ptr == &setup.sound_music  && !audio.music_available) ||
2132         (value_ptr == &setup.fullscreen   && !video.fullscreen_available) ||
2133         (value_ptr == &window_size_text   && !video.window_scaling_available) ||
2134         (value_ptr == &scaling_type_text  && !video.window_scaling_available))
2135       si->type |= TYPE_GHOSTED;
2136
2137     if (si->type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
2138       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
2139     else if (si->type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
2140       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
2141     else if (si->type & ~TYPE_SKIP_ENTRY)
2142       initCursor(i, IMG_MENU_BUTTON);
2143
2144     DrawCursorAndText_Menu(i, menu_info_pos, FALSE);
2145
2146     if (si->type & TYPE_VALUE &&
2147         menu_info == setup_info)
2148       drawSetupValue(i, menu_info_pos);
2149   }
2150 }
2151
2152 static void DrawInfoScreen_Main()
2153 {
2154   int fade_mask = REDRAW_FIELD;
2155   int i;
2156
2157   if (redraw_mask & REDRAW_ALL)
2158     fade_mask = REDRAW_ALL;
2159
2160   if (CheckIfGlobalBorderHasChanged())
2161     fade_mask = REDRAW_ALL;
2162
2163   UnmapAllGadgets();
2164   FadeMenuSoundsAndMusic();
2165
2166   FreeScreenGadgets();
2167   CreateScreenGadgets();
2168
2169   /* (needed after displaying title screens which disable auto repeat) */
2170   KeyboardAutoRepeatOn();
2171
2172   FadeSetLeaveScreen();
2173
2174   FadeOut(fade_mask);
2175
2176   /* needed if different viewport properties defined for info screen */
2177   ChangeViewportPropertiesIfNeeded();
2178
2179   SetMainBackgroundImage(IMG_BACKGROUND_INFO);
2180
2181   ClearField();
2182
2183   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
2184
2185   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Info Screen");
2186
2187   info_info = info_info_main;
2188
2189   // determine maximal number of info entries that can be displayed on screen
2190   num_info_info = 0;
2191   for (i = 0; info_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
2192     num_info_info++;
2193
2194   // determine maximal number of info entries available for menu of info screen
2195   max_info_info = 0;
2196   for (i = 0; info_info[i].type != 0; i++)
2197     max_info_info++;
2198
2199   HandleInfoScreen_Main(0, 0, 0, 0, MB_MENU_INITIALIZE);
2200
2201   MapScreenGadgets(max_info_info);
2202
2203   PlayMenuSoundsAndMusic();
2204
2205   DrawMaskedBorder(fade_mask);
2206
2207   FadeIn(fade_mask);
2208 }
2209
2210 static void changeSetupValue(int, int, int);
2211
2212 void HandleMenuScreen(int mx, int my, int dx, int dy, int button,
2213                       int mode, int num_page_entries, int max_page_entries)
2214 {
2215   static int num_page_entries_all_last[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2216   static int choice_stores[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2217   static int first_entry_stores[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2218   int *num_page_entries_last = num_page_entries_all_last[game_status];
2219   int *choice_store = choice_stores[game_status];
2220   int *first_entry_store = first_entry_stores[game_status];
2221   int choice = choice_store[mode];              /* starts with 0 */
2222   int first_entry = first_entry_store[mode];    /* starts with 0 */
2223   int x = 0;
2224   int y = choice - first_entry;
2225   int y_old = y;
2226   boolean position_set_by_scrollbar = (dx == 999);
2227   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
2228   int i;
2229
2230   if (button == MB_MENU_INITIALIZE)
2231   {
2232     // check if number of menu page entries has changed (may happen by change
2233     // of custom artwork definition value for 'list_size' for this menu screen)
2234     // (in this case, the last menu position most probably has to be corrected)
2235     if (num_page_entries != num_page_entries_last[mode])
2236     {
2237       choice_store[mode] = first_entry_store[mode] = 0;
2238
2239       choice = first_entry = 0;
2240       y = y_old = 0;
2241
2242       num_page_entries_last[mode] = num_page_entries;
2243     }
2244
2245     /* advance to first valid menu entry */
2246     while (choice < num_page_entries &&
2247            menu_info[choice].type & TYPE_SKIP_ENTRY)
2248       choice++;
2249
2250     if (position_set_by_scrollbar)
2251       first_entry = first_entry_store[mode] = dy;
2252     else
2253       AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2254                       NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2255
2256     drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2257
2258     if (choice < first_entry)
2259     {
2260       choice = first_entry;
2261
2262       if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2263         choice++;
2264     }
2265     else if (choice > first_entry + num_page_entries - 1)
2266     {
2267       choice = first_entry + num_page_entries - 1;
2268
2269       if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2270         choice--;
2271     }
2272
2273     choice_store[mode] = choice;
2274
2275     DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2276
2277     return;
2278   }
2279   else if (button == MB_MENU_LEAVE)
2280   {
2281     PlaySound(SND_MENU_ITEM_SELECTING);
2282
2283     for (i = 0; i < max_page_entries; i++)
2284     {
2285       if (menu_info[i].type & TYPE_LEAVE_MENU)
2286       {
2287         void (*menu_callback_function)(void) = menu_info[i].value;
2288
2289         FadeSetLeaveMenu();
2290
2291         menu_callback_function();
2292
2293         break;  /* absolutely needed because function changes 'menu_info'! */
2294       }
2295     }
2296
2297     return;
2298   }
2299
2300   if (mx || my)         /* mouse input */
2301   {
2302     x = (mx - mSX) / 32;
2303     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
2304   }
2305   else if (dx || dy)    /* keyboard or scrollbar/scrollbutton input */
2306   {
2307     /* move cursor instead of scrolling when already at start/end of list */
2308     if (dy == -1 * SCROLL_LINE && first_entry == 0)
2309       dy = -1;
2310     else if (dy == +1 * SCROLL_LINE &&
2311              first_entry + num_page_entries == max_page_entries)
2312       dy = 1;
2313
2314     /* handle scrolling screen one line or page */
2315     if (y + dy < 0 ||
2316         y + dy > num_page_entries - 1)
2317     {
2318       boolean redraw = FALSE;
2319
2320       if (ABS(dy) == SCROLL_PAGE)
2321         step = num_page_entries - 1;
2322
2323       if (dy < 0 && first_entry > 0)
2324       {
2325         /* scroll page/line up */
2326
2327         first_entry -= step;
2328         if (first_entry < 0)
2329           first_entry = 0;
2330
2331         redraw = TRUE;
2332       }
2333       else if (dy > 0 && first_entry + num_page_entries < max_page_entries)
2334       {
2335         /* scroll page/line down */
2336
2337         first_entry += step;
2338         if (first_entry + num_page_entries > max_page_entries)
2339           first_entry = MAX(0, max_page_entries - num_page_entries);
2340
2341         redraw = TRUE;
2342       }
2343
2344       if (redraw)
2345       {
2346         choice += first_entry - first_entry_store[mode];
2347
2348         if (choice < first_entry)
2349         {
2350           choice = first_entry;
2351
2352           if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2353             choice++;
2354         }
2355         else if (choice > first_entry + num_page_entries - 1)
2356         {
2357           choice = first_entry + num_page_entries - 1;
2358
2359           if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2360             choice--;
2361         }
2362         else if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2363         {
2364           choice += SIGN(dy);
2365
2366           if (choice < first_entry ||
2367               choice > first_entry + num_page_entries - 1)
2368           first_entry += SIGN(dy);
2369         }
2370
2371         first_entry_store[mode] = first_entry;
2372         choice_store[mode] = choice;
2373
2374         drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2375
2376         DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2377
2378         AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2379                         NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2380       }
2381
2382       return;
2383     }
2384
2385     if (dx)
2386     {
2387       int menu_navigation_type = (dx < 0 ? TYPE_LEAVE : TYPE_ENTER);
2388
2389       if (menu_info[choice].type & menu_navigation_type ||
2390           menu_info[choice].type & TYPE_BOOLEAN_STYLE ||
2391           menu_info[choice].type & TYPE_YES_NO_AUTO)
2392         button = MB_MENU_CHOICE;
2393     }
2394     else if (dy)
2395       y += dy;
2396
2397     /* jump to next non-empty menu entry (up or down) */
2398     while (first_entry + y > 0 &&
2399            first_entry + y < max_page_entries - 1 &&
2400            menu_info[first_entry + y].type & TYPE_SKIP_ENTRY)
2401       y += dy;
2402
2403     if (!IN_VIS_MENU(x, y))
2404     {
2405       choice += y - y_old;
2406
2407       if (choice < first_entry)
2408         first_entry = choice;
2409       else if (choice > first_entry + num_page_entries - 1)
2410         first_entry = choice - num_page_entries + 1;
2411
2412       if (first_entry >= 0 &&
2413           first_entry + num_page_entries <= max_page_entries)
2414       {
2415         first_entry_store[mode] = first_entry;
2416
2417         if (choice < first_entry)
2418           choice = first_entry;
2419         else if (choice > first_entry + num_page_entries - 1)
2420           choice = first_entry + num_page_entries - 1;
2421
2422         choice_store[mode] = choice;
2423
2424         drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2425
2426         DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2427
2428         AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2429                         NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2430       }
2431
2432       return;
2433     }
2434   }
2435
2436   if (!anyScrollbarGadgetActive() &&
2437       IN_VIS_MENU(x, y) &&
2438       mx < screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x &&
2439       y >= 0 && y < num_page_entries)
2440   {
2441     if (button)
2442     {
2443       if (first_entry + y != choice &&
2444           menu_info[first_entry + y].type & ~TYPE_SKIP_ENTRY)
2445       {
2446         PlaySound(SND_MENU_ITEM_ACTIVATING);
2447
2448         DrawCursorAndText_Menu(choice - first_entry, choice, FALSE);
2449         DrawCursorAndText_Menu(y, first_entry + y, TRUE);
2450
2451         choice = choice_store[mode] = first_entry + y;
2452       }
2453       else if (dx < 0)
2454       {
2455         PlaySound(SND_MENU_ITEM_SELECTING);
2456
2457         for (i = 0; menu_info[i].type != 0; i++)
2458         {
2459           if (menu_info[i].type & TYPE_LEAVE_MENU)
2460           {
2461             void (*menu_callback_function)(void) = menu_info[i].value;
2462
2463             FadeSetLeaveMenu();
2464
2465             menu_callback_function();
2466
2467             /* absolutely needed because function changes 'menu_info'! */
2468             break;
2469           }
2470         }
2471
2472         return;
2473       }
2474     }
2475     else if (!(menu_info[first_entry + y].type & TYPE_GHOSTED))
2476     {
2477       PlaySound(SND_MENU_ITEM_SELECTING);
2478
2479       /* when selecting key headline, execute function for key value change */
2480       if (menu_info[first_entry + y].type & TYPE_KEYTEXT &&
2481           menu_info[first_entry + y + 1].type & TYPE_KEY)
2482         y++;
2483
2484       /* when selecting string value, execute function for list selection */
2485       if (menu_info[first_entry + y].type & TYPE_STRING && y > 0 &&
2486           menu_info[first_entry + y - 1].type & TYPE_ENTER_LIST)
2487         y--;
2488
2489       if (menu_info[first_entry + y].type & TYPE_ENTER_OR_LEAVE)
2490       {
2491         void (*menu_callback_function)(void) =
2492           menu_info[first_entry + y].value;
2493
2494         FadeSetFromType(menu_info[first_entry + y].type);
2495
2496         menu_callback_function();
2497       }
2498       else if (menu_info[first_entry + y].type & TYPE_VALUE &&
2499                menu_info == setup_info)
2500       {
2501         changeSetupValue(y, first_entry + y, dx);
2502       }
2503     }
2504   }
2505 }
2506
2507 void HandleInfoScreen_Main(int mx, int my, int dx, int dy, int button)
2508 {
2509   menu_info = info_info;
2510
2511   HandleMenuScreen(mx, my, dx, dy, button,
2512                    info_mode, num_info_info, max_info_info);
2513 }
2514
2515 void DrawInfoScreen_NotAvailable(char *text_title, char *text_error)
2516 {
2517   int ystart1 = mSY - SY + 100;
2518   int ystart2 = mSY - SY + 150;
2519   int ybottom = mSY - SY + SYSIZE - 20;
2520
2521   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO);
2522
2523   FadeOut(REDRAW_FIELD);
2524
2525   ClearField();
2526   DrawHeadline();
2527
2528   DrawTextSCentered(ystart1, FONT_TEXT_1, text_title);
2529   DrawTextSCentered(ystart2, FONT_TEXT_2, text_error);
2530
2531   DrawTextSCentered(ybottom, FONT_TEXT_4,
2532                     "Press any key or button for info menu");
2533
2534   FadeIn(REDRAW_FIELD);
2535 }
2536
2537 void DrawInfoScreen_HelpAnim(int start, int max_anims, boolean init)
2538 {
2539   static int infoscreen_step[MAX_INFO_ELEMENTS_ON_SCREEN];
2540   static int infoscreen_frame[MAX_INFO_ELEMENTS_ON_SCREEN];
2541   int xstart = mSX + MENU_SCREEN_INFO_XSTART;
2542   int ystart1 = mSY - SY + MENU_SCREEN_INFO_YSTART1;
2543   int ystart2 = mSY + MENU_SCREEN_INFO_YSTART2;
2544   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
2545   int ystep = MENU_SCREEN_INFO_YSTEP;
2546   int element, action, direction;
2547   int graphic;
2548   int delay;
2549   int sync_frame;
2550   int i, j;
2551
2552   if (init)
2553   {
2554     for (i = 0; i < NUM_INFO_ELEMENTS_ON_SCREEN; i++)
2555       infoscreen_step[i] = infoscreen_frame[i] = 0;
2556
2557     ClearField();
2558     DrawHeadline();
2559
2560     DrawTextSCentered(ystart1, FONT_TEXT_1, "The Game Elements:");
2561
2562     DrawTextSCentered(ybottom, FONT_TEXT_4,
2563                       "Press any key or button for next page");
2564
2565     FrameCounter = 0;
2566   }
2567
2568   i = j = 0;
2569   while (helpanim_info[j].element != HELPANIM_LIST_END)
2570   {
2571     if (i >= start + NUM_INFO_ELEMENTS_ON_SCREEN ||
2572         i >= max_anims)
2573       break;
2574     else if (i < start)
2575     {
2576       while (helpanim_info[j].element != HELPANIM_LIST_NEXT)
2577         j++;
2578
2579       j++;
2580       i++;
2581
2582       continue;
2583     }
2584
2585     j += infoscreen_step[i - start];
2586
2587     element = helpanim_info[j].element;
2588     action = helpanim_info[j].action;
2589     direction = helpanim_info[j].direction;
2590
2591     if (element < 0)
2592       element = EL_UNKNOWN;
2593
2594     if (action != -1 && direction != -1)
2595       graphic = el_act_dir2img(element, action, direction);
2596     else if (action != -1)
2597       graphic = el_act2img(element, action);
2598     else if (direction != -1)
2599       graphic = el_dir2img(element, direction);
2600     else
2601       graphic = el2img(element);
2602
2603     delay = helpanim_info[j++].delay;
2604
2605     if (delay == -1)
2606       delay = 1000000;
2607
2608     if (infoscreen_frame[i - start] == 0)
2609     {
2610       sync_frame = 0;
2611       infoscreen_frame[i - start] = delay - 1;
2612     }
2613     else
2614     {
2615       sync_frame = delay - infoscreen_frame[i - start];
2616       infoscreen_frame[i - start]--;
2617     }
2618
2619     if (helpanim_info[j].element == HELPANIM_LIST_NEXT)
2620     {
2621       if (!infoscreen_frame[i - start])
2622         infoscreen_step[i - start] = 0;
2623     }
2624     else
2625     {
2626       if (!infoscreen_frame[i - start])
2627         infoscreen_step[i - start]++;
2628       while (helpanim_info[j].element != HELPANIM_LIST_NEXT)
2629         j++;
2630     }
2631
2632     j++;
2633
2634     ClearRectangleOnBackground(drawto, xstart, ystart2 + (i - start) * ystep,
2635                                TILEX, TILEY);
2636     DrawFixedGraphicAnimationExt(drawto, xstart, ystart2 + (i - start) * ystep,
2637                                  graphic, sync_frame, USE_MASKING);
2638
2639     if (init)
2640       DrawInfoScreen_HelpText(element, action, direction, i - start);
2641
2642     i++;
2643   }
2644
2645   redraw_mask |= REDRAW_FIELD;
2646
2647   FrameCounter++;
2648 }
2649
2650 static char *getHelpText(int element, int action, int direction)
2651 {
2652   char token[MAX_LINE_LEN];
2653
2654   strcpy(token, element_info[element].token_name);
2655
2656   if (action != -1)
2657     strcat(token, element_action_info[action].suffix);
2658
2659   if (direction != -1)
2660     strcat(token, element_direction_info[MV_DIR_TO_BIT(direction)].suffix);
2661
2662   return getHashEntry(helptext_info, token);
2663 }
2664
2665 void DrawInfoScreen_HelpText(int element, int action, int direction, int ypos)
2666 {
2667   int font_nr = FONT_INFO_ELEMENTS;
2668   int font_width = getFontWidth(font_nr);
2669   int sx = mSX + MINI_TILEX + TILEX + MINI_TILEX;
2670   int sy = mSY + 65 + 2 * 32 + 1;
2671   int ystep = TILEY + 4;
2672   int pad_x = sx - SX;
2673   int max_chars_per_line = (SXSIZE - pad_x - MINI_TILEX) / font_width;
2674   int max_lines_per_text = 2;    
2675   char *text = NULL;
2676
2677   if (action != -1 && direction != -1)          /* element.action.direction */
2678     text = getHelpText(element, action, direction);
2679
2680   if (text == NULL && action != -1)             /* element.action */
2681     text = getHelpText(element, action, -1);
2682
2683   if (text == NULL && direction != -1)          /* element.direction */
2684     text = getHelpText(element, -1, direction);
2685
2686   if (text == NULL)                             /* base element */
2687     text = getHelpText(element, -1, -1);
2688
2689   if (text == NULL)                             /* not found */
2690     text = "No description available";
2691
2692   if (strlen(text) <= max_chars_per_line)       /* only one line of text */
2693     sy += getFontHeight(font_nr) / 2;
2694
2695   DrawTextBuffer(sx, sy + ypos * ystep, text, font_nr,
2696                  max_chars_per_line, -1, max_lines_per_text, 0, -1,
2697                  TRUE, FALSE, FALSE);
2698 }
2699
2700 void DrawInfoScreen_TitleScreen()
2701 {
2702   SetGameStatus(GAME_MODE_TITLE);
2703
2704   DrawTitleScreen();
2705 }
2706
2707 void HandleInfoScreen_TitleScreen(int button)
2708 {
2709   HandleTitleScreen(0, 0, 0, 0, button);
2710 }
2711
2712 void DrawInfoScreen_Elements()
2713 {
2714   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_ELEMENTS);
2715
2716   FadeOut(REDRAW_FIELD);
2717
2718   LoadHelpAnimInfo();
2719   LoadHelpTextInfo();
2720
2721   HandleInfoScreen_Elements(MB_MENU_INITIALIZE);
2722
2723   FadeIn(REDRAW_FIELD);
2724 }
2725
2726 void HandleInfoScreen_Elements(int button)
2727 {
2728   static unsigned int info_delay = 0;
2729   static int num_anims;
2730   static int num_pages;
2731   static int page;
2732   int anims_per_page = NUM_INFO_ELEMENTS_ON_SCREEN;
2733   int i;
2734
2735   if (button == MB_MENU_INITIALIZE)
2736   {
2737     boolean new_element = TRUE;
2738
2739     num_anims = 0;
2740
2741     for (i = 0; helpanim_info[i].element != HELPANIM_LIST_END; i++)
2742     {
2743       if (helpanim_info[i].element == HELPANIM_LIST_NEXT)
2744         new_element = TRUE;
2745       else if (new_element)
2746       {
2747         num_anims++;
2748         new_element = FALSE;
2749       }
2750     }
2751
2752     num_pages = (num_anims + anims_per_page - 1) / anims_per_page;
2753     page = 0;
2754   }
2755
2756   if (button == MB_MENU_LEAVE)
2757   {
2758     PlaySound(SND_MENU_ITEM_SELECTING);
2759
2760     info_mode = INFO_MODE_MAIN;
2761     DrawInfoScreen();
2762
2763     return;
2764   }
2765   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
2766   {
2767     if (button != MB_MENU_INITIALIZE)
2768     {
2769       PlaySound(SND_MENU_ITEM_SELECTING);
2770
2771       page++;
2772     }
2773
2774     if (page >= num_pages)
2775     {
2776       FadeMenuSoundsAndMusic();
2777
2778       info_mode = INFO_MODE_MAIN;
2779       DrawInfoScreen();
2780
2781       return;
2782     }
2783
2784     if (page > 0)
2785       FadeSetNextScreen();
2786
2787     if (button != MB_MENU_INITIALIZE)
2788       FadeOut(REDRAW_FIELD);
2789
2790     DrawInfoScreen_HelpAnim(page * anims_per_page, num_anims, TRUE);
2791
2792     if (button != MB_MENU_INITIALIZE)
2793       FadeIn(REDRAW_FIELD);
2794   }
2795   else
2796   {
2797     if (DelayReached(&info_delay, GameFrameDelay))
2798       if (page < num_pages)
2799         DrawInfoScreen_HelpAnim(page * anims_per_page, num_anims, FALSE);
2800
2801     PlayMenuSoundIfLoop();
2802   }
2803 }
2804
2805 void DrawInfoScreen_Music()
2806 {
2807   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_MUSIC);
2808
2809   FadeOut(REDRAW_FIELD);
2810
2811   ClearField();
2812   DrawHeadline();
2813
2814   LoadMusicInfo();
2815
2816   HandleInfoScreen_Music(MB_MENU_INITIALIZE);
2817
2818   FadeIn(REDRAW_FIELD);
2819 }
2820
2821 void HandleInfoScreen_Music(int button)
2822 {
2823   static struct MusicFileInfo *list = NULL;
2824   int ystart1 = mSY - SY + 100;
2825   int ystart2 = mSY - SY + 150;
2826   int ybottom = mSY - SY + SYSIZE - 20;
2827   int dy = 30;
2828
2829   if (button == MB_MENU_INITIALIZE)
2830   {
2831     list = music_file_info;
2832
2833     if (list == NULL)
2834     {
2835       FadeMenuSoundsAndMusic();
2836
2837       ClearField();
2838       DrawHeadline();
2839
2840       DrawTextSCentered(ystart1, FONT_TEXT_1,
2841                         "No music info for this level set.");
2842
2843       DrawTextSCentered(ybottom, FONT_TEXT_4,
2844                         "Press any key or button for info menu");
2845
2846       return;
2847     }
2848   }
2849
2850   if (button == MB_MENU_LEAVE)
2851   {
2852     PlaySound(SND_MENU_ITEM_SELECTING);
2853
2854     FadeMenuSoundsAndMusic();
2855
2856     info_mode = INFO_MODE_MAIN;
2857     DrawInfoScreen();
2858
2859     return;
2860   }
2861   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
2862   {
2863     int y = 0;
2864
2865     if (button != MB_MENU_INITIALIZE)
2866     {
2867       PlaySound(SND_MENU_ITEM_SELECTING);
2868
2869       if (list != NULL)
2870         list = list->next;
2871     }
2872
2873     if (list == NULL)
2874     {
2875       FadeMenuSoundsAndMusic();
2876
2877       info_mode = INFO_MODE_MAIN;
2878       DrawInfoScreen();
2879
2880       return;
2881     }
2882
2883     FadeMenuSoundsAndMusic();
2884
2885     if (list != music_file_info)
2886       FadeSetNextScreen();
2887
2888     if (button != MB_MENU_INITIALIZE)
2889       FadeOut(REDRAW_FIELD);
2890
2891     ClearField();
2892     DrawHeadline();
2893
2894     if (list->is_sound)
2895     {
2896       int sound = list->music;
2897
2898       if (sound_info[sound].loop)
2899         PlaySoundLoop(sound);
2900       else
2901         PlaySound(sound);
2902
2903       DrawTextSCentered(ystart1, FONT_TEXT_1, "The Game Background Sounds:");
2904     }
2905     else
2906     {
2907       PlayMusic(list->music);
2908
2909       DrawTextSCentered(ystart1, FONT_TEXT_1, "The Game Background Music:");
2910     }
2911
2912     if (!strEqual(list->title, UNKNOWN_NAME))
2913     {
2914       if (!strEqual(list->title_header, UNKNOWN_NAME))
2915         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->title_header);
2916
2917       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "\"%s\"", list->title);
2918     }
2919
2920     if (!strEqual(list->artist, UNKNOWN_NAME))
2921     {
2922       if (!strEqual(list->artist_header, UNKNOWN_NAME))
2923         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->artist_header);
2924       else
2925         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, "by");
2926
2927       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "%s", list->artist);
2928     }
2929
2930     if (!strEqual(list->album, UNKNOWN_NAME))
2931     {
2932       if (!strEqual(list->album_header, UNKNOWN_NAME))
2933         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->album_header);
2934       else
2935         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, "from the album");
2936
2937       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "\"%s\"", list->album);
2938     }
2939
2940     if (!strEqual(list->year, UNKNOWN_NAME))
2941     {
2942       if (!strEqual(list->year_header, UNKNOWN_NAME))
2943         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->year_header);
2944       else
2945         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, "from the year");
2946
2947       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "%s", list->year);
2948     }
2949
2950     DrawTextSCentered(ybottom, FONT_TEXT_4,
2951                       "Press any key or button for next page");
2952
2953     if (button != MB_MENU_INITIALIZE)
2954       FadeIn(REDRAW_FIELD);
2955   }
2956
2957   if (list != NULL && list->is_sound && sound_info[list->music].loop)
2958     PlaySoundLoop(list->music);
2959 }
2960
2961 static void DrawInfoScreen_CreditsScreen(int screen_nr)
2962 {
2963   int ystart1 = mSY - SY + 100;
2964   int ystart2 = mSY - SY + 150;
2965   int ybottom = mSY - SY + SYSIZE - 20;
2966   int ystep = 30;
2967
2968   ClearField();
2969   DrawHeadline();
2970
2971   DrawTextSCentered(ystart1, FONT_TEXT_1, "Credits:");
2972
2973   if (screen_nr == 0)
2974   {
2975     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
2976                       "Special thanks to");
2977     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
2978                       "Peter Liepa");
2979     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
2980                       "for creating");
2981     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
2982                       "\"Boulder Dash\"");
2983     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
2984                       "in the year");
2985     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
2986                       "1984");
2987     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
2988                       "published by");
2989     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
2990                       "First Star Software");
2991   }
2992   else if (screen_nr == 1)
2993   {
2994     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
2995                       "Special thanks to");
2996     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
2997                       "Klaus Heinz & Volker Wertich");
2998     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
2999                       "for creating");
3000     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3001                       "\"Emerald Mine\"");
3002     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3003                       "in the year");
3004     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3005                       "1987");
3006     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3007                       "published by");
3008     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
3009                       "Kingsoft");
3010   }
3011   else if (screen_nr == 2)
3012   {
3013     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3014                       "Special thanks to");
3015     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3016                       "Michael Stopp & Philip Jespersen");
3017     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3018                       "for creating");
3019     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3020                       "\"Supaplex\"");
3021     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3022                       "in the year");
3023     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3024                       "1991");
3025     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3026                       "published by");
3027     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
3028                       "Digital Integration");
3029   }
3030   else if (screen_nr == 3)
3031   {
3032     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3033                       "Special thanks to");
3034     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3035                       "Hiroyuki Imabayashi");
3036     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3037                       "for creating");
3038     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3039                       "\"Sokoban\"");
3040     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3041                       "in the year");
3042     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3043                       "1982");
3044     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3045                       "published by");
3046     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
3047                       "Thinking Rabbit");
3048   }
3049   else if (screen_nr == 4)
3050   {
3051     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3052                       "Special thanks to");
3053     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3054                       "Alan Bond");
3055     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3056                       "and");
3057     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3058                       "J\xfcrgen Bonhagen");
3059     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3060                       "for the continuous creation");
3061     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_2,
3062                       "of outstanding level sets");
3063   }
3064   else if (screen_nr == 5)
3065   {
3066     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3067                       "Thanks to");
3068     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3069                       "Peter Elzner");
3070     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3071                       "for ideas and inspiration by");
3072     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3073                       "Diamond Caves");
3074
3075     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_2,
3076                       "Thanks to");
3077     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_3,
3078                       "Steffest");
3079     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_2,
3080                       "for ideas and inspiration by");
3081     DrawTextSCentered(ystart2 + 8 * ystep, FONT_TEXT_3,
3082                       "DX-Boulderdash");
3083   }
3084   else if (screen_nr == 6)
3085   {
3086     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3087                       "Thanks to");
3088     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3089                       "David Tritscher");
3090 #if 1
3091     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3092                       "for the code base used for the");
3093     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_2,
3094                       "native Emerald Mine engine");
3095 #else
3096     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3097                       "for the new Emerald Mine engine");
3098 #endif
3099   }
3100   else if (screen_nr == 7)
3101   {
3102     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3103                       "Thanks to");
3104     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3105                       "Guido Schulz");
3106     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3107                       "for the initial DOS port");
3108
3109     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3110                       "Thanks to");
3111     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3112                       "Karl H\xf6rnell");
3113     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3114                       "for some additional toons");
3115   }
3116   else if (screen_nr == 8)
3117   {
3118     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3119                       "And not to forget:");
3120     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_2,
3121                       "Many thanks to");
3122     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_3,
3123                       "All those who contributed");
3124     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3125                       "levels to this game");
3126     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_3,
3127                       "since 1995");
3128   }
3129
3130   DrawTextSCentered(ybottom, FONT_TEXT_4,
3131                     "Press any key or button for next page");
3132 }
3133
3134 void DrawInfoScreen_Credits()
3135 {
3136   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_CREDITS);
3137
3138   FadeMenuSoundsAndMusic();
3139
3140   FadeOut(REDRAW_FIELD);
3141
3142   HandleInfoScreen_Credits(MB_MENU_INITIALIZE);
3143
3144   FadeIn(REDRAW_FIELD);
3145 }
3146
3147 void HandleInfoScreen_Credits(int button)
3148 {
3149   static int screen_nr = 0;
3150   int num_screens = 9;
3151
3152   if (button == MB_MENU_INITIALIZE)
3153   {
3154     screen_nr = 0;
3155
3156     // DrawInfoScreen_CreditsScreen(screen_nr);
3157   }
3158
3159   if (button == MB_MENU_LEAVE)
3160   {
3161     PlaySound(SND_MENU_ITEM_SELECTING);
3162
3163     info_mode = INFO_MODE_MAIN;
3164     DrawInfoScreen();
3165
3166     return;
3167   }
3168   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
3169   {
3170     if (button != MB_MENU_INITIALIZE)
3171     {
3172       PlaySound(SND_MENU_ITEM_SELECTING);
3173
3174       screen_nr++;
3175     }
3176
3177     if (screen_nr >= num_screens)
3178     {
3179       FadeMenuSoundsAndMusic();
3180
3181       info_mode = INFO_MODE_MAIN;
3182       DrawInfoScreen();
3183
3184       return;
3185     }
3186
3187     if (screen_nr > 0)
3188       FadeSetNextScreen();
3189
3190     if (button != MB_MENU_INITIALIZE)
3191       FadeOut(REDRAW_FIELD);
3192
3193     DrawInfoScreen_CreditsScreen(screen_nr);
3194
3195     if (button != MB_MENU_INITIALIZE)
3196       FadeIn(REDRAW_FIELD);
3197   }
3198   else
3199   {
3200     PlayMenuSoundIfLoop();
3201   }
3202 }
3203
3204 void DrawInfoScreen_Program()
3205 {
3206   int ystart1 = mSY - SY + 100;
3207   int ystart2 = mSY - SY + 150;
3208   int ybottom = mSY - SY + SYSIZE - 20;
3209   int ystep = 30;
3210
3211   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_PROGRAM);
3212
3213   FadeOut(REDRAW_FIELD);
3214
3215   ClearField();
3216   DrawHeadline();
3217
3218   DrawTextSCentered(ystart1, FONT_TEXT_1, "Program Information:");
3219
3220   DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3221                     "This game is Freeware!");
3222   DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_2,
3223                     "If you like it, send e-mail to:");
3224   DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_3,
3225                     setup.internal.program_email);
3226   DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3227                     "More information and levels:");
3228   DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3229                     setup.internal.program_website);
3230   DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_2,
3231                     "If you have created new levels,");
3232   DrawTextSCentered(ystart2 + 8 * ystep, FONT_TEXT_2,
3233                     "send them to me to include them!");
3234   DrawTextSCentered(ystart2 + 9 * ystep, FONT_TEXT_2,
3235                     ":-)");
3236
3237   DrawTextSCentered(ybottom, FONT_TEXT_4,
3238                     "Press any key or button for info menu");
3239
3240   FadeIn(REDRAW_FIELD);
3241 }
3242
3243 void HandleInfoScreen_Program(int button)
3244 {
3245   if (button == MB_MENU_LEAVE)
3246   {
3247     PlaySound(SND_MENU_ITEM_SELECTING);
3248
3249     info_mode = INFO_MODE_MAIN;
3250     DrawInfoScreen();
3251
3252     return;
3253   }
3254   else if (button == MB_MENU_CHOICE)
3255   {
3256     PlaySound(SND_MENU_ITEM_SELECTING);
3257
3258     FadeMenuSoundsAndMusic();
3259
3260     info_mode = INFO_MODE_MAIN;
3261     DrawInfoScreen();
3262   }
3263   else
3264   {
3265     PlayMenuSoundIfLoop();
3266   }
3267 }
3268
3269 void DrawInfoScreen_Version()
3270 {
3271   int font_header = FONT_TEXT_3;
3272   int font_text = FONT_TEXT_2;
3273   int xstep = getFontWidth(font_text);
3274   int ystep = getFontHeight(font_text);
3275   int ystart1 = mSY - SY + 100;
3276   int ystart2 = mSY - SY + 150;
3277   int ybottom = mSY - SY + SYSIZE - 20;
3278   int xstart1 = mSX - SX + 2 * xstep;
3279   int xstart2 = mSX - SX + 18 * xstep;
3280   int xstart3 = mSX - SX + 28 * xstep;
3281   SDL_version sdl_version_compiled;
3282   const SDL_version *sdl_version_linked;
3283   int driver_name_len = 10;
3284 #if defined(TARGET_SDL2)
3285   SDL_version sdl_version_linked_ext;
3286   const char *driver_name = NULL;
3287 #else
3288   char driver_name[driver_name_len];
3289 #endif
3290
3291   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_VERSION);
3292
3293   FadeOut(REDRAW_FIELD);
3294
3295   ClearField();
3296   DrawHeadline();
3297
3298   DrawTextSCentered(ystart1, FONT_TEXT_1, "Version Information:");
3299
3300   DrawTextF(xstart1, ystart2, font_header, "Name");
3301   DrawTextF(xstart2, ystart2, font_text, getProgramTitleString());
3302
3303   ystart2 += ystep;
3304   DrawTextF(xstart1, ystart2, font_header, "Version");
3305   DrawTextF(xstart2, ystart2, font_text, getProgramVersionString());
3306
3307   ystart2 += ystep;
3308   DrawTextF(xstart1, ystart2, font_header, "Platform");
3309   DrawTextF(xstart2, ystart2, font_text, PLATFORM_STRING);
3310
3311   ystart2 += ystep;
3312   DrawTextF(xstart1, ystart2, font_header, "Target");
3313   DrawTextF(xstart2, ystart2, font_text, TARGET_STRING);
3314
3315   ystart2 += ystep;
3316   DrawTextF(xstart1, ystart2, font_header, "Source date");
3317   DrawTextF(xstart2, ystart2, font_text, getSourceDateString());
3318
3319   ystart2 += 3 * ystep;
3320   DrawTextF(xstart1, ystart2, font_header, "Library");
3321   DrawTextF(xstart2, ystart2, font_header, "compiled");
3322   DrawTextF(xstart3, ystart2, font_header, "linked");
3323
3324   SDL_VERSION(&sdl_version_compiled);
3325 #if defined(TARGET_SDL2)
3326   SDL_GetVersion(&sdl_version_linked_ext);
3327   sdl_version_linked = &sdl_version_linked_ext;
3328 #else
3329   sdl_version_linked = SDL_Linked_Version();
3330 #endif
3331
3332   ystart2 += 2 * ystep;
3333   DrawTextF(xstart1, ystart2, font_text, "SDL");
3334   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3335             sdl_version_compiled.major,
3336             sdl_version_compiled.minor,
3337             sdl_version_compiled.patch);
3338   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3339             sdl_version_linked->major,
3340             sdl_version_linked->minor,
3341             sdl_version_linked->patch);
3342
3343   SDL_IMAGE_VERSION(&sdl_version_compiled);
3344   sdl_version_linked = IMG_Linked_Version();
3345
3346   ystart2 += ystep;
3347   DrawTextF(xstart1, ystart2, font_text, "SDL_image");
3348   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3349             sdl_version_compiled.major,
3350             sdl_version_compiled.minor,
3351             sdl_version_compiled.patch);
3352   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3353             sdl_version_linked->major,
3354             sdl_version_linked->minor,
3355             sdl_version_linked->patch);
3356
3357   SDL_MIXER_VERSION(&sdl_version_compiled);
3358   sdl_version_linked = Mix_Linked_Version();
3359
3360   ystart2 += ystep;
3361   DrawTextF(xstart1, ystart2, font_text, "SDL_mixer");
3362   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3363             sdl_version_compiled.major,
3364             sdl_version_compiled.minor,
3365             sdl_version_compiled.patch);
3366   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3367             sdl_version_linked->major,
3368             sdl_version_linked->minor,
3369             sdl_version_linked->patch);
3370
3371   SDL_NET_VERSION(&sdl_version_compiled);
3372   sdl_version_linked = SDLNet_Linked_Version();
3373
3374   ystart2 += ystep;
3375   DrawTextF(xstart1, ystart2, font_text, "SDL_net");
3376   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3377             sdl_version_compiled.major,
3378             sdl_version_compiled.minor,
3379             sdl_version_compiled.patch);
3380   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3381             sdl_version_linked->major,
3382             sdl_version_linked->minor,
3383             sdl_version_linked->patch);
3384
3385   ystart2 += 3 * ystep;
3386   DrawTextF(xstart1, ystart2, font_header, "Driver");
3387   DrawTextF(xstart2, ystart2, font_header, "Requested");
3388   DrawTextF(xstart3, ystart2, font_header, "Used");
3389
3390 #if defined(TARGET_SDL2)
3391   driver_name = getStringCopyNStatic(SDL_GetVideoDriver(0), driver_name_len);
3392 #else
3393   SDL_VideoDriverName(driver_name, driver_name_len);
3394 #endif
3395
3396   ystart2 += 2 * ystep;
3397   DrawTextF(xstart1, ystart2, font_text, "SDL_VideoDriver");
3398   DrawTextF(xstart2, ystart2, font_text, "%s", setup.system.sdl_videodriver);
3399   DrawTextF(xstart3, ystart2, font_text, "%s", driver_name);
3400
3401 #if defined(TARGET_SDL2)
3402   driver_name = getStringCopyNStatic(SDL_GetAudioDriver(0), driver_name_len);
3403 #else
3404   SDL_AudioDriverName(driver_name, driver_name_len);
3405 #endif
3406
3407   ystart2 += ystep;
3408   DrawTextF(xstart1, ystart2, font_text, "SDL_AudioDriver");
3409   DrawTextF(xstart2, ystart2, font_text, "%s", setup.system.sdl_audiodriver);
3410   DrawTextF(xstart3, ystart2, font_text, "%s", driver_name);
3411
3412   DrawTextSCentered(ybottom, FONT_TEXT_4,
3413                     "Press any key or button for info menu");
3414
3415   FadeIn(REDRAW_FIELD);
3416 }
3417
3418 void HandleInfoScreen_Version(int button)
3419 {
3420   if (button == MB_MENU_LEAVE)
3421   {
3422     PlaySound(SND_MENU_ITEM_SELECTING);
3423
3424     info_mode = INFO_MODE_MAIN;
3425     DrawInfoScreen();
3426
3427     return;
3428   }
3429   else if (button == MB_MENU_CHOICE)
3430   {
3431     PlaySound(SND_MENU_ITEM_SELECTING);
3432
3433     FadeMenuSoundsAndMusic();
3434
3435     info_mode = INFO_MODE_MAIN;
3436     DrawInfoScreen();
3437   }
3438   else
3439   {
3440     PlayMenuSoundIfLoop();
3441   }
3442 }
3443
3444 void DrawInfoScreen_LevelSet()
3445 {
3446   struct TitleMessageInfo *tmi = &readme;
3447   char *filename = getLevelSetInfoFilename();
3448   char *title = "Level Set Information:";
3449   int ystart1 = mSY - SY + 100;
3450   int ybottom = mSY - SY + SYSIZE - 20;
3451
3452   if (filename == NULL)
3453   {
3454     DrawInfoScreen_NotAvailable(title, "No information for this level set.");
3455
3456     return;
3457   }
3458
3459   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_LEVELSET);
3460
3461   FadeOut(REDRAW_FIELD);
3462
3463   ClearField();
3464   DrawHeadline();
3465
3466   DrawTextSCentered(ystart1, FONT_TEXT_1, title);
3467
3468   /* if x position set to "-1", automatically determine by playfield width */
3469   if (tmi->x == -1)
3470     tmi->x = SXSIZE / 2;
3471
3472   /* if y position set to "-1", use static default value */
3473   if (tmi->y == -1)
3474     tmi->y = 150;
3475
3476   /* if width set to "-1", automatically determine by playfield width */
3477   if (tmi->width == -1)
3478     tmi->width = SXSIZE - 2 * TILEX;
3479
3480   /* if height set to "-1", automatically determine by playfield height */
3481   if (tmi->height == -1)
3482     tmi->height = SYSIZE - 20 - tmi->y - 10;
3483
3484   /* if chars set to "-1", automatically determine by text and font width */
3485   if (tmi->chars == -1)
3486     tmi->chars = tmi->width / getFontWidth(tmi->font);
3487   else
3488     tmi->width = tmi->chars * getFontWidth(tmi->font);
3489
3490   /* if lines set to "-1", automatically determine by text and font height */
3491   if (tmi->lines == -1)
3492     tmi->lines = tmi->height / getFontHeight(tmi->font);
3493   else
3494     tmi->height = tmi->lines * getFontHeight(tmi->font);
3495
3496   DrawTextFile(mSX + ALIGNED_TEXT_XPOS(tmi), mSY + ALIGNED_TEXT_YPOS(tmi),
3497                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
3498                tmi->autowrap, tmi->centered, tmi->parse_comments);
3499
3500   DrawTextSCentered(ybottom, FONT_TEXT_4,
3501                     "Press any key or button for info menu");
3502
3503   FadeIn(REDRAW_FIELD);
3504 }
3505
3506 void HandleInfoScreen_LevelSet(int button)
3507 {
3508   if (button == MB_MENU_LEAVE)
3509   {
3510     PlaySound(SND_MENU_ITEM_SELECTING);
3511
3512     info_mode = INFO_MODE_MAIN;
3513     DrawInfoScreen();
3514
3515     return;
3516   }
3517   else if (button == MB_MENU_CHOICE)
3518   {
3519     PlaySound(SND_MENU_ITEM_SELECTING);
3520
3521     FadeMenuSoundsAndMusic();
3522
3523     info_mode = INFO_MODE_MAIN;
3524     DrawInfoScreen();
3525   }
3526   else
3527   {
3528     PlayMenuSoundIfLoop();
3529   }
3530 }
3531
3532 static void DrawInfoScreen()
3533 {
3534   if (info_mode == INFO_MODE_TITLE)
3535     DrawInfoScreen_TitleScreen();
3536   else if (info_mode == INFO_MODE_ELEMENTS)
3537     DrawInfoScreen_Elements();
3538   else if (info_mode == INFO_MODE_MUSIC)
3539     DrawInfoScreen_Music();
3540   else if (info_mode == INFO_MODE_CREDITS)
3541     DrawInfoScreen_Credits();
3542   else if (info_mode == INFO_MODE_PROGRAM)
3543     DrawInfoScreen_Program();
3544   else if (info_mode == INFO_MODE_VERSION)
3545     DrawInfoScreen_Version();
3546   else if (info_mode == INFO_MODE_LEVELSET)
3547     DrawInfoScreen_LevelSet();
3548   else
3549     DrawInfoScreen_Main();
3550
3551   if (info_mode != INFO_MODE_MAIN &&
3552       info_mode != INFO_MODE_TITLE &&
3553       info_mode != INFO_MODE_MUSIC)
3554     PlayMenuSoundsAndMusic();
3555 }
3556
3557 void HandleInfoScreen(int mx, int my, int dx, int dy, int button)
3558 {
3559   if (info_mode == INFO_MODE_TITLE)
3560     HandleInfoScreen_TitleScreen(button);
3561   else if (info_mode == INFO_MODE_ELEMENTS)
3562     HandleInfoScreen_Elements(button);
3563   else if (info_mode == INFO_MODE_MUSIC)
3564     HandleInfoScreen_Music(button);
3565   else if (info_mode == INFO_MODE_CREDITS)
3566     HandleInfoScreen_Credits(button);
3567   else if (info_mode == INFO_MODE_PROGRAM)
3568     HandleInfoScreen_Program(button);
3569   else if (info_mode == INFO_MODE_VERSION)
3570     HandleInfoScreen_Version(button);
3571   else if (info_mode == INFO_MODE_LEVELSET)
3572     HandleInfoScreen_LevelSet(button);
3573   else
3574     HandleInfoScreen_Main(mx, my, dx, dy, button);
3575 }
3576
3577
3578 /* ========================================================================= */
3579 /* type name functions                                                       */
3580 /* ========================================================================= */
3581
3582 void HandleTypeName(int newxpos, Key key)
3583 {
3584   static char last_player_name[MAX_PLAYER_NAME_LEN + 1];
3585   struct MainControlInfo *mci = getMainControlInfo(MAIN_CONTROL_NAME);
3586   struct TextPosInfo *pos = mci->pos_input;
3587   int startx = mSX + ALIGNED_TEXT_XPOS(pos);
3588   int starty = mSY + ALIGNED_TEXT_YPOS(pos);
3589   static int xpos = 0;
3590   int font_nr = pos->font;
3591   int font_active_nr = FONT_ACTIVE(font_nr);
3592   int font_width = getFontWidth(font_active_nr);
3593   char key_char = getValidConfigValueChar(getCharFromKey(key));
3594   boolean is_valid_key_char = (key_char != 0 && (key_char != ' ' || xpos > 0));
3595   boolean is_active = TRUE;
3596
3597   DrawBackgroundForFont(startx,starty, pos->width, pos->height, font_active_nr);
3598
3599   if (newxpos)
3600   {
3601     strcpy(last_player_name, setup.player_name);
3602
3603     xpos = newxpos;
3604
3605     StartTextInput(startx, starty, pos->width, pos->height);
3606   }
3607   else if (is_valid_key_char && xpos < MAX_PLAYER_NAME_LEN)
3608   {
3609     setup.player_name[xpos] = key_char;
3610     setup.player_name[xpos + 1] = 0;
3611
3612     xpos++;
3613   }
3614   else if ((key == KSYM_Delete || key == KSYM_BackSpace) && xpos > 0)
3615   {
3616     xpos--;
3617
3618     setup.player_name[xpos] = 0;
3619   }
3620   else if (key == KSYM_Return && xpos > 0)
3621   {
3622     SaveSetup();
3623
3624     is_active = FALSE;
3625
3626     SetGameStatus(GAME_MODE_MAIN);
3627   }
3628   else if (key == KSYM_Escape)
3629   {
3630     strcpy(setup.player_name, last_player_name);
3631
3632     is_active = FALSE;
3633
3634     SetGameStatus(GAME_MODE_MAIN);
3635   }
3636
3637   if (is_active)
3638   {
3639     pos->width = (strlen(setup.player_name) + 1) * font_width;
3640     startx = mSX + ALIGNED_TEXT_XPOS(pos);
3641
3642     DrawText(startx, starty, setup.player_name, font_active_nr);
3643     DrawText(startx + xpos * font_width, starty, "_", font_active_nr);
3644   }
3645   else
3646   {
3647     pos->width = strlen(setup.player_name) * font_width;
3648     startx = mSX + ALIGNED_TEXT_XPOS(pos);
3649
3650     DrawText(startx, starty, setup.player_name, font_nr);
3651
3652     StopTextInput();
3653   }
3654 }
3655
3656
3657 /* ========================================================================= */
3658 /* tree menu functions                                                       */
3659 /* ========================================================================= */
3660
3661 static void DrawChooseTree(TreeInfo **ti_ptr)
3662 {
3663   int fade_mask = REDRAW_FIELD;
3664
3665   if (CheckIfGlobalBorderHasChanged())
3666     fade_mask = REDRAW_ALL;
3667
3668   if (strEqual((*ti_ptr)->subdir, STRING_TOP_DIRECTORY))
3669   {
3670     SetGameStatus(GAME_MODE_MAIN);
3671
3672     DrawMainMenu();
3673
3674     return;
3675   }
3676
3677   UnmapAllGadgets();
3678
3679   FreeScreenGadgets();
3680   CreateScreenGadgets();
3681
3682   FadeOut(fade_mask);
3683
3684   /* needed if different viewport properties defined for choosing level (set) */
3685   ChangeViewportPropertiesIfNeeded();
3686
3687   if (game_status == GAME_MODE_LEVELNR)
3688     SetMainBackgroundImage(IMG_BACKGROUND_LEVELNR);
3689   else if (game_status == GAME_MODE_LEVELS)
3690     SetMainBackgroundImage(IMG_BACKGROUND_LEVELS);
3691
3692   ClearField();
3693
3694   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
3695
3696   HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, ti_ptr);
3697   MapScreenTreeGadgets(*ti_ptr);
3698
3699   DrawMaskedBorder(fade_mask);
3700
3701   FadeIn(fade_mask);
3702 }
3703
3704 static void drawChooseTreeList(int first_entry, int num_page_entries,
3705                                TreeInfo *ti)
3706 {
3707   int i;
3708   char *title_string = NULL;
3709   int yoffset_sets = MENU_TITLE1_YPOS;
3710   int yoffset_setup = 16;
3711   int yoffset = (ti->type == TREE_TYPE_LEVEL_DIR ||
3712                  ti->type == TREE_TYPE_LEVEL_NR ? yoffset_sets : yoffset_setup);
3713
3714   title_string = ti->infotext;
3715
3716   DrawTextSCentered(mSY - SY + yoffset, FONT_TITLE_1, title_string);
3717
3718   clearMenuListArea();
3719
3720   for (i = 0; i < num_page_entries; i++)
3721   {
3722     TreeInfo *node, *node_first;
3723     int entry_pos = first_entry + i;
3724     int xpos = MENU_SCREEN_START_XPOS;
3725     int ypos = MENU_SCREEN_START_YPOS + i;
3726     int startx = mSX + xpos * 32;
3727     int starty = mSY + ypos * 32;
3728     int font_nr = FONT_TEXT_1;
3729     int font_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
3730     int startx_text = startx + font_xoffset;
3731     int startx_scrollbar = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
3732     int text_size = startx_scrollbar - startx_text;
3733     int max_buffer_len = text_size / getFontWidth(font_nr);
3734     char buffer[max_buffer_len + 1];
3735
3736     node_first = getTreeInfoFirstGroupEntry(ti);
3737     node = getTreeInfoFromPos(node_first, entry_pos);
3738
3739     strncpy(buffer, node->name, max_buffer_len);
3740     buffer[max_buffer_len] = '\0';
3741
3742     DrawText(startx, starty, buffer, font_nr + node->color);
3743
3744     if (node->parent_link)
3745       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
3746     else if (node->level_group)
3747       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
3748     else
3749       initCursor(i, IMG_MENU_BUTTON);
3750   }
3751
3752   redraw_mask |= REDRAW_FIELD;
3753 }
3754
3755 static void drawChooseTreeInfo(int entry_pos, TreeInfo *ti)
3756 {
3757   TreeInfo *node, *node_first;
3758   int x, last_redraw_mask = redraw_mask;
3759   int ypos = MENU_TITLE2_YPOS;
3760   int font_nr = FONT_TITLE_2;
3761
3762   if (ti->type == TREE_TYPE_LEVEL_NR)
3763     DrawTextFCentered(ypos, font_nr, leveldir_current->name);
3764
3765   if (ti->type != TREE_TYPE_LEVEL_DIR)
3766     return;
3767
3768   node_first = getTreeInfoFirstGroupEntry(ti);
3769   node = getTreeInfoFromPos(node_first, entry_pos);
3770
3771   DrawBackgroundForFont(SX, SY + ypos, SXSIZE, getFontHeight(font_nr), font_nr);
3772
3773   if (node->parent_link)
3774     DrawTextFCentered(ypos, font_nr, "leave \"%s\"",
3775                       node->node_parent->name);
3776   else if (node->level_group)
3777     DrawTextFCentered(ypos, font_nr, "enter \"%s\"",
3778                       node->name);
3779   else if (ti->type == TREE_TYPE_LEVEL_DIR)
3780     DrawTextFCentered(ypos, font_nr, "%3d %s (%s)",
3781                       node->levels, (node->levels > 1 ? "levels" : "level"),
3782                       node->class_desc);
3783
3784   /* let BackToFront() redraw only what is needed */
3785   redraw_mask = last_redraw_mask;
3786   for (x = 0; x < SCR_FIELDX; x++)
3787     MarkTileDirty(x, 1);
3788 }
3789
3790 static void HandleChooseTree(int mx, int my, int dx, int dy, int button,
3791                              TreeInfo **ti_ptr)
3792 {
3793   TreeInfo *ti = *ti_ptr;
3794   int x = 0;
3795   int y = ti->cl_cursor;
3796   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
3797   int num_entries = numTreeInfoInGroup(ti);
3798   int num_page_entries;
3799   boolean position_set_by_scrollbar = (dx == 999);
3800
3801   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
3802     num_page_entries = num_entries;
3803   else
3804     num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
3805
3806   if (button == MB_MENU_INITIALIZE)
3807   {
3808     int num_entries = numTreeInfoInGroup(ti);
3809     int entry_pos = posTreeInfo(ti);
3810
3811     if (ti->cl_first == -1)
3812     {
3813       /* only on initialization */
3814       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
3815       ti->cl_cursor = entry_pos - ti->cl_first;
3816     }
3817     else if (ti->cl_cursor >= num_page_entries ||
3818              (num_entries > num_page_entries &&
3819               num_entries - ti->cl_first < num_page_entries))
3820     {
3821       /* only after change of list size (by custom graphic configuration) */
3822       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
3823       ti->cl_cursor = entry_pos - ti->cl_first;
3824     }
3825
3826     if (position_set_by_scrollbar)
3827       ti->cl_first = dy;
3828     else
3829       AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
3830                                 ti->cl_first, ti);
3831
3832     drawChooseTreeList(ti->cl_first, num_page_entries, ti);
3833     drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
3834     drawChooseTreeCursor(ti->cl_cursor, TRUE);
3835
3836     return;
3837   }
3838   else if (button == MB_MENU_LEAVE)
3839   {
3840     FadeSetLeaveMenu();
3841
3842     PlaySound(SND_MENU_ITEM_SELECTING);
3843
3844     if (ti->node_parent)
3845     {
3846       *ti_ptr = ti->node_parent;
3847       DrawChooseTree(ti_ptr);
3848     }
3849     else if (game_status == GAME_MODE_SETUP)
3850     {
3851       if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
3852           setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
3853           setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
3854         execSetupGame();
3855       else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
3856                setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
3857                setup_mode == SETUP_MODE_CHOOSE_RENDERING)
3858         execSetupGraphics();
3859       else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
3860                setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
3861                setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
3862         execSetupSound();
3863       else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
3864                setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
3865                setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
3866         execSetupTouch();
3867       else
3868         execSetupArtwork();
3869     }
3870     else
3871     {
3872       if (game_status == GAME_MODE_LEVELNR)
3873       {
3874         int new_level_nr = atoi(level_number_current->identifier);
3875
3876         HandleMainMenu_SelectLevel(0, 0, new_level_nr);
3877       }
3878
3879       SetGameStatus(GAME_MODE_MAIN);
3880
3881       DrawMainMenu();
3882     }
3883
3884     return;
3885   }
3886
3887   if (mx || my)         /* mouse input */
3888   {
3889     x = (mx - mSX) / 32;
3890     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
3891   }
3892   else if (dx || dy)    /* keyboard or scrollbar/scrollbutton input */
3893   {
3894     /* move cursor instead of scrolling when already at start/end of list */
3895     if (dy == -1 * SCROLL_LINE && ti->cl_first == 0)
3896       dy = -1;
3897     else if (dy == +1 * SCROLL_LINE &&
3898              ti->cl_first + num_page_entries == num_entries)
3899       dy = 1;
3900
3901     /* handle scrolling screen one line or page */
3902     if (ti->cl_cursor + dy < 0 ||
3903         ti->cl_cursor + dy > num_page_entries - 1)
3904     {
3905       boolean redraw = FALSE;
3906
3907       if (ABS(dy) == SCROLL_PAGE)
3908         step = num_page_entries - 1;
3909
3910       if (dy < 0 && ti->cl_first > 0)
3911       {
3912         /* scroll page/line up */
3913
3914         ti->cl_first -= step;
3915         if (ti->cl_first < 0)
3916           ti->cl_first = 0;
3917
3918         redraw = TRUE;
3919       }
3920       else if (dy > 0 && ti->cl_first + num_page_entries < num_entries)
3921       {
3922         /* scroll page/line down */
3923
3924         ti->cl_first += step;
3925         if (ti->cl_first + num_page_entries > num_entries)
3926           ti->cl_first = MAX(0, num_entries - num_page_entries);
3927
3928         redraw = TRUE;
3929       }
3930
3931       if (redraw)
3932       {
3933         drawChooseTreeList(ti->cl_first, num_page_entries, ti);
3934         drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
3935         drawChooseTreeCursor(ti->cl_cursor, TRUE);
3936
3937         AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
3938                                   ti->cl_first, ti);
3939       }
3940
3941       return;
3942     }
3943
3944     /* handle moving cursor one line */
3945     y = ti->cl_cursor + dy;
3946   }
3947
3948   if (dx == 1)
3949   {
3950     TreeInfo *node_first, *node_cursor;
3951     int entry_pos = ti->cl_first + y;
3952
3953     node_first = getTreeInfoFirstGroupEntry(ti);
3954     node_cursor = getTreeInfoFromPos(node_first, entry_pos);
3955
3956     if (node_cursor->node_group)
3957     {
3958       FadeSetEnterMenu();
3959
3960       PlaySound(SND_MENU_ITEM_SELECTING);
3961
3962       node_cursor->cl_first = ti->cl_first;
3963       node_cursor->cl_cursor = ti->cl_cursor;
3964       *ti_ptr = node_cursor->node_group;
3965       DrawChooseTree(ti_ptr);
3966
3967       return;
3968     }
3969   }
3970   else if (dx == -1 && ti->node_parent)
3971   {
3972     FadeSetLeaveMenu();
3973
3974     PlaySound(SND_MENU_ITEM_SELECTING);
3975
3976     *ti_ptr = ti->node_parent;
3977     DrawChooseTree(ti_ptr);
3978
3979     return;
3980   }
3981
3982   if (!anyScrollbarGadgetActive() &&
3983       IN_VIS_MENU(x, y) &&
3984       mx < screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x &&
3985       y >= 0 && y < num_page_entries)
3986   {
3987     if (button)
3988     {
3989       if (y != ti->cl_cursor)
3990       {
3991         PlaySound(SND_MENU_ITEM_ACTIVATING);
3992
3993         drawChooseTreeCursor(ti->cl_cursor, FALSE);
3994         drawChooseTreeCursor(y, TRUE);
3995         drawChooseTreeInfo(ti->cl_first + y, ti);
3996
3997         ti->cl_cursor = y;
3998       }
3999       else if (dx < 0)
4000       {
4001         if (game_status == GAME_MODE_SETUP)
4002         {
4003           if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
4004               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
4005               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
4006             execSetupGame();
4007           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
4008                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
4009                    setup_mode == SETUP_MODE_CHOOSE_RENDERING)
4010             execSetupGraphics();
4011           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
4012                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
4013                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
4014             execSetupSound();
4015           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
4016                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
4017                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
4018             execSetupTouch();
4019           else
4020             execSetupArtwork();
4021         }
4022       }
4023     }
4024     else
4025     {
4026       TreeInfo *node_first, *node_cursor;
4027       int entry_pos = ti->cl_first + y;
4028
4029       PlaySound(SND_MENU_ITEM_SELECTING);
4030
4031       node_first = getTreeInfoFirstGroupEntry(ti);
4032       node_cursor = getTreeInfoFromPos(node_first, entry_pos);
4033
4034       if (node_cursor->node_group)
4035       {
4036         FadeSetEnterMenu();
4037
4038         node_cursor->cl_first = ti->cl_first;
4039         node_cursor->cl_cursor = ti->cl_cursor;
4040         *ti_ptr = node_cursor->node_group;
4041         DrawChooseTree(ti_ptr);
4042       }
4043       else if (node_cursor->parent_link)
4044       {
4045         FadeSetLeaveMenu();
4046
4047         *ti_ptr = node_cursor->node_parent;
4048         DrawChooseTree(ti_ptr);
4049       }
4050       else
4051       {
4052         FadeSetEnterMenu();
4053
4054         node_cursor->cl_first = ti->cl_first;
4055         node_cursor->cl_cursor = ti->cl_cursor;
4056         *ti_ptr = node_cursor;
4057
4058         if (ti->type == TREE_TYPE_LEVEL_DIR)
4059         {
4060           LoadLevelSetup_SeriesInfo();
4061
4062           SaveLevelSetup_LastSeries();
4063           SaveLevelSetup_SeriesInfo();
4064           TapeErase();
4065         }
4066
4067         if (game_status == GAME_MODE_SETUP)
4068         {
4069           if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
4070               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
4071               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
4072             execSetupGame();
4073           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
4074                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
4075                    setup_mode == SETUP_MODE_CHOOSE_RENDERING)
4076             execSetupGraphics();
4077           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
4078                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
4079                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
4080             execSetupSound();
4081           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
4082                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
4083                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
4084             execSetupTouch();
4085           else
4086             execSetupArtwork();
4087         }
4088         else
4089         {
4090           if (game_status == GAME_MODE_LEVELNR)
4091           {
4092             int new_level_nr = atoi(level_number_current->identifier);
4093
4094             HandleMainMenu_SelectLevel(0, 0, new_level_nr);
4095           }
4096
4097           SetGameStatus(GAME_MODE_MAIN);
4098
4099           DrawMainMenu();
4100         }
4101       }
4102     }
4103   }
4104 }
4105
4106 void DrawChooseLevelSet()
4107 {
4108   FadeMenuSoundsAndMusic();
4109
4110   DrawChooseTree(&leveldir_current);
4111
4112   PlayMenuSoundsAndMusic();
4113 }
4114
4115 void HandleChooseLevelSet(int mx, int my, int dx, int dy, int button)
4116 {
4117   HandleChooseTree(mx, my, dx, dy, button, &leveldir_current);
4118 }
4119
4120 void DrawChooseLevelNr()
4121 {
4122   int i;
4123
4124   FadeMenuSoundsAndMusic();
4125
4126   if (level_number != NULL)
4127   {
4128     freeTreeInfo(level_number);
4129
4130     level_number = NULL;
4131   }
4132
4133   for (i = leveldir_current->first_level; i <= leveldir_current->last_level;i++)
4134   {
4135     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_LEVEL_NR);
4136     char identifier[32], name[32];
4137     int value = i;
4138
4139     /* temporarily load level info to get level name */
4140     LoadLevelInfoOnly(i);
4141
4142     ti->node_top = &level_number;
4143     ti->sort_priority = 10000 + value;
4144     ti->color = (level.no_level_file ? FC_BLUE :
4145                  LevelStats_getSolved(i) ? FC_GREEN :
4146                  LevelStats_getPlayed(i) ? FC_YELLOW : FC_RED);
4147
4148     snprintf(identifier, sizeof(identifier), "%d", value);
4149     snprintf(name, sizeof(name), "%03d: %s", value,
4150              (level.no_level_file ? "(no file)" : level.name));
4151
4152     setString(&ti->identifier, identifier);
4153     setString(&ti->name, name);
4154     setString(&ti->name_sorting, name);
4155
4156     pushTreeInfo(&level_number, ti);
4157   }
4158
4159   /* sort level number values to start with lowest level number */
4160   sortTreeInfo(&level_number);
4161
4162   /* set current level number to current level number */
4163   level_number_current =
4164     getTreeInfoFromIdentifier(level_number, i_to_a(level_nr));
4165
4166   /* if that also fails, set current level number to first available level */
4167   if (level_number_current == NULL)
4168     level_number_current = level_number;
4169
4170   DrawChooseTree(&level_number_current);
4171
4172   PlayMenuSoundsAndMusic();
4173 }
4174
4175 void HandleChooseLevelNr(int mx, int my, int dx, int dy, int button)
4176 {
4177   HandleChooseTree(mx, my, dx, dy, button, &level_number_current);
4178 }
4179
4180 void DrawHallOfFame(int highlight_position)
4181 {
4182   int fade_mask = REDRAW_FIELD;
4183
4184   if (CheckIfGlobalBorderHasChanged())
4185     fade_mask = REDRAW_ALL;
4186
4187   UnmapAllGadgets();
4188   FadeMenuSoundsAndMusic();
4189
4190   /* (this is needed when called from GameEnd() after winning a game) */
4191   KeyboardAutoRepeatOn();
4192
4193   /* (this is needed when called from GameEnd() after winning a game) */
4194   SetDrawDeactivationMask(REDRAW_NONE);
4195   SetDrawBackgroundMask(REDRAW_FIELD);
4196
4197   if (highlight_position < 0) 
4198     LoadScore(level_nr);
4199   else
4200     SetAnimStatus(GAME_MODE_PSEUDO_SCORESNEW);
4201
4202   FadeSetEnterScreen();
4203
4204   FadeOut(fade_mask);
4205
4206   /* needed if different viewport properties defined for scores */
4207   ChangeViewportPropertiesIfNeeded();
4208
4209   PlayMenuSoundsAndMusic();
4210
4211   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
4212
4213   HandleHallOfFame(highlight_position, 0, 0, 0, MB_MENU_INITIALIZE);
4214
4215   DrawMaskedBorder(fade_mask);
4216
4217   FadeIn(fade_mask);
4218 }
4219
4220 static void drawHallOfFameList(int first_entry, int highlight_position)
4221 {
4222   int i, j;
4223
4224   SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
4225   ClearField();
4226
4227   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, "Hall Of Fame");
4228   DrawTextFCentered(MENU_TITLE2_YPOS, FONT_TITLE_2,
4229                     "HighScores of Level %d", level_nr);
4230
4231   for (i = 0; i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
4232   {
4233     int entry = first_entry + i;
4234     boolean active = (entry == highlight_position);
4235     int font_nr1 = (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4236     int font_nr2 = (active ? FONT_TEXT_2_ACTIVE : FONT_TEXT_2);
4237     int font_nr3 = (active ? FONT_TEXT_3_ACTIVE : FONT_TEXT_3);
4238     int font_nr4 = (active ? FONT_TEXT_4_ACTIVE : FONT_TEXT_4);
4239     int dxoff = getFontDrawOffsetX(font_nr1);
4240     int dx1 = 3 * getFontWidth(font_nr1);
4241     int dx2 = dx1 + getFontWidth(font_nr1);
4242     int dx3 = SXSIZE - 2 * (mSX - SX + dxoff) - 5 * getFontWidth(font_nr4);
4243     int num_dots = (dx3 - dx2) / getFontWidth(font_nr3);
4244     int sy = mSY + 64 + i * 32;
4245
4246     DrawText(mSX, sy, int2str(entry + 1, 3), font_nr1);
4247     DrawText(mSX + dx1, sy, ".", font_nr1);
4248
4249     for (j = 0; j < num_dots; j++)
4250       DrawText(mSX + dx2 + j * getFontWidth(font_nr3), sy, ".", font_nr3);
4251
4252     if (!strEqual(highscore[entry].Name, EMPTY_PLAYER_NAME))
4253       DrawText(mSX + dx2, sy, highscore[entry].Name, font_nr2);
4254
4255     DrawText(mSX + dx3, sy, int2str(highscore[entry].Score, 5), font_nr4);
4256   }
4257
4258   redraw_mask |= REDRAW_FIELD;
4259 }
4260
4261 void HandleHallOfFame(int mx, int my, int dx, int dy, int button)
4262 {
4263   static int first_entry = 0;
4264   static int highlight_position = 0;
4265   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
4266
4267   if (button == MB_MENU_INITIALIZE)
4268   {
4269     first_entry = 0;
4270     highlight_position = mx;
4271     drawHallOfFameList(first_entry, highlight_position);
4272
4273     return;
4274   }
4275
4276   if (ABS(dy) == SCROLL_PAGE)           /* handle scrolling one page */
4277     step = NUM_MENU_ENTRIES_ON_SCREEN - 1;
4278
4279   if (dy < 0)
4280   {
4281     if (first_entry > 0)
4282     {
4283       first_entry -= step;
4284       if (first_entry < 0)
4285         first_entry = 0;
4286
4287       drawHallOfFameList(first_entry, highlight_position);
4288     }
4289   }
4290   else if (dy > 0)
4291   {
4292     if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN < MAX_SCORE_ENTRIES)
4293     {
4294       first_entry += step;
4295       if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN > MAX_SCORE_ENTRIES)
4296         first_entry = MAX(0, MAX_SCORE_ENTRIES - NUM_MENU_ENTRIES_ON_SCREEN);
4297
4298       drawHallOfFameList(first_entry, highlight_position);
4299     }
4300   }
4301   else if (button == MB_MENU_LEAVE)
4302   {
4303     PlaySound(SND_MENU_ITEM_SELECTING);
4304
4305     FadeSound(SND_BACKGROUND_SCORES);
4306
4307     SetGameStatus(GAME_MODE_MAIN);
4308
4309     DrawMainMenu();
4310   }
4311   else if (button == MB_MENU_CHOICE)
4312   {
4313     PlaySound(SND_MENU_ITEM_SELECTING);
4314
4315     FadeSound(SND_BACKGROUND_SCORES);
4316
4317     SetGameStatus(GAME_MODE_MAIN);
4318
4319     DrawMainMenu();
4320   }
4321
4322   if (game_status == GAME_MODE_SCORES)
4323     PlayMenuSoundIfLoop();
4324 }
4325
4326
4327 /* ========================================================================= */
4328 /* setup screen functions                                                    */
4329 /* ========================================================================= */
4330
4331 static struct TokenInfo *setup_info;
4332 static int num_setup_info;      /* number of setup entries shown on screen */
4333 static int max_setup_info;      /* total number of setup entries in list */
4334
4335 static char *window_size_text;
4336 static char *scaling_type_text;
4337 static char *rendering_mode_text;
4338 static char *scroll_delay_text;
4339 static char *snapshot_mode_text;
4340 static char *game_speed_text;
4341 static char *graphics_set_name;
4342 static char *sounds_set_name;
4343 static char *music_set_name;
4344 static char *volume_simple_text;
4345 static char *volume_loops_text;
4346 static char *volume_music_text;
4347 static char *touch_controls_text;
4348 static char *move_distance_text;
4349 static char *drop_distance_text;
4350
4351 static void execSetupMain()
4352 {
4353   setup_mode = SETUP_MODE_MAIN;
4354
4355   DrawSetupScreen();
4356 }
4357
4358 static void execSetupGame_setGameSpeeds()
4359 {
4360   if (game_speeds == NULL)
4361   {
4362     int i;
4363
4364     for (i = 0; game_speeds_list[i].value != -1; i++)
4365     {
4366       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4367       char identifier[32], name[32];
4368       int value = game_speeds_list[i].value;
4369       char *text = game_speeds_list[i].text;
4370
4371       ti->node_top = &game_speeds;
4372       ti->sort_priority = 10000 - value;
4373
4374       sprintf(identifier, "%d", value);
4375       sprintf(name, "%s", text);
4376
4377       setString(&ti->identifier, identifier);
4378       setString(&ti->name, name);
4379       setString(&ti->name_sorting, name);
4380       setString(&ti->infotext, "Game Speed");
4381
4382       pushTreeInfo(&game_speeds, ti);
4383     }
4384
4385     /* sort game speed values to start with slowest game speed */
4386     sortTreeInfo(&game_speeds);
4387
4388     /* set current game speed to configured game speed value */
4389     game_speed_current =
4390       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
4391
4392     /* if that fails, set current game speed to reliable default value */
4393     if (game_speed_current == NULL)
4394       game_speed_current =
4395         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
4396
4397     /* if that also fails, set current game speed to first available speed */
4398     if (game_speed_current == NULL)
4399       game_speed_current = game_speeds;
4400   }
4401
4402   setup.game_frame_delay = atoi(game_speed_current->identifier);
4403
4404   /* needed for displaying game speed text instead of identifier */
4405   game_speed_text = game_speed_current->name;
4406 }
4407
4408 static void execSetupGame_setScrollDelays()
4409 {
4410   if (scroll_delays == NULL)
4411   {
4412     int i;
4413
4414     for (i = 0; scroll_delays_list[i].value != -1; i++)
4415     {
4416       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4417       char identifier[32], name[32];
4418       int value = scroll_delays_list[i].value;
4419       char *text = scroll_delays_list[i].text;
4420
4421       ti->node_top = &scroll_delays;
4422       ti->sort_priority = value;
4423
4424       sprintf(identifier, "%d", value);
4425       sprintf(name, "%s", text);
4426
4427       setString(&ti->identifier, identifier);
4428       setString(&ti->name, name);
4429       setString(&ti->name_sorting, name);
4430       setString(&ti->infotext, "Scroll Delay");
4431
4432       pushTreeInfo(&scroll_delays, ti);
4433     }
4434
4435     /* sort scroll delay values to start with lowest scroll delay value */
4436     sortTreeInfo(&scroll_delays);
4437
4438     /* set current scroll delay value to configured scroll delay value */
4439     scroll_delay_current =
4440       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
4441
4442     /* if that fails, set current scroll delay to reliable default value */
4443     if (scroll_delay_current == NULL)
4444       scroll_delay_current =
4445         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
4446
4447     /* if that also fails, set current scroll delay to first available value */
4448     if (scroll_delay_current == NULL)
4449       scroll_delay_current = scroll_delays;
4450   }
4451
4452   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
4453
4454   /* needed for displaying scroll delay text instead of identifier */
4455   scroll_delay_text = scroll_delay_current->name;
4456 }
4457
4458 static void execSetupGame_setSnapshotModes()
4459 {
4460   if (snapshot_modes == NULL)
4461   {
4462     int i;
4463
4464     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
4465     {
4466       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4467       char identifier[32], name[32];
4468       char *value = snapshot_modes_list[i].value;
4469       char *text = snapshot_modes_list[i].text;
4470
4471       ti->node_top = &snapshot_modes;
4472       ti->sort_priority = i;
4473
4474       sprintf(identifier, "%s", value);
4475       sprintf(name, "%s", text);
4476
4477       setString(&ti->identifier, identifier);
4478       setString(&ti->name, name);
4479       setString(&ti->name_sorting, name);
4480       setString(&ti->infotext, "Snapshot Mode");
4481
4482       pushTreeInfo(&snapshot_modes, ti);
4483     }
4484
4485     /* sort snapshot mode values to start with lowest snapshot mode value */
4486     sortTreeInfo(&snapshot_modes);
4487
4488     /* set current snapshot mode value to configured snapshot mode value */
4489     snapshot_mode_current =
4490       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
4491
4492     /* if that fails, set current snapshot mode to reliable default value */
4493     if (snapshot_mode_current == NULL)
4494       snapshot_mode_current =
4495         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
4496
4497     /* if that also fails, set current snapshot mode to first available value */
4498     if (snapshot_mode_current == NULL)
4499       snapshot_mode_current = snapshot_modes;
4500   }
4501
4502   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
4503
4504   /* needed for displaying snapshot mode text instead of identifier */
4505   snapshot_mode_text = snapshot_mode_current->name;
4506 }
4507
4508 static void execSetupGame()
4509 {
4510   execSetupGame_setGameSpeeds();
4511   execSetupGame_setScrollDelays();
4512   execSetupGame_setSnapshotModes();
4513
4514   setup_mode = SETUP_MODE_GAME;
4515
4516   DrawSetupScreen();
4517 }
4518
4519 static void execSetupChooseGameSpeed()
4520 {
4521   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
4522
4523   DrawSetupScreen();
4524 }
4525
4526 static void execSetupChooseScrollDelay()
4527 {
4528   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
4529
4530   DrawSetupScreen();
4531 }
4532
4533 static void execSetupChooseSnapshotMode()
4534 {
4535   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
4536
4537   DrawSetupScreen();
4538 }
4539
4540 static void execSetupEditor()
4541 {
4542   setup_mode = SETUP_MODE_EDITOR;
4543
4544   DrawSetupScreen();
4545 }
4546
4547 static void execSetupGraphics_setWindowSizes(boolean update_list)
4548 {
4549   if (window_sizes != NULL && update_list)
4550   {
4551     freeTreeInfo(window_sizes);
4552
4553     window_sizes = NULL;
4554   }
4555
4556   if (window_sizes == NULL)
4557   {
4558     boolean current_window_size_found = FALSE;
4559     int i;
4560
4561     for (i = 0; window_sizes_list[i].value != -1; i++)
4562     {
4563       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4564       char identifier[32], name[32];
4565       int value = window_sizes_list[i].value;
4566       char *text = window_sizes_list[i].text;
4567
4568       ti->node_top = &window_sizes;
4569       ti->sort_priority = value;
4570
4571       sprintf(identifier, "%d", value);
4572       sprintf(name, "%s", text);
4573
4574       setString(&ti->identifier, identifier);
4575       setString(&ti->name, name);
4576       setString(&ti->name_sorting, name);
4577       setString(&ti->infotext, "Window Scaling");
4578
4579       pushTreeInfo(&window_sizes, ti);
4580
4581       if (value == setup.window_scaling_percent)
4582         current_window_size_found = TRUE;
4583     }
4584
4585     if (!current_window_size_found)
4586     {
4587       // add entry for non-preset window scaling value
4588
4589       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4590       char identifier[32], name[32];
4591       int value = setup.window_scaling_percent;
4592
4593       ti->node_top = &window_sizes;
4594       ti->sort_priority = value;
4595
4596       sprintf(identifier, "%d", value);
4597       sprintf(name, "%d %% (Current)", value);
4598
4599       setString(&ti->identifier, identifier);
4600       setString(&ti->name, name);
4601       setString(&ti->name_sorting, name);
4602       setString(&ti->infotext, "Window Scaling");
4603
4604       pushTreeInfo(&window_sizes, ti);
4605     }
4606
4607     /* sort window size values to start with lowest window size value */
4608     sortTreeInfo(&window_sizes);
4609
4610     /* set current window size value to configured window size value */
4611     window_size_current =
4612       getTreeInfoFromIdentifier(window_sizes,
4613                                 i_to_a(setup.window_scaling_percent));
4614
4615     /* if that fails, set current window size to reliable default value */
4616     if (window_size_current == NULL)
4617       window_size_current =
4618         getTreeInfoFromIdentifier(window_sizes,
4619                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
4620
4621     /* if that also fails, set current window size to first available value */
4622     if (window_size_current == NULL)
4623       window_size_current = window_sizes;
4624   }
4625
4626   setup.window_scaling_percent = atoi(window_size_current->identifier);
4627
4628   /* needed for displaying window size text instead of identifier */
4629   window_size_text = window_size_current->name;
4630 }
4631
4632 static void execSetupGraphics_setScalingTypes()
4633 {
4634   if (scaling_types == NULL)
4635   {
4636     int i;
4637
4638     for (i = 0; scaling_types_list[i].value != NULL; i++)
4639     {
4640       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4641       char identifier[32], name[32];
4642       char *value = scaling_types_list[i].value;
4643       char *text = scaling_types_list[i].text;
4644
4645       ti->node_top = &scaling_types;
4646       ti->sort_priority = i;
4647
4648       sprintf(identifier, "%s", value);
4649       sprintf(name, "%s", text);
4650
4651       setString(&ti->identifier, identifier);
4652       setString(&ti->name, name);
4653       setString(&ti->name_sorting, name);
4654       setString(&ti->infotext, "Anti-Aliasing");
4655
4656       pushTreeInfo(&scaling_types, ti);
4657     }
4658
4659     /* sort scaling type values to start with lowest scaling type value */
4660     sortTreeInfo(&scaling_types);
4661
4662     /* set current scaling type value to configured scaling type value */
4663     scaling_type_current =
4664       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
4665
4666     /* if that fails, set current scaling type to reliable default value */
4667     if (scaling_type_current == NULL)
4668       scaling_type_current =
4669         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
4670
4671     /* if that also fails, set current scaling type to first available value */
4672     if (scaling_type_current == NULL)
4673       scaling_type_current = scaling_types;
4674   }
4675
4676   setup.window_scaling_quality = scaling_type_current->identifier;
4677
4678   /* needed for displaying scaling type text instead of identifier */
4679   scaling_type_text = scaling_type_current->name;
4680 }
4681
4682 static void execSetupGraphics_setRenderingModes()
4683 {
4684   if (rendering_modes == NULL)
4685   {
4686     int i;
4687
4688     for (i = 0; rendering_modes_list[i].value != NULL; i++)
4689     {
4690       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4691       char identifier[32], name[32];
4692       char *value = rendering_modes_list[i].value;
4693       char *text = rendering_modes_list[i].text;
4694
4695       ti->node_top = &rendering_modes;
4696       ti->sort_priority = i;
4697
4698       sprintf(identifier, "%s", value);
4699       sprintf(name, "%s", text);
4700
4701       setString(&ti->identifier, identifier);
4702       setString(&ti->name, name);
4703       setString(&ti->name_sorting, name);
4704       setString(&ti->infotext, "Special Rendering");
4705
4706       pushTreeInfo(&rendering_modes, ti);
4707     }
4708
4709     /* sort rendering mode values to start with lowest rendering mode value */
4710     sortTreeInfo(&rendering_modes);
4711
4712     /* set current rendering mode value to configured rendering mode value */
4713     rendering_mode_current =
4714       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
4715
4716     /* if that fails, set current rendering mode to reliable default value */
4717     if (rendering_mode_current == NULL)
4718       rendering_mode_current =
4719         getTreeInfoFromIdentifier(rendering_modes,
4720                                   STR_SPECIAL_RENDERING_DEFAULT);
4721
4722     /* if that also fails, set current rendering mode to first available one */
4723     if (rendering_mode_current == NULL)
4724       rendering_mode_current = rendering_modes;
4725   }
4726
4727   setup.screen_rendering_mode = rendering_mode_current->identifier;
4728
4729   /* needed for displaying rendering mode text instead of identifier */
4730   rendering_mode_text = rendering_mode_current->name;
4731 }
4732
4733 static void execSetupGraphics()
4734 {
4735   // update "setup.window_scaling_percent" from list selection
4736   // (in this case, window scaling was changed on setup screen)
4737   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
4738     execSetupGraphics_setWindowSizes(FALSE);
4739
4740   // update list selection from "setup.window_scaling_percent"
4741   // (window scaling may have changed by resizing the window)
4742   execSetupGraphics_setWindowSizes(TRUE);
4743
4744   execSetupGraphics_setScalingTypes();
4745   execSetupGraphics_setRenderingModes();
4746
4747   setup_mode = SETUP_MODE_GRAPHICS;
4748
4749   DrawSetupScreen();
4750
4751 #if defined(TARGET_SDL2)
4752   // window scaling may have changed at this point
4753   ToggleFullscreenOrChangeWindowScalingIfNeeded();
4754
4755   // window scaling quality may have changed at this point
4756   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
4757     SDLSetWindowScalingQuality(setup.window_scaling_quality);
4758
4759   // screen rendering mode may have changed at this point
4760   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
4761 #endif
4762 }
4763
4764 #if defined(TARGET_SDL2) && !defined(PLATFORM_ANDROID)
4765 static void execSetupChooseWindowSize()
4766 {
4767   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
4768
4769   DrawSetupScreen();
4770 }
4771
4772 static void execSetupChooseScalingType()
4773 {
4774   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
4775
4776   DrawSetupScreen();
4777 }
4778
4779 static void execSetupChooseRenderingMode()
4780 {
4781   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
4782
4783   DrawSetupScreen();
4784 }
4785 #endif
4786
4787 static void execSetupChooseVolumeSimple()
4788 {
4789   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
4790
4791   DrawSetupScreen();
4792 }
4793
4794 static void execSetupChooseVolumeLoops()
4795 {
4796   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
4797
4798   DrawSetupScreen();
4799 }
4800
4801 static void execSetupChooseVolumeMusic()
4802 {
4803   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
4804
4805   DrawSetupScreen();
4806 }
4807
4808 static void execSetupSound()
4809 {
4810   if (volumes_simple == NULL)
4811   {
4812     boolean current_volume_simple_found = FALSE;
4813     int i;
4814
4815     for (i = 0; volumes_list[i].value != -1; i++)
4816     {
4817       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4818       char identifier[32], name[32];
4819       int value = volumes_list[i].value;
4820       char *text = volumes_list[i].text;
4821
4822       ti->node_top = &volumes_simple;
4823       ti->sort_priority = value;
4824
4825       sprintf(identifier, "%d", value);
4826       sprintf(name, "%s", text);
4827
4828       setString(&ti->identifier, identifier);
4829       setString(&ti->name, name);
4830       setString(&ti->name_sorting, name);
4831       setString(&ti->infotext, "Sound Volume");
4832
4833       pushTreeInfo(&volumes_simple, ti);
4834
4835       if (value == setup.volume_simple)
4836         current_volume_simple_found = TRUE;
4837     }
4838
4839     if (!current_volume_simple_found)
4840     {
4841       // add entry for non-preset volume value
4842
4843       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4844       char identifier[32], name[32];
4845       int value = setup.volume_simple;
4846
4847       ti->node_top = &volumes_simple;
4848       ti->sort_priority = value;
4849
4850       sprintf(identifier, "%d", value);
4851       sprintf(name, "%d %% (Current)", value);
4852
4853       setString(&ti->identifier, identifier);
4854       setString(&ti->name, name);
4855       setString(&ti->name_sorting, name);
4856       setString(&ti->infotext, "Sound Volume");
4857
4858       pushTreeInfo(&volumes_simple, ti);
4859     }
4860
4861     /* sort volume values to start with lowest volume value */
4862     sortTreeInfo(&volumes_simple);
4863
4864     /* set current volume value to configured volume value */
4865     volume_simple_current =
4866       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
4867
4868     /* if that fails, set current volume to reliable default value */
4869     if (volume_simple_current == NULL)
4870       volume_simple_current =
4871         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
4872
4873     /* if that also fails, set current volume to first available value */
4874     if (volume_simple_current == NULL)
4875       volume_simple_current = volumes_simple;
4876   }
4877
4878   if (volumes_loops == NULL)
4879   {
4880     boolean current_volume_loops_found = FALSE;
4881     int i;
4882
4883     for (i = 0; volumes_list[i].value != -1; i++)
4884     {
4885       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4886       char identifier[32], name[32];
4887       int value = volumes_list[i].value;
4888       char *text = volumes_list[i].text;
4889
4890       ti->node_top = &volumes_loops;
4891       ti->sort_priority = value;
4892
4893       sprintf(identifier, "%d", value);
4894       sprintf(name, "%s", text);
4895
4896       setString(&ti->identifier, identifier);
4897       setString(&ti->name, name);
4898       setString(&ti->name_sorting, name);
4899       setString(&ti->infotext, "Loops Volume");
4900
4901       pushTreeInfo(&volumes_loops, ti);
4902
4903       if (value == setup.volume_loops)
4904         current_volume_loops_found = TRUE;
4905     }
4906
4907     if (!current_volume_loops_found)
4908     {
4909       // add entry for non-preset volume value
4910
4911       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4912       char identifier[32], name[32];
4913       int value = setup.volume_loops;
4914
4915       ti->node_top = &volumes_loops;
4916       ti->sort_priority = value;
4917
4918       sprintf(identifier, "%d", value);
4919       sprintf(name, "%d %% (Current)", value);
4920
4921       setString(&ti->identifier, identifier);
4922       setString(&ti->name, name);
4923       setString(&ti->name_sorting, name);
4924       setString(&ti->infotext, "Loops Volume");
4925
4926       pushTreeInfo(&volumes_loops, ti);
4927     }
4928
4929     /* sort volume values to start with lowest volume value */
4930     sortTreeInfo(&volumes_loops);
4931
4932     /* set current volume value to configured volume value */
4933     volume_loops_current =
4934       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
4935
4936     /* if that fails, set current volume to reliable default value */
4937     if (volume_loops_current == NULL)
4938       volume_loops_current =
4939         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
4940
4941     /* if that also fails, set current volume to first available value */
4942     if (volume_loops_current == NULL)
4943       volume_loops_current = volumes_loops;
4944   }
4945
4946   if (volumes_music == NULL)
4947   {
4948     boolean current_volume_music_found = FALSE;
4949     int i;
4950
4951     for (i = 0; volumes_list[i].value != -1; i++)
4952     {
4953       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4954       char identifier[32], name[32];
4955       int value = volumes_list[i].value;
4956       char *text = volumes_list[i].text;
4957
4958       ti->node_top = &volumes_music;
4959       ti->sort_priority = value;
4960
4961       sprintf(identifier, "%d", value);
4962       sprintf(name, "%s", text);
4963
4964       setString(&ti->identifier, identifier);
4965       setString(&ti->name, name);
4966       setString(&ti->name_sorting, name);
4967       setString(&ti->infotext, "Music Volume");
4968
4969       pushTreeInfo(&volumes_music, ti);
4970
4971       if (value == setup.volume_music)
4972         current_volume_music_found = TRUE;
4973     }
4974
4975     if (!current_volume_music_found)
4976     {
4977       // add entry for non-preset volume value
4978
4979       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4980       char identifier[32], name[32];
4981       int value = setup.volume_music;
4982
4983       ti->node_top = &volumes_music;
4984       ti->sort_priority = value;
4985
4986       sprintf(identifier, "%d", value);
4987       sprintf(name, "%d %% (Current)", value);
4988
4989       setString(&ti->identifier, identifier);
4990       setString(&ti->name, name);
4991       setString(&ti->name_sorting, name);
4992       setString(&ti->infotext, "Music Volume");
4993
4994       pushTreeInfo(&volumes_music, ti);
4995     }
4996
4997     /* sort volume values to start with lowest volume value */
4998     sortTreeInfo(&volumes_music);
4999
5000     /* set current volume value to configured volume value */
5001     volume_music_current =
5002       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
5003
5004     /* if that fails, set current volume to reliable default value */
5005     if (volume_music_current == NULL)
5006       volume_music_current =
5007         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
5008
5009     /* if that also fails, set current volume to first available value */
5010     if (volume_music_current == NULL)
5011       volume_music_current = volumes_music;
5012   }
5013
5014   setup.volume_simple = atoi(volume_simple_current->identifier);
5015   setup.volume_loops  = atoi(volume_loops_current->identifier);
5016   setup.volume_music  = atoi(volume_music_current->identifier);
5017
5018   /* needed for displaying volume text instead of identifier */
5019   volume_simple_text = volume_simple_current->name;
5020   volume_loops_text = volume_loops_current->name;
5021   volume_music_text = volume_music_current->name;
5022
5023   setup_mode = SETUP_MODE_SOUND;
5024
5025   DrawSetupScreen();
5026 }
5027
5028 static void execSetupChooseTouchControls()
5029 {
5030   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
5031
5032   DrawSetupScreen();
5033 }
5034
5035 static void execSetupChooseMoveDistance()
5036 {
5037   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
5038
5039   DrawSetupScreen();
5040 }
5041
5042 static void execSetupChooseDropDistance()
5043 {
5044   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
5045
5046   DrawSetupScreen();
5047 }
5048
5049 static void execSetupTouch()
5050 {
5051   if (touch_controls == NULL)
5052   {
5053     int i;
5054
5055     for (i = 0; touch_controls_list[i].value != NULL; i++)
5056     {
5057       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5058       char identifier[32], name[32];
5059       char *value = touch_controls_list[i].value;
5060       char *text = touch_controls_list[i].text;
5061
5062       ti->node_top = &touch_controls;
5063       ti->sort_priority = i;
5064
5065       sprintf(identifier, "%s", value);
5066       sprintf(name, "%s", text);
5067
5068       setString(&ti->identifier, identifier);
5069       setString(&ti->name, name);
5070       setString(&ti->name_sorting, name);
5071       setString(&ti->infotext, "Control Type");
5072
5073       pushTreeInfo(&touch_controls, ti);
5074     }
5075
5076     /* sort touch control values to start with lowest touch control value */
5077     sortTreeInfo(&touch_controls);
5078
5079     /* set current touch control value to configured touch control value */
5080     touch_control_current =
5081       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
5082
5083     /* if that fails, set current touch control to reliable default value */
5084     if (touch_control_current == NULL)
5085       touch_control_current =
5086         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
5087
5088     /* if that also fails, set current touch control to first available value */
5089     if (touch_control_current == NULL)
5090       touch_control_current = touch_controls;
5091   }
5092
5093   if (move_distances == NULL)
5094   {
5095     int i;
5096
5097     for (i = 0; distances_list[i].value != -1; i++)
5098     {
5099       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5100       char identifier[32], name[32];
5101       int value = distances_list[i].value;
5102       char *text = distances_list[i].text;
5103
5104       ti->node_top = &move_distances;
5105       ti->sort_priority = value;
5106
5107       sprintf(identifier, "%d", value);
5108       sprintf(name, "%s", text);
5109
5110       setString(&ti->identifier, identifier);
5111       setString(&ti->name, name);
5112       setString(&ti->name_sorting, name);
5113       setString(&ti->infotext, "Move Distance");
5114
5115       pushTreeInfo(&move_distances, ti);
5116     }
5117
5118     /* sort distance values to start with lowest distance value */
5119     sortTreeInfo(&move_distances);
5120
5121     /* set current distance value to configured distance value */
5122     move_distance_current =
5123       getTreeInfoFromIdentifier(move_distances,
5124                                 i_to_a(setup.touch.move_distance));
5125
5126     /* if that fails, set current distance to reliable default value */
5127     if (move_distance_current == NULL)
5128       move_distance_current =
5129         getTreeInfoFromIdentifier(move_distances, i_to_a(1));
5130
5131     /* if that also fails, set current distance to first available value */
5132     if (move_distance_current == NULL)
5133       move_distance_current = move_distances;
5134   }
5135
5136   if (drop_distances == NULL)
5137   {
5138     int i;
5139
5140     for (i = 0; distances_list[i].value != -1; i++)
5141     {
5142       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5143       char identifier[32], name[32];
5144       int value = distances_list[i].value;
5145       char *text = distances_list[i].text;
5146
5147       ti->node_top = &drop_distances;
5148       ti->sort_priority = value;
5149
5150       sprintf(identifier, "%d", value);
5151       sprintf(name, "%s", text);
5152
5153       setString(&ti->identifier, identifier);
5154       setString(&ti->name, name);
5155       setString(&ti->name_sorting, name);
5156       setString(&ti->infotext, "Drop Distance");
5157
5158       pushTreeInfo(&drop_distances, ti);
5159     }
5160
5161     /* sort distance values to start with lowest distance value */
5162     sortTreeInfo(&drop_distances);
5163
5164     /* set current distance value to configured distance value */
5165     drop_distance_current =
5166       getTreeInfoFromIdentifier(drop_distances,
5167                                 i_to_a(setup.touch.drop_distance));
5168
5169     /* if that fails, set current distance to reliable default value */
5170     if (drop_distance_current == NULL)
5171       drop_distance_current =
5172         getTreeInfoFromIdentifier(drop_distances, i_to_a(1));
5173
5174     /* if that also fails, set current distance to first available value */
5175     if (drop_distance_current == NULL)
5176       drop_distance_current = drop_distances;
5177   }
5178
5179   setup.touch.control_type = touch_control_current->identifier;
5180   setup.touch.move_distance = atoi(move_distance_current->identifier);
5181   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
5182
5183   /* needed for displaying volume text instead of identifier */
5184   touch_controls_text = touch_control_current->name;
5185   move_distance_text = move_distance_current->name;
5186   drop_distance_text = drop_distance_current->name;
5187
5188   setup_mode = SETUP_MODE_TOUCH;
5189
5190   DrawSetupScreen();
5191 }
5192
5193 static void execSetupArtwork()
5194 {
5195 #if 0
5196   printf("::: '%s', '%s', '%s'\n",
5197          artwork.gfx_current->subdir,
5198          artwork.gfx_current->fullpath,
5199          artwork.gfx_current->basepath);
5200 #endif
5201
5202   setup.graphics_set = artwork.gfx_current->identifier;
5203   setup.sounds_set = artwork.snd_current->identifier;
5204   setup.music_set = artwork.mus_current->identifier;
5205
5206   /* needed if last screen (setup choice) changed graphics, sounds or music */
5207   ReloadCustomArtwork(0);
5208
5209   /* needed for displaying artwork name instead of artwork identifier */
5210   graphics_set_name = artwork.gfx_current->name;
5211   sounds_set_name = artwork.snd_current->name;
5212   music_set_name = artwork.mus_current->name;
5213
5214   setup_mode = SETUP_MODE_ARTWORK;
5215
5216   DrawSetupScreen();
5217 }
5218
5219 static void execSetupChooseGraphics()
5220 {
5221   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
5222
5223   DrawSetupScreen();
5224 }
5225
5226 static void execSetupChooseSounds()
5227 {
5228   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
5229
5230   DrawSetupScreen();
5231 }
5232
5233 static void execSetupChooseMusic()
5234 {
5235   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
5236
5237   DrawSetupScreen();
5238 }
5239
5240 static void execSetupInput()
5241 {
5242   setup_mode = SETUP_MODE_INPUT;
5243
5244   DrawSetupScreen();
5245 }
5246
5247 static void execSetupShortcuts()
5248 {
5249   setup_mode = SETUP_MODE_SHORTCUTS;
5250
5251   DrawSetupScreen();
5252 }
5253
5254 static void execSetupShortcuts1()
5255 {
5256   setup_mode = SETUP_MODE_SHORTCUTS_1;
5257
5258   DrawSetupScreen();
5259 }
5260
5261 static void execSetupShortcuts2()
5262 {
5263   setup_mode = SETUP_MODE_SHORTCUTS_2;
5264
5265   DrawSetupScreen();
5266 }
5267
5268 static void execSetupShortcuts3()
5269 {
5270   setup_mode = SETUP_MODE_SHORTCUTS_3;
5271
5272   DrawSetupScreen();
5273 }
5274
5275 static void execSetupShortcuts4()
5276 {
5277   setup_mode = SETUP_MODE_SHORTCUTS_4;
5278
5279   DrawSetupScreen();
5280 }
5281
5282 static void execSetupShortcuts5()
5283 {
5284   setup_mode = SETUP_MODE_SHORTCUTS_5;
5285
5286   DrawSetupScreen();
5287 }
5288
5289 static void execExitSetup()
5290 {
5291   SetGameStatus(GAME_MODE_MAIN);
5292
5293   DrawMainMenu();
5294 }
5295
5296 static void execSaveAndExitSetup()
5297 {
5298   SaveSetup();
5299   execExitSetup();
5300 }
5301
5302 static struct TokenInfo setup_info_main[] =
5303 {
5304   { TYPE_ENTER_MENU,    execSetupGame,          "Game & Menu"           },
5305   { TYPE_ENTER_MENU,    execSetupEditor,        "Editor"                },
5306   { TYPE_ENTER_MENU,    execSetupGraphics,      "Graphics"              },
5307   { TYPE_ENTER_MENU,    execSetupSound,         "Sound & Music"         },
5308   { TYPE_ENTER_MENU,    execSetupArtwork,       "Custom Artwork"        },
5309   { TYPE_ENTER_MENU,    execSetupInput,         "Input Devices"         },
5310   { TYPE_ENTER_MENU,    execSetupTouch,         "Touch Controls"        },
5311   { TYPE_ENTER_MENU,    execSetupShortcuts,     "Key Shortcuts"         },
5312   { TYPE_EMPTY,         NULL,                   ""                      },
5313   { TYPE_LEAVE_MENU,    execExitSetup,          "Exit"                  },
5314   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   "Save and Exit"         },
5315
5316   { 0,                  NULL,                   NULL                    }
5317 };
5318
5319 static struct TokenInfo setup_info_game[] =
5320 {
5321   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
5322   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
5323   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
5324   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
5325   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
5326   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
5327   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
5328   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
5329   { TYPE_STRING,        &game_speed_text,       ""                      },
5330 #if 1
5331   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
5332   { TYPE_STRING,        &scroll_delay_text,     ""                      },
5333 #endif
5334   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
5335   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
5336   { TYPE_SWITCH,        &setup.show_snapshot_buttons,"Show Snapshot Buttons:" },
5337   { TYPE_EMPTY,         NULL,                   ""                      },
5338   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5339
5340   { 0,                  NULL,                   NULL                    }
5341 };
5342
5343 static struct TokenInfo setup_info_editor[] =
5344 {
5345 #if 0
5346   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
5347   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
5348   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
5349   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
5350   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
5351   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
5352   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
5353   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
5354   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
5355   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
5356 #endif
5357   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
5358   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
5359 #if 0
5360   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
5361 #endif
5362   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
5363   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
5364   { TYPE_EMPTY,         NULL,                   ""                      },
5365 #if 0
5366   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
5367   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
5368   { TYPE_EMPTY,         NULL,                   ""                      },
5369 #endif
5370   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
5371   { TYPE_EMPTY,         NULL,                   ""                      },
5372   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5373
5374   { 0,                  NULL,                   NULL                    }
5375 };
5376
5377 static struct TokenInfo setup_info_graphics[] =
5378 {
5379 #if defined(TARGET_SDL2) && !defined(PLATFORM_ANDROID)
5380   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
5381   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
5382   { TYPE_STRING,        &window_size_text,      ""                      },
5383   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
5384   { TYPE_STRING,        &scaling_type_text,     ""                      },
5385   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
5386   { TYPE_STRING,        &rendering_mode_text,   ""                      },
5387 #endif
5388 #if 0
5389   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
5390   { TYPE_STRING,        &scroll_delay_text,     ""                      },
5391 #endif
5392   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
5393   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
5394   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
5395   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
5396   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
5397   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics,"EMC graphics preference:" },
5398   { TYPE_SWITCH, &setup.sp_show_border_elements,"Supaplex Border Elements:" },
5399   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
5400   { TYPE_EMPTY,         NULL,                   ""                      },
5401   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5402
5403   { 0,                  NULL,                   NULL                    }
5404 };
5405
5406 static struct TokenInfo setup_info_sound[] =
5407 {
5408   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
5409   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
5410   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
5411   { TYPE_EMPTY,         NULL,                   ""                      },
5412   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
5413   { TYPE_STRING,        &volume_simple_text,    ""                      },
5414   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
5415   { TYPE_STRING,        &volume_loops_text,     ""                      },
5416   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
5417   { TYPE_STRING,        &volume_music_text,     ""                      },
5418   { TYPE_EMPTY,         NULL,                   ""                      },
5419   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5420
5421   { 0,                  NULL,                   NULL                    }
5422 };
5423
5424 static struct TokenInfo setup_info_artwork[] =
5425 {
5426   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
5427   { TYPE_STRING,        &graphics_set_name,     ""                      },
5428   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
5429   { TYPE_STRING,        &sounds_set_name,       ""                      },
5430   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
5431   { TYPE_STRING,        &music_set_name,        ""                      },
5432   { TYPE_EMPTY,         NULL,                   ""                      },
5433   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
5434   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
5435   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
5436   { TYPE_EMPTY,         NULL,                   ""                      },
5437   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5438
5439   { 0,                  NULL,                   NULL                    }
5440 };
5441
5442 static struct TokenInfo setup_info_input[] =
5443 {
5444   { TYPE_SWITCH,        NULL,                   "Player:"               },
5445   { TYPE_SWITCH,        NULL,                   "Device:"               },
5446   { TYPE_SWITCH,        NULL,                   ""                      },
5447   { TYPE_EMPTY,         NULL,                   ""                      },
5448   { TYPE_EMPTY,         NULL,                   ""                      },
5449   { TYPE_EMPTY,         NULL,                   ""                      },
5450   { TYPE_EMPTY,         NULL,                   ""                      },
5451   { TYPE_EMPTY,         NULL,                   ""                      },
5452   { TYPE_EMPTY,         NULL,                   ""                      },
5453   { TYPE_EMPTY,         NULL,                   ""                      },
5454   { TYPE_EMPTY,         NULL,                   ""                      },
5455   { TYPE_EMPTY,         NULL,                   ""                      },
5456   { TYPE_EMPTY,         NULL,                   ""                      },
5457   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5458
5459   { 0,                  NULL,                   NULL                    }
5460 };
5461
5462 static struct TokenInfo setup_info_touch[] =
5463 {
5464   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
5465   { TYPE_STRING,        &touch_controls_text,   ""                      },
5466   { TYPE_EMPTY,         NULL,                   ""                      },
5467   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5468
5469   { 0,                  NULL,                   NULL                    }
5470 };
5471
5472 static struct TokenInfo setup_info_touch_wipe_gestures[] =
5473 {
5474   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
5475   { TYPE_STRING,        &touch_controls_text,   ""                      },
5476   { TYPE_EMPTY,         NULL,                   ""                      },
5477   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
5478   { TYPE_STRING,        &move_distance_text,    ""                      },
5479   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
5480   { TYPE_STRING,        &drop_distance_text,    ""                      },
5481   { TYPE_EMPTY,         NULL,                   ""                      },
5482   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5483
5484   { 0,                  NULL,                   NULL                    }
5485 };
5486
5487 static struct TokenInfo setup_info_shortcuts[] =
5488 {
5489   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
5490   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
5491   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
5492   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
5493   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
5494   { TYPE_EMPTY,         NULL,                   ""                      },
5495   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5496
5497   { 0,                  NULL,                   NULL                    }
5498 };
5499
5500 static struct TokenInfo setup_info_shortcuts_1[] =
5501 {
5502   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
5503   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
5504   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
5505   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
5506   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
5507   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
5508   { TYPE_EMPTY,         NULL,                   ""                      },
5509   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
5510   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
5511   { TYPE_EMPTY,         NULL,                   ""                      },
5512   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5513
5514   { 0,                  NULL,                   NULL                    }
5515 };
5516
5517 static struct TokenInfo setup_info_shortcuts_2[] =
5518 {
5519   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
5520   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
5521   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
5522   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
5523   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
5524   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
5525   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
5526   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
5527   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
5528   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
5529   { TYPE_EMPTY,         NULL,                   ""                      },
5530   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5531
5532   { 0,                  NULL,                   NULL                    }
5533 };
5534
5535 static struct TokenInfo setup_info_shortcuts_3[] =
5536 {
5537   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
5538   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
5539   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
5540   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
5541   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
5542   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
5543   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
5544   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
5545   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
5546   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
5547   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
5548   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
5549   { TYPE_EMPTY,         NULL,                   ""                      },
5550   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5551
5552   { 0,                  NULL,                   NULL                    }
5553 };
5554
5555 static struct TokenInfo setup_info_shortcuts_4[] =
5556 {
5557   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
5558   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
5559   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
5560   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
5561   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
5562   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
5563   { TYPE_EMPTY,         NULL,                   ""                      },
5564   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5565
5566   { 0,                  NULL,                   NULL                    }
5567 };
5568
5569 static struct TokenInfo setup_info_shortcuts_5[] =
5570 {
5571   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
5572   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
5573   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
5574   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
5575   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
5576   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
5577   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
5578   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
5579   { TYPE_EMPTY,         NULL,                   ""                      },
5580   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5581
5582   { 0,                  NULL,                   NULL                    }
5583 };
5584
5585 static Key getSetupKey()
5586 {
5587   Key key = KSYM_UNDEFINED;
5588   boolean got_key_event = FALSE;
5589
5590   while (!got_key_event)
5591   {
5592     if (PendingEvent())         /* got event */
5593     {
5594       Event event;
5595
5596       NextEvent(&event);
5597
5598       switch (event.type)
5599       {
5600         case EVENT_KEYPRESS:
5601           {
5602             key = GetEventKey((KeyEvent *)&event, TRUE);
5603
5604             /* press 'Escape' or 'Enter' to keep the existing key binding */
5605             if (key == KSYM_Escape || key == KSYM_Return)
5606               key = KSYM_UNDEFINED;     /* keep old value */
5607
5608             got_key_event = TRUE;
5609           }
5610           break;
5611
5612         case EVENT_KEYRELEASE:
5613           key_joystick_mapping = 0;
5614           break;
5615
5616         default:
5617           HandleOtherEvents(&event);
5618           break;
5619       }
5620     }
5621
5622     BackToFront();
5623   }
5624
5625   return key;
5626 }
5627
5628 static int getSetupValueFont(int type, void *value)
5629 {
5630   if (type & TYPE_KEY)
5631     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
5632   else if (type & TYPE_STRING)
5633     return FONT_VALUE_2;
5634   else if (type & TYPE_ECS_AGA)
5635     return FONT_VALUE_1;
5636   else if (type & TYPE_BOOLEAN_STYLE)
5637     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
5638   else if (type & TYPE_YES_NO_AUTO)
5639     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
5640             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
5641   else
5642     return FONT_VALUE_1;
5643 }
5644
5645 static int getSetupValueFontNarrow(int type, int font_nr)
5646 {
5647   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
5648           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
5649           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
5650           font_nr);
5651 }
5652
5653 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
5654 {
5655   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
5656   struct TokenInfo *si = &setup_info[si_pos];
5657   boolean font_draw_xoffset_modified = FALSE;
5658   boolean scrollbar_needed = (num_setup_info < max_setup_info);
5659   int font_draw_xoffset_old = -1;
5660   int xoffset = (scrollbar_needed ? -1 : 0);
5661   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
5662   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
5663   int xpos = menu_screen_value_xpos;
5664   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
5665   int startx = mSX + xpos * 32;
5666   int starty = mSY + ypos * 32;
5667   int font_nr, font_nr_default, font_width_default;
5668   int type = si->type;
5669   void *value = si->value;
5670   char *value_string = getSetupValue(type, value);
5671   int i;
5672
5673   if (value_string == NULL)
5674     return;
5675
5676   if (type & TYPE_KEY)
5677   {
5678     xpos = MENU_SCREEN_START_XPOS;
5679
5680     if (type & TYPE_QUERY)
5681       value_string = "<press key>";
5682   }
5683   else if (type & TYPE_STRING)
5684   {
5685     int max_value_len = (SCR_FIELDX - 2) * 2;
5686
5687     xpos = MENU_SCREEN_START_XPOS;
5688
5689     if (strlen(value_string) > max_value_len)
5690       value_string[max_value_len] = '\0';
5691   }
5692   else if (type & TYPE_YES_NO_AUTO)
5693   {
5694     xpos = menu_screen_value_xpos - 1;
5695   }
5696
5697   startx = mSX + xpos * 32;
5698   starty = mSY + ypos * 32;
5699   font_nr_default = getSetupValueFont(type, value);
5700   font_width_default = getFontWidth(font_nr_default);
5701
5702   font_nr = font_nr_default;
5703
5704   // special check if right-side setup values moved left due to scrollbar
5705   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
5706   {
5707     int max_menu_text_length = 26;      // maximum text length for classic menu
5708     int font_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
5709     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
5710     int text_font_nr = getMenuTextFont(FONT_MENU_2);
5711     int text_font_xoffset = getFontBitmapInfo(text_font_nr)->draw_xoffset;
5712     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
5713
5714     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
5715     {
5716       xpos += 1;
5717       startx = mSX + xpos * 32;
5718
5719       font_nr = getSetupValueFontNarrow(type, font_nr);
5720     }
5721   }
5722
5723   /* downward compatibility correction for Juergen Bonhagen's menu settings */
5724   if (setup_mode != SETUP_MODE_INPUT)
5725   {
5726     int max_menu_text_length_big = (menu_screen_value_xpos -
5727                                     MENU_SCREEN_START_XPOS);
5728     int max_menu_text_length_medium = max_menu_text_length_big * 2;
5729     int check_font_nr = FONT_OPTION_ON; /* known font that needs correction */
5730     int font1_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
5731     int font2_xoffset = getFontBitmapInfo(check_font_nr)->draw_xoffset;
5732     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
5733     int text_font_nr = getMenuTextFont(FONT_MENU_2);
5734     int text_font_xoffset = getFontBitmapInfo(text_font_nr)->draw_xoffset;
5735     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
5736     boolean correct_font_draw_xoffset = FALSE;
5737
5738     if (xpos == MENU_SCREEN_START_XPOS &&
5739         startx + font1_xoffset < text_startx + text_font_xoffset)
5740       correct_font_draw_xoffset = TRUE;
5741
5742     if (xpos == menu_screen_value_xpos &&
5743         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
5744       correct_font_draw_xoffset = TRUE;
5745
5746     /* check if setup value would overlap with setup text when printed */
5747     /* (this can happen for extreme/wrong values for font draw offset) */
5748     if (correct_font_draw_xoffset)
5749     {
5750       font_draw_xoffset_old = getFontBitmapInfo(font_nr)->draw_xoffset;
5751       font_draw_xoffset_modified = TRUE;
5752
5753       if (type & TYPE_KEY)
5754         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
5755       else if (!(type & TYPE_STRING))
5756         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
5757           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
5758     }
5759   }
5760
5761   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
5762     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
5763
5764   DrawText(startx, starty, value_string, font_nr);
5765
5766   if (font_draw_xoffset_modified)
5767     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
5768 }
5769
5770 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
5771 {
5772   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
5773   struct TokenInfo *si = &setup_info[si_pos];
5774
5775   if (si->type & TYPE_BOOLEAN_STYLE)
5776   {
5777     *(boolean *)si->value ^= TRUE;
5778   }
5779   else if (si->type & TYPE_YES_NO_AUTO)
5780   {
5781     *(int *)si->value =
5782       (dx == -1 ?
5783        (*(int *)si->value == AUTO ? TRUE :
5784         *(int *)si->value == TRUE ? FALSE : AUTO) :
5785        (*(int *)si->value == TRUE ? AUTO :
5786         *(int *)si->value == AUTO ? FALSE : TRUE));
5787   }
5788   else if (si->type & TYPE_KEY)
5789   {
5790     Key key;
5791
5792     si->type |= TYPE_QUERY;
5793     drawSetupValue(screen_pos, setup_info_pos_raw);
5794     si->type &= ~TYPE_QUERY;
5795
5796     key = getSetupKey();
5797     if (key != KSYM_UNDEFINED)
5798       *(Key *)si->value = key;
5799   }
5800
5801   drawSetupValue(screen_pos, setup_info_pos_raw);
5802
5803   // fullscreen state may have changed at this point
5804   if (si->value == &setup.fullscreen)
5805     ToggleFullscreenOrChangeWindowScalingIfNeeded();
5806 }
5807
5808 static void DrawSetupScreen_Generic()
5809 {
5810   int fade_mask = REDRAW_FIELD;
5811   boolean redraw_all = FALSE;
5812   char *title_string = NULL;
5813   int i;
5814
5815   if (CheckIfGlobalBorderHasChanged())
5816     fade_mask = REDRAW_ALL;
5817
5818   UnmapAllGadgets();
5819   FadeMenuSoundsAndMusic();
5820
5821   FreeScreenGadgets();
5822   CreateScreenGadgets();
5823
5824   if (redraw_mask & REDRAW_ALL)
5825     redraw_all = TRUE;
5826
5827   FadeOut(fade_mask);
5828
5829   /* needed if different viewport properties defined for setup screen */
5830   ChangeViewportPropertiesIfNeeded();
5831
5832   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
5833
5834   ClearField();
5835
5836   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
5837
5838   if (setup_mode == SETUP_MODE_MAIN)
5839   {
5840     setup_info = setup_info_main;
5841     title_string = "Setup";
5842   }
5843   else if (setup_mode == SETUP_MODE_GAME)
5844   {
5845     setup_info = setup_info_game;
5846     title_string = "Setup Game";
5847   }
5848   else if (setup_mode == SETUP_MODE_EDITOR)
5849   {
5850     setup_info = setup_info_editor;
5851     title_string = "Setup Editor";
5852   }
5853   else if (setup_mode == SETUP_MODE_GRAPHICS)
5854   {
5855     setup_info = setup_info_graphics;
5856     title_string = "Setup Graphics";
5857   }
5858   else if (setup_mode == SETUP_MODE_SOUND)
5859   {
5860     setup_info = setup_info_sound;
5861     title_string = "Setup Sound";
5862   }
5863   else if (setup_mode == SETUP_MODE_ARTWORK)
5864   {
5865     setup_info = setup_info_artwork;
5866     title_string = "Custom Artwork";
5867   }
5868   else if (setup_mode == SETUP_MODE_TOUCH)
5869   {
5870     setup_info = setup_info_touch;
5871     title_string = "Setup Touch Ctrls";
5872
5873     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
5874       setup_info = setup_info_touch_wipe_gestures;
5875   }
5876   else if (setup_mode == SETUP_MODE_SHORTCUTS)
5877   {
5878     setup_info = setup_info_shortcuts;
5879     title_string = "Setup Shortcuts";
5880   }
5881   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
5882   {
5883     setup_info = setup_info_shortcuts_1;
5884     title_string = "Setup Shortcuts";
5885   }
5886   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
5887   {
5888     setup_info = setup_info_shortcuts_2;
5889     title_string = "Setup Shortcuts";
5890   }
5891   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
5892   {
5893     setup_info = setup_info_shortcuts_3;
5894     title_string = "Setup Shortcuts";
5895   }
5896   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
5897   {
5898     setup_info = setup_info_shortcuts_4;
5899     title_string = "Setup Shortcuts";
5900   }
5901   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
5902   {
5903     setup_info = setup_info_shortcuts_5;
5904     title_string = "Setup Shortcuts";
5905   }
5906
5907   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
5908
5909   // determine maximal number of setup entries that can be displayed on screen
5910   num_setup_info = 0;
5911   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
5912     num_setup_info++;
5913
5914   // determine maximal number of setup entries available for this setup screen
5915   max_setup_info = 0;
5916   for (i = 0; setup_info[i].type != 0; i++)
5917     max_setup_info++;
5918
5919   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
5920
5921   MapScreenGadgets(max_setup_info);
5922
5923   if (redraw_all)
5924     redraw_mask = fade_mask = REDRAW_ALL;
5925
5926   DrawMaskedBorder(fade_mask);
5927
5928   FadeIn(fade_mask);
5929 }
5930
5931 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
5932 {
5933   menu_info = setup_info;
5934
5935   HandleMenuScreen(mx, my, dx, dy, button,
5936                    setup_mode, num_setup_info, max_setup_info);
5937 }
5938
5939 void DrawSetupScreen_Input()
5940 {
5941   int i;
5942
5943   FadeOut(REDRAW_FIELD);
5944
5945   ClearField();
5946
5947   setup_info = setup_info_input;
5948
5949   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Setup Input");
5950
5951   for (i = 0; setup_info[i].type != 0 && i < MAX_MENU_ENTRIES_ON_SCREEN; i++)
5952   {
5953     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
5954       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
5955     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
5956       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
5957     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
5958       initCursor(i, IMG_MENU_BUTTON);
5959
5960     DrawCursorAndText_Setup(i, -1, FALSE);
5961   }
5962
5963   /* create gadgets for setup input menu screen */
5964   FreeScreenGadgets();
5965   CreateScreenGadgets();
5966
5967   /* map gadgets for setup input menu screen */
5968   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
5969
5970   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
5971
5972   FadeIn(REDRAW_FIELD);
5973 }
5974
5975 static void setJoystickDeviceToNr(char *device_name, int device_nr)
5976 {
5977   if (device_name == NULL)
5978     return;
5979
5980   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
5981     device_nr = 0;
5982
5983   if (strlen(device_name) > 1)
5984   {
5985     char c1 = device_name[strlen(device_name) - 1];
5986     char c2 = device_name[strlen(device_name) - 2];
5987
5988     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
5989       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
5990   }
5991   else
5992     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
5993             strlen(device_name));
5994 }
5995
5996 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
5997 {
5998   int i;
5999   static struct SetupKeyboardInfo custom_key;
6000   static struct
6001   {
6002     Key *key;
6003     char *text;
6004   } custom[] =
6005   {
6006     { &custom_key.left,  "Axis/Pad Left"  },
6007     { &custom_key.right, "Axis/Pad Right" },
6008     { &custom_key.up,    "Axis/Pad Up"    },
6009     { &custom_key.down,  "Axis/Pad Down"  },
6010     { &custom_key.snap,  "Button 1/A/X"   },
6011     { &custom_key.drop,  "Button 2/B/Y"   }
6012   };
6013   static char *joystick_name[MAX_PLAYERS] =
6014   {
6015     "Joystick1",
6016     "Joystick2",
6017     "Joystick3",
6018     "Joystick4"
6019   };
6020   int text_font_nr = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
6021
6022   custom_key = setup.input[player_nr].key;
6023
6024   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
6025            FONT_INPUT_1_ACTIVE);
6026
6027   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
6028                              TILEX, TILEY);
6029   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
6030                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
6031
6032   if (setup.input[player_nr].use_joystick)
6033   {
6034     char *device_name = setup.input[player_nr].joy.device_name;
6035     int joystick_nr = getJoystickNrFromDeviceName(device_name);
6036     boolean joystick_active = CheckJoystickOpened(joystick_nr);
6037     char *text = joystick_name[joystick_nr];
6038     int font_nr = (joystick_active ? FONT_VALUE_1 : FONT_VALUE_OLD);
6039
6040     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
6041     DrawText(mSX + 32, mSY + 4 * 32, "Configure", text_font_nr);
6042   }
6043   else
6044   {
6045     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", FONT_VALUE_1);
6046     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", text_font_nr);
6047   }
6048
6049   DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", FONT_MENU_1);
6050
6051   drawCursorXY(1, 4, IMG_MENU_BUTTON_LEFT);
6052   drawCursorXY(1, 5, IMG_MENU_BUTTON_RIGHT);
6053   drawCursorXY(1, 6, IMG_MENU_BUTTON_UP);
6054   drawCursorXY(1, 7, IMG_MENU_BUTTON_DOWN);
6055
6056   DrawText(mSX + 2 * 32, mSY +  6 * 32, ":", FONT_VALUE_OLD);
6057   DrawText(mSX + 2 * 32, mSY +  7 * 32, ":", FONT_VALUE_OLD);
6058   DrawText(mSX + 2 * 32, mSY +  8 * 32, ":", FONT_VALUE_OLD);
6059   DrawText(mSX + 2 * 32, mSY +  9 * 32, ":", FONT_VALUE_OLD);
6060   DrawText(mSX + 1 * 32, mSY + 10 * 32, "Snap Field:", FONT_VALUE_OLD);
6061   DrawText(mSX + 1 * 32, mSY + 12 * 32, "Drop Element:", FONT_VALUE_OLD);
6062
6063   for (i = 0; i < 6; i++)
6064   {
6065     int ypos = 6 + i + (i > 3 ? i-3 : 0);
6066
6067     DrawText(mSX + 3 * 32, mSY + ypos * 32,
6068              "              ", FONT_VALUE_1);
6069     DrawText(mSX + 3 * 32, mSY + ypos * 32,
6070              (setup.input[player_nr].use_joystick ?
6071               custom[i].text :
6072               getKeyNameFromKey(*custom[i].key)), FONT_VALUE_1);
6073   }
6074 }
6075
6076 static int input_player_nr = 0;
6077
6078 void HandleSetupScreen_Input_Player(int step, int direction)
6079 {
6080   int old_player_nr = input_player_nr;
6081   int new_player_nr;
6082
6083   new_player_nr = old_player_nr + step * direction;
6084   if (new_player_nr < 0)
6085     new_player_nr = 0;
6086   if (new_player_nr > MAX_PLAYERS - 1)
6087     new_player_nr = MAX_PLAYERS - 1;
6088
6089   if (new_player_nr != old_player_nr)
6090   {
6091     input_player_nr = new_player_nr;
6092
6093     drawPlayerSetupInputInfo(input_player_nr, FALSE);
6094   }
6095 }
6096
6097 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
6098 {
6099   static int choice = 0;
6100   int x = 0;
6101   int y = choice;
6102   int pos_start  = SETUPINPUT_SCREEN_POS_START;
6103   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
6104   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
6105   int pos_end    = SETUPINPUT_SCREEN_POS_END;
6106
6107   if (button == MB_MENU_INITIALIZE)
6108   {
6109     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
6110
6111     DrawCursorAndText_Setup(choice, -1, TRUE);
6112
6113     return;
6114   }
6115   else if (button == MB_MENU_LEAVE)
6116   {
6117     setup_mode = SETUP_MODE_MAIN;
6118     DrawSetupScreen();
6119     InitJoysticks();
6120
6121     return;
6122   }
6123
6124   if (mx || my)         /* mouse input */
6125   {
6126     x = (mx - mSX) / 32;
6127     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
6128   }
6129   else if (dx || dy)    /* keyboard input */
6130   {
6131     if (dx && choice == 0)
6132       x = (dx < 0 ? 10 : 12);
6133     else if ((dx && choice == 1) ||
6134              (dx == -1 && choice == pos_end))
6135       button = MB_MENU_CHOICE;
6136     else if (dy)
6137       y = choice + dy;
6138
6139     if (y >= pos_empty1 && y <= pos_empty2)
6140       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
6141   }
6142
6143   if (y == 0 && dx != 0 && button)
6144   {
6145     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
6146   }
6147   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
6148            y >= pos_start && y <= pos_end &&
6149            !(y >= pos_empty1 && y <= pos_empty2))
6150   {
6151     if (button)
6152     {
6153       if (y != choice)
6154       {
6155         DrawCursorAndText_Setup(choice, -1, FALSE);
6156         DrawCursorAndText_Setup(y, -1, TRUE);
6157
6158         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
6159
6160         choice = y;
6161       }
6162     }
6163     else
6164     {
6165       if (y == 1)
6166       {
6167         char *device_name = setup.input[input_player_nr].joy.device_name;
6168
6169         if (!setup.input[input_player_nr].use_joystick)
6170         {
6171           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
6172
6173           setJoystickDeviceToNr(device_name, new_device_nr);
6174           setup.input[input_player_nr].use_joystick = TRUE;
6175         }
6176         else
6177         {
6178           int device_nr = getJoystickNrFromDeviceName(device_name);
6179           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
6180
6181           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
6182             setup.input[input_player_nr].use_joystick = FALSE;
6183           else
6184             setJoystickDeviceToNr(device_name, new_device_nr);
6185         }
6186
6187         drawPlayerSetupInputInfo(input_player_nr, FALSE);
6188       }
6189       else if (y == 2)
6190       {
6191         if (setup.input[input_player_nr].use_joystick)
6192           ConfigureJoystick(input_player_nr);
6193         else
6194           CustomizeKeyboard(input_player_nr);
6195       }
6196       else if (y == pos_end)
6197       {
6198         InitJoysticks();
6199
6200         FadeSetLeaveMenu();
6201
6202         setup_mode = SETUP_MODE_MAIN;
6203         DrawSetupScreen();
6204       }
6205     }
6206   }
6207 }
6208
6209 void CustomizeKeyboard(int player_nr)
6210 {
6211   int i;
6212   int step_nr;
6213   boolean finished = FALSE;
6214   static struct SetupKeyboardInfo custom_key;
6215   static struct
6216   {
6217     Key *key;
6218     char *text;
6219   } customize_step[] =
6220   {
6221     { &custom_key.left,  "Move Left"    },
6222     { &custom_key.right, "Move Right"   },
6223     { &custom_key.up,    "Move Up"      },
6224     { &custom_key.down,  "Move Down"    },
6225     { &custom_key.snap,  "Snap Field"   },
6226     { &custom_key.drop,  "Drop Element" }
6227   };
6228
6229   /* read existing key bindings from player setup */
6230   custom_key = setup.input[player_nr].key;
6231
6232   FadeSetEnterMenu();
6233   FadeOut(REDRAW_FIELD);
6234
6235   ClearField();
6236
6237   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
6238
6239   step_nr = 0;
6240   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
6241            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
6242   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
6243            "Key:", FONT_INPUT_1_ACTIVE);
6244   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6245            getKeyNameFromKey(*customize_step[step_nr].key), FONT_VALUE_OLD);
6246
6247   FadeIn(REDRAW_FIELD);
6248
6249   while (!finished)
6250   {
6251     if (PendingEvent())         /* got event */
6252     {
6253       Event event;
6254
6255       NextEvent(&event);
6256
6257       switch (event.type)
6258       {
6259         case EVENT_KEYPRESS:
6260           {
6261             Key key = GetEventKey((KeyEvent *)&event, FALSE);
6262
6263             if (key == KSYM_Escape || (key == KSYM_Return && step_nr == 6))
6264             {
6265               if (key == KSYM_Escape)
6266                 FadeSkipNextFadeIn();
6267
6268               finished = TRUE;
6269               break;
6270             }
6271
6272             /* all keys configured -- wait for "Escape" or "Return" key */
6273             if (step_nr == 6)
6274               break;
6275
6276             /* press 'Enter' to keep the existing key binding */
6277             if (key == KSYM_Return)
6278               key = *customize_step[step_nr].key;
6279
6280             /* check if key already used */
6281             for (i = 0; i < step_nr; i++)
6282               if (*customize_step[i].key == key)
6283                 break;
6284             if (i < step_nr)
6285               break;
6286
6287             /* got new key binding */
6288             *customize_step[step_nr].key = key;
6289             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6290                      "             ", FONT_VALUE_1);
6291             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6292                      getKeyNameFromKey(key), FONT_VALUE_1);
6293             step_nr++;
6294
6295             /* un-highlight last query */
6296             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
6297                      customize_step[step_nr - 1].text, FONT_MENU_1);
6298             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
6299                      "Key:", FONT_MENU_1);
6300
6301             /* press 'Enter' to leave */
6302             if (step_nr == 6)
6303             {
6304               DrawText(mSX + 16, mSY + 15 * 32 + 16,
6305                        "Press Enter", FONT_TITLE_1);
6306               break;
6307             }
6308
6309             /* query next key binding */
6310             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
6311                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
6312             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
6313                      "Key:", FONT_INPUT_1_ACTIVE);
6314             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6315                      getKeyNameFromKey(*customize_step[step_nr].key),
6316                      FONT_VALUE_OLD);
6317           }
6318           break;
6319
6320         case EVENT_KEYRELEASE:
6321           key_joystick_mapping = 0;
6322           break;
6323
6324         default:
6325           HandleOtherEvents(&event);
6326           break;
6327       }
6328     }
6329
6330     BackToFront();
6331   }
6332
6333   /* write new key bindings back to player setup */
6334   setup.input[player_nr].key = custom_key;
6335
6336   DrawSetupScreen_Input();
6337 }
6338
6339 #if 0
6340 static boolean OLD_CalibrateJoystickMain(int player_nr)
6341 {
6342   int new_joystick_xleft = JOYSTICK_XMIDDLE;
6343   int new_joystick_xright = JOYSTICK_XMIDDLE;
6344   int new_joystick_yupper = JOYSTICK_YMIDDLE;
6345   int new_joystick_ylower = JOYSTICK_YMIDDLE;
6346   int new_joystick_xmiddle, new_joystick_ymiddle;
6347
6348   char *device_name = setup.input[player_nr].joy.device_name;
6349   int joystick_nr = getJoystickNrFromDeviceName(device_name);
6350   boolean joystick_active = CheckJoystickOpened(joystick_nr);
6351
6352   int x, y, last_x, last_y, xpos = 8, ypos = 3;
6353   boolean check[3][3];
6354   int check_remaining = 3 * 3;
6355   int joy_x, joy_y;
6356   int joy_value;
6357   int result = -1;
6358
6359   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
6360     return FALSE;
6361
6362   if (!joystick_active || !setup.input[player_nr].use_joystick)
6363     return FALSE;
6364
6365   FadeSetEnterMenu();
6366   FadeOut(REDRAW_FIELD);
6367
6368   ClearField();
6369
6370   for (y = 0; y < 3; y++)
6371   {
6372     for (x = 0; x < 3; x++)
6373     {
6374       DrawFixedGraphic(xpos + x - 1, ypos + y - 1, IMG_MENU_CALIBRATE_BLUE, 0);
6375       check[x][y] = FALSE;
6376     }
6377   }
6378
6379   DrawTextSCentered(mSY - SY +  6 * 32, FONT_TITLE_1, "Rotate joystick");
6380   DrawTextSCentered(mSY - SY +  7 * 32, FONT_TITLE_1, "in all directions");
6381   DrawTextSCentered(mSY - SY +  9 * 32, FONT_TITLE_1, "if all balls");
6382   DrawTextSCentered(mSY - SY + 10 * 32, FONT_TITLE_1, "are marked,");
6383   DrawTextSCentered(mSY - SY + 11 * 32, FONT_TITLE_1, "center joystick");
6384   DrawTextSCentered(mSY - SY + 12 * 32, FONT_TITLE_1, "and");
6385   DrawTextSCentered(mSY - SY + 13 * 32, FONT_TITLE_1, "press any button!");
6386
6387   joy_value = JoystickExt(joystick_nr, TRUE);
6388   last_x = (joy_value & JOY_LEFT ? -1 : joy_value & JOY_RIGHT ? +1 : 0);
6389   last_y = (joy_value & JOY_UP   ? -1 : joy_value & JOY_DOWN  ? +1 : 0);
6390
6391   /* eventually uncalibrated center position (joystick could be uncentered) */
6392   if (!ReadJoystick(joystick_nr, &joy_x, &joy_y, NULL, NULL))
6393     return FALSE;
6394
6395   new_joystick_xmiddle = joy_x;
6396   new_joystick_ymiddle = joy_y;
6397
6398   DrawFixedGraphic(xpos + last_x, ypos + last_y, IMG_MENU_CALIBRATE_RED, 0);
6399
6400   FadeIn(REDRAW_FIELD);
6401
6402   /* wait for potentially still pressed button to be released */
6403   while (JoystickExt(joystick_nr, TRUE) & JOY_BUTTON);
6404
6405   while (result < 0)
6406   {
6407     while (PendingEvent())              /* got event */
6408     {
6409       Event event;
6410
6411       NextEvent(&event);
6412
6413       switch (event.type)
6414       {
6415         case EVENT_KEYPRESS:
6416           switch (GetEventKey((KeyEvent *)&event, TRUE))
6417           {
6418             case KSYM_Return:
6419               if (check_remaining == 0)
6420                 result = 1;
6421               break;
6422
6423             case KSYM_Escape:
6424               FadeSkipNextFadeIn();
6425               result = 0;
6426               break;
6427
6428             default:
6429               break;
6430           }
6431           break;
6432
6433         case EVENT_KEYRELEASE:
6434           key_joystick_mapping = 0;
6435           break;
6436
6437         default:
6438           HandleOtherEvents(&event);
6439           break;
6440       }
6441     }
6442
6443     if (!ReadJoystick(joystick_nr, &joy_x, &joy_y, NULL, NULL))
6444       return FALSE;
6445
6446     new_joystick_xleft  = MIN(new_joystick_xleft,  joy_x);
6447     new_joystick_xright = MAX(new_joystick_xright, joy_x);
6448     new_joystick_yupper = MIN(new_joystick_yupper, joy_y);
6449     new_joystick_ylower = MAX(new_joystick_ylower, joy_y);
6450
6451     setup.input[player_nr].joy.xleft = new_joystick_xleft;
6452     setup.input[player_nr].joy.yupper = new_joystick_yupper;
6453     setup.input[player_nr].joy.xright = new_joystick_xright;
6454     setup.input[player_nr].joy.ylower = new_joystick_ylower;
6455     setup.input[player_nr].joy.xmiddle = new_joystick_xmiddle;
6456     setup.input[player_nr].joy.ymiddle = new_joystick_ymiddle;
6457
6458     CheckJoystickData();
6459
6460     joy_value = JoystickExt(joystick_nr, TRUE);
6461
6462     if (joy_value & JOY_BUTTON && check_remaining == 0)
6463       result = 1;
6464
6465     x = (joy_value & JOY_LEFT ? -1 : joy_value & JOY_RIGHT ? +1 : 0);
6466     y = (joy_value & JOY_UP   ? -1 : joy_value & JOY_DOWN  ? +1 : 0);
6467
6468     if (x != last_x || y != last_y)
6469     {
6470       DrawFixedGraphic(xpos + last_x, ypos + last_y,
6471                        IMG_MENU_CALIBRATE_YELLOW, 0);
6472       DrawFixedGraphic(xpos + x,      ypos + y,
6473                        IMG_MENU_CALIBRATE_RED,    0);
6474
6475       last_x = x;
6476       last_y = y;
6477
6478       if (check_remaining > 0 && !check[x+1][y+1])
6479       {
6480         check[x+1][y+1] = TRUE;
6481         check_remaining--;
6482       }
6483     }
6484
6485     BackToFront();
6486   }
6487
6488   /* calibrated center position (joystick should now be centered) */
6489   if (!ReadJoystick(joystick_nr, &joy_x, &joy_y, NULL, NULL))
6490     return FALSE;
6491
6492   new_joystick_xmiddle = joy_x;
6493   new_joystick_ymiddle = joy_y;
6494
6495   /* wait until the last pressed button was released */
6496   while (JoystickExt(joystick_nr, TRUE) & JOY_BUTTON)
6497   {
6498     if (PendingEvent())         /* got event */
6499     {
6500       Event event;
6501
6502       NextEvent(&event);
6503       HandleOtherEvents(&event);
6504
6505       BackToFront();
6506     }
6507   }
6508
6509   return TRUE;
6510 }
6511 #endif
6512
6513 /* game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com> */
6514
6515 #define MARKER_BUTTON           1
6516 #define MARKER_AXIS_X           2
6517 #define MARKER_AXIS_Y           3
6518
6519 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
6520 {
6521 #if defined(TARGET_SDL2)
6522   static boolean bitmaps_initialized = FALSE;
6523   boolean screen_initialized = FALSE;
6524   static Bitmap *controller, *button, *axis_x, *axis_y;
6525   Bitmap *marker;
6526   char *name;
6527   boolean success = TRUE;
6528   boolean done = FALSE, next = FALSE;
6529   Event event;
6530   int alpha = 200, alpha_step = -1;
6531   int alpha_ticks = 0;
6532   char mapping[4096], temp[4096];
6533   int font_name = FONT_TEXT_1;
6534   int font_info = FONT_REQUEST;
6535   int ystep1 = getFontHeight(font_name) + 2;
6536   int ystep2 = getFontHeight(font_info) + 2;
6537   int i, j;
6538
6539   struct
6540   {
6541     int x, y;
6542     int marker;
6543     char *field;
6544     int axis, button, hat, hat_value;
6545     char mapping[4096];
6546   }
6547   *step, *prev_step, steps[] =
6548   {
6549     { 356, 155, MARKER_BUTTON, "a",             },
6550     { 396, 122, MARKER_BUTTON, "b",             },
6551     { 320, 125, MARKER_BUTTON, "x",             },
6552     { 358,  95, MARKER_BUTTON, "y",             },
6553     { 162, 125, MARKER_BUTTON, "back",          },
6554     { 216, 125, MARKER_BUTTON, "guide",         },
6555     { 271, 125, MARKER_BUTTON, "start",         },
6556     { 110, 200, MARKER_BUTTON, "dpleft",        },
6557     { 146, 228, MARKER_BUTTON, "dpdown",        },
6558     { 178, 200, MARKER_BUTTON, "dpright",       },
6559     { 146, 172, MARKER_BUTTON, "dpup",          },
6560     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
6561     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
6562     { 382,  40, MARKER_BUTTON, "rightshoulder", },
6563     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
6564     {  73, 141, MARKER_BUTTON, "leftstick",     },
6565     { 282, 210, MARKER_BUTTON, "rightstick",    },
6566     {  73, 141, MARKER_AXIS_X, "leftx",         },
6567     {  73, 141, MARKER_AXIS_Y, "lefty",         },
6568     { 282, 210, MARKER_AXIS_X, "rightx",        },
6569     { 282, 210, MARKER_AXIS_Y, "righty",        },
6570   };
6571
6572   unsigned int event_frame_delay = 0;
6573   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
6574
6575   ResetDelayCounter(&event_frame_delay);
6576
6577   if (!bitmaps_initialized)
6578   {
6579     controller = LoadCustomImage("joystick/controller.png");
6580     button     = LoadCustomImage("joystick/button.png");
6581     axis_x     = LoadCustomImage("joystick/axis_x.png");
6582     axis_y     = LoadCustomImage("joystick/axis_y.png");
6583
6584     bitmaps_initialized = TRUE;
6585   }
6586
6587   name = getFormattedJoystickName(SDL_JoystickName(joystick));
6588
6589   /* print info about the joystick we are watching */
6590   Error(ERR_DEBUG, "watching joystick %d: (%s)\n",
6591         SDL_JoystickInstanceID(joystick), name);
6592   Error(ERR_DEBUG, "joystick has %d axes, %d hats, %d balls, and %d buttons\n",
6593         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
6594         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
6595
6596   /* initialize mapping with GUID and name */
6597   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
6598
6599   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
6600            temp, name, SDL_GetPlatform());
6601
6602   /* loop through all steps (buttons and axes), getting joystick events */
6603   for (i = 0; i < SDL_arraysize(steps) && !done;)
6604   {
6605     step = &steps[i];
6606     strcpy(step->mapping, mapping);
6607     step->axis = -1;
6608     step->button = -1;
6609     step->hat = -1;
6610     step->hat_value = -1;
6611
6612     marker = (step->marker == MARKER_BUTTON ? button :
6613               step->marker == MARKER_AXIS_X ? axis_x :
6614               step->marker == MARKER_AXIS_Y ? axis_y : marker);
6615
6616     next = FALSE;
6617
6618     while (!done && !next)
6619     {
6620       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
6621       alpha_ticks = SDL_GetTicks();
6622
6623       if (alpha >= 255)
6624       {
6625         alpha = 255;
6626         alpha_step = -1;
6627       }
6628       else if (alpha < 128)
6629       {
6630         alpha = 127;
6631         alpha_step = 1;
6632       }
6633
6634       int controller_x = SX + (SXSIZE - controller->width) / 2;
6635       int controller_y = SY + ystep2;
6636
6637       int marker_x = controller_x + step->x;
6638       int marker_y = controller_y + step->y;
6639
6640       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
6641       int ystart2 = ystart1 + ystep1 + ystep2;
6642
6643       ClearField();
6644
6645       DrawTextSCentered(ystart1, font_name, name);
6646
6647       DrawTextSCentered(ystart2 + 0 * ystep2, font_info,
6648                         "Press buttons and move axes on");
6649       DrawTextSCentered(ystart2 + 1 * ystep2, font_info,
6650                         "your controller when indicated.");
6651       DrawTextSCentered(ystart2 + 2 * ystep2, font_info,
6652                         "(Your controller may look different.)");
6653
6654 #if defined(PLATFORM_ANDROID)
6655       DrawTextSCentered(ystart2 + 4 * ystep2, font_info,
6656                         "To correct a mistake,");
6657       DrawTextSCentered(ystart2 + 5 * ystep2, font_info,
6658                         "press the 'back' button.");
6659       DrawTextSCentered(ystart2 + 6 * ystep2, font_info,
6660                         "To skip a button or axis,");
6661       DrawTextSCentered(ystart2 + 7 * ystep2, font_info,
6662                         "press the 'menu' button.");
6663 #else
6664       DrawTextSCentered(ystart2 + 4 * ystep2, font_info,
6665                         "To correct a mistake,");
6666       DrawTextSCentered(ystart2 + 5 * ystep2, font_info,
6667                         "press the 'backspace' key.");
6668       DrawTextSCentered(ystart2 + 6 * ystep2, font_info,
6669                         "To skip a button or axis,");
6670       DrawTextSCentered(ystart2 + 7 * ystep2, font_info,
6671                         "press the 'return' key.");
6672
6673       DrawTextSCentered(ystart2 + 8 * ystep2, font_info,
6674                         "To exit, press the 'escape' key.");
6675 #endif
6676
6677       BlitBitmapMasked(controller, drawto, 0, 0,
6678                        controller->width, controller->height,
6679                        controller_x, controller_y);
6680
6681       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
6682
6683       BlitBitmapMasked(marker, drawto, 0, 0,
6684                        marker->width, marker->height,
6685                        marker_x, marker_y);
6686
6687       if (!screen_initialized)
6688         FadeIn(REDRAW_FIELD);
6689       else
6690         BackToFront();
6691
6692       screen_initialized = TRUE;
6693
6694       while (NextValidEvent(&event))
6695       {
6696         switch (event.type)
6697         {
6698           case SDL_JOYAXISMOTION:
6699             if (event.jaxis.value > 20000 ||
6700                 event.jaxis.value < -20000)
6701             {
6702               for (j = 0; j < i; j++)
6703                 if (steps[j].axis == event.jaxis.axis)
6704                   break;
6705
6706               if (j == i)
6707               {
6708                 if (step->marker != MARKER_AXIS_X &&
6709                     step->marker != MARKER_AXIS_Y)
6710                   break;
6711
6712                 step->axis = event.jaxis.axis;
6713                 strcat(mapping, step->field);
6714                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
6715                 strcat(mapping, temp);
6716                 i++;
6717                 next = TRUE;
6718               }
6719             }
6720
6721             break;
6722
6723           case SDL_JOYHATMOTION:
6724             /* ignore centering; we're probably just coming back
6725                to the center from the previous item we set */
6726             if (event.jhat.value == SDL_HAT_CENTERED)
6727               break;
6728
6729             for (j = 0; j < i; j++)
6730               if (steps[j].hat == event.jhat.hat &&
6731                   steps[j].hat_value == event.jhat.value)
6732                 break;
6733
6734             if (j == i)
6735             {
6736               step->hat = event.jhat.hat;
6737               step->hat_value = event.jhat.value;
6738               strcat(mapping, step->field);
6739               snprintf(temp, sizeof(temp), ":h%u.%u,",
6740                        event.jhat.hat, event.jhat.value );
6741               strcat(mapping, temp);
6742               i++;
6743               next = TRUE;
6744             }
6745
6746             break;
6747
6748           case SDL_JOYBALLMOTION:
6749             break;
6750
6751           case SDL_JOYBUTTONUP:
6752             for (j = 0; j < i; j++)
6753               if (steps[j].button == event.jbutton.button)
6754                 break;
6755
6756             if (j == i)
6757             {
6758               step->button = event.jbutton.button;
6759               strcat(mapping, step->field);
6760               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
6761               strcat(mapping, temp);
6762               i++;
6763               next = TRUE;
6764             }
6765
6766             break;
6767
6768           case SDL_FINGERDOWN:
6769           case SDL_MOUSEBUTTONDOWN:
6770             /* skip this step */
6771             i++;
6772             next = TRUE;
6773
6774             break;
6775
6776           case SDL_KEYDOWN:
6777             if (event.key.keysym.sym == KSYM_BackSpace ||
6778                 event.key.keysym.sym == KSYM_Back)
6779             {
6780               if (i == 0)
6781               {
6782                 /* leave screen */
6783                 success = FALSE;
6784                 done = TRUE;
6785               }
6786
6787               /* undo this step */
6788               prev_step = &steps[i - 1];
6789               strcpy(mapping, prev_step->mapping);
6790               i--;
6791               next = TRUE;
6792
6793               break;
6794             }
6795
6796             if (event.key.keysym.sym == KSYM_space ||
6797                 event.key.keysym.sym == KSYM_Return ||
6798                 event.key.keysym.sym == KSYM_Menu)
6799             {
6800               /* skip this step */
6801               i++;
6802               next = TRUE;
6803
6804               break;
6805             }
6806
6807             if (event.key.keysym.sym == KSYM_Escape)
6808             {
6809               /* leave screen */
6810               success = FALSE;
6811               done = TRUE;
6812             }
6813
6814             break;
6815
6816           case SDL_QUIT:
6817             program.exit_function(0);
6818             break;
6819
6820           default:
6821             break;
6822         }
6823
6824         // do not handle events for longer than standard frame delay period
6825         if (DelayReached(&event_frame_delay, event_frame_delay_value))
6826           break;
6827       }
6828     }
6829   }
6830
6831   if (success)
6832   {
6833     Error(ERR_DEBUG, "New game controller mapping:\n\n%s\n\n", mapping);
6834
6835     // activate mapping for this game
6836     SDL_GameControllerAddMapping(mapping);
6837
6838     // save mapping to personal mappings
6839     SaveSetup_AddGameControllerMapping(mapping);
6840   }
6841
6842   /* wait until the last pending event was removed from event queue */
6843   while (NextValidEvent(&event));
6844
6845   return success;
6846 #else
6847   return TRUE;
6848 #endif
6849 }
6850
6851 static int ConfigureJoystickMain(int player_nr)
6852 {
6853   char *device_name = setup.input[player_nr].joy.device_name;
6854   int joystick_nr = getJoystickNrFromDeviceName(device_name);
6855   boolean joystick_active = CheckJoystickOpened(joystick_nr);
6856   int success = FALSE;
6857   int i;
6858
6859   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
6860     return JOYSTICK_NOT_AVAILABLE;
6861
6862   if (!joystick_active || !setup.input[player_nr].use_joystick)
6863     return JOYSTICK_NOT_AVAILABLE;
6864
6865   FadeSetEnterMenu();
6866   FadeOut(REDRAW_FIELD);
6867
6868   // close all joystick devices (potentially opened as game controllers)
6869   for (i = 0; i < SDL_NumJoysticks(); i++)
6870     SDLCloseJoystick(i);
6871
6872   // open joystick device as plain joystick to configure as game controller
6873   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
6874
6875   // as the joystick was successfully opened before, this should not happen
6876   if (joystick == NULL)
6877     return FALSE;
6878
6879   // create new game controller mapping (buttons and axes) for joystick device
6880   success = ConfigureJoystickMapButtonsAndAxes(joystick);
6881
6882   // close joystick (and maybe re-open as configured game controller later)
6883   SDL_JoystickClose(joystick);
6884
6885   // re-open all joystick devices (potentially as game controllers)
6886   for (i = 0; i < SDL_NumJoysticks(); i++)
6887     SDLOpenJoystick(i);
6888
6889   // clear all joystick input actions for all joystick devices
6890   SDLClearJoystickState();
6891
6892   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
6893 }
6894
6895 void ConfigureJoystick(int player_nr)
6896 {
6897   boolean state = ConfigureJoystickMain(player_nr);
6898
6899   if (state != JOYSTICK_NOT_CONFIGURED)
6900   {
6901     boolean success = (state == JOYSTICK_CONFIGURED);
6902     char *message = (success ? " IS CONFIGURED! " : " NOT AVAILABLE! ");
6903     char *device_name = setup.input[player_nr].joy.device_name;
6904     int nr = getJoystickNrFromDeviceName(device_name) + 1;
6905     int xpos = mSX - SX;
6906     int ypos = mSY - SY;
6907     unsigned int wait_frame_delay = 0;
6908     unsigned int wait_frame_delay_value = 2000;
6909
6910     ResetDelayCounter(&wait_frame_delay);
6911
6912     ClearField();
6913
6914     DrawTextF(xpos + 16, ypos + 6 * 32, FONT_TITLE_1, "   JOYSTICK %d   ", nr);
6915     DrawTextF(xpos + 16, ypos + 7 * 32, FONT_TITLE_1, message);
6916
6917     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
6918       BackToFront();
6919
6920     ClearEventQueue();
6921   }
6922
6923   DrawSetupScreen_Input();
6924 }
6925
6926 void DrawSetupScreen()
6927 {
6928   if (setup_mode == SETUP_MODE_INPUT)
6929     DrawSetupScreen_Input();
6930   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
6931     DrawChooseTree(&game_speed_current);
6932   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
6933     DrawChooseTree(&scroll_delay_current);
6934   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
6935     DrawChooseTree(&snapshot_mode_current);
6936   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6937     DrawChooseTree(&window_size_current);
6938   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
6939     DrawChooseTree(&scaling_type_current);
6940   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
6941     DrawChooseTree(&rendering_mode_current);
6942   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
6943     DrawChooseTree(&artwork.gfx_current);
6944   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
6945     DrawChooseTree(&artwork.snd_current);
6946   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
6947     DrawChooseTree(&artwork.mus_current);
6948   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
6949     DrawChooseTree(&volume_simple_current);
6950   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
6951     DrawChooseTree(&volume_loops_current);
6952   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
6953     DrawChooseTree(&volume_music_current);
6954   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
6955     DrawChooseTree(&touch_control_current);
6956   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
6957     DrawChooseTree(&move_distance_current);
6958   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
6959     DrawChooseTree(&drop_distance_current);
6960   else
6961     DrawSetupScreen_Generic();
6962
6963   PlayMenuSoundsAndMusic();
6964 }
6965
6966 void RedrawSetupScreenAfterFullscreenToggle()
6967 {
6968   if (setup_mode == SETUP_MODE_GRAPHICS ||
6969       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6970   {
6971     // update list selection from "setup.window_scaling_percent"
6972     execSetupGraphics_setWindowSizes(TRUE);
6973
6974     DrawSetupScreen();
6975   }
6976 }
6977
6978 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
6979 {
6980   if (setup_mode == SETUP_MODE_INPUT)
6981     HandleSetupScreen_Input(mx, my, dx, dy, button);
6982   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
6983     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
6984   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
6985     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
6986   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
6987     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
6988   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6989     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
6990   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
6991     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
6992   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
6993     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
6994   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
6995     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
6996   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
6997     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
6998   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
6999     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
7000   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
7001     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
7002   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
7003     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
7004   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
7005     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
7006   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
7007     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
7008   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
7009     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
7010   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
7011     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
7012   else
7013     HandleSetupScreen_Generic(mx, my, dx, dy, button);
7014 }
7015
7016 void HandleGameActions()
7017 {
7018   if (game_status != GAME_MODE_PLAYING)
7019     return;
7020
7021   GameActions();        /* main game loop */
7022
7023   if (tape.auto_play && !tape.playing)
7024     AutoPlayTape();     /* continue automatically playing next tape */
7025 }
7026
7027
7028 /* ---------- new screen button stuff -------------------------------------- */
7029
7030 static void getScreenMenuButtonPos(int *x, int *y, int gadget_id)
7031 {
7032   switch (gadget_id)
7033   {
7034     case SCREEN_CTRL_ID_PREV_LEVEL:
7035       *x = mSX + GDI_ACTIVE_POS(menu.main.button.prev_level.x);
7036       *y = mSY + GDI_ACTIVE_POS(menu.main.button.prev_level.y);
7037       break;
7038
7039     case SCREEN_CTRL_ID_NEXT_LEVEL:
7040       *x = mSX + GDI_ACTIVE_POS(menu.main.button.next_level.x);
7041       *y = mSY + GDI_ACTIVE_POS(menu.main.button.next_level.y);
7042       break;
7043
7044     case SCREEN_CTRL_ID_PREV_PLAYER:
7045       *x = mSX + TILEX * 10;
7046       *y = mSY + TILEY * MENU_SCREEN_START_YPOS;
7047       break;
7048
7049     case SCREEN_CTRL_ID_NEXT_PLAYER:
7050       *x = mSX + TILEX * 12;
7051       *y = mSY + TILEY * MENU_SCREEN_START_YPOS;
7052       break;
7053
7054     default:
7055       Error(ERR_EXIT, "unknown gadget ID %d", gadget_id);
7056   }
7057 }
7058
7059 static struct
7060 {
7061   int gfx_unpressed, gfx_pressed;
7062   void (*get_gadget_position)(int *, int *, int);
7063   int gadget_id;
7064   int screen_mask;
7065   char *infotext;
7066 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
7067 {
7068   {
7069     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
7070     getScreenMenuButtonPos,
7071     SCREEN_CTRL_ID_PREV_LEVEL,
7072     SCREEN_MASK_MAIN,
7073     "last level"
7074   },
7075   {
7076     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
7077     getScreenMenuButtonPos,
7078     SCREEN_CTRL_ID_NEXT_LEVEL,
7079     SCREEN_MASK_MAIN,
7080     "next level"
7081   },
7082   {
7083     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
7084     getScreenMenuButtonPos,
7085     SCREEN_CTRL_ID_PREV_PLAYER,
7086     SCREEN_MASK_INPUT,
7087     "last player"
7088   },
7089   {
7090     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
7091     getScreenMenuButtonPos,
7092     SCREEN_CTRL_ID_NEXT_PLAYER,
7093     SCREEN_MASK_INPUT,
7094     "next player"
7095   },
7096 };
7097
7098 static struct
7099 {
7100   int gfx_unpressed, gfx_pressed;
7101   int x, y;
7102   int gadget_id;
7103   char *infotext;
7104 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
7105 {
7106   {
7107     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
7108     -1, -1,     /* these values are not constant, but can change at runtime */
7109     SCREEN_CTRL_ID_SCROLL_UP,
7110     "scroll up"
7111   },
7112   {
7113     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
7114     -1, -1,     /* these values are not constant, but can change at runtime */
7115     SCREEN_CTRL_ID_SCROLL_DOWN,
7116     "scroll down"
7117   }
7118 };
7119
7120 static struct
7121 {
7122   int gfx_unpressed, gfx_pressed;
7123   int x, y;
7124   int width, height;
7125   int type;
7126   int gadget_id;
7127   char *infotext;
7128 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
7129 {
7130   {
7131     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
7132     -1, -1,     /* these values are not constant, but can change at runtime */
7133     -1, -1,     /* these values are not constant, but can change at runtime */
7134     GD_TYPE_SCROLLBAR_VERTICAL,
7135     SCREEN_CTRL_ID_SCROLL_VERTICAL,
7136     "scroll level series vertically"
7137   }
7138 };
7139
7140 static void CreateScreenMenubuttons()
7141 {
7142   struct GadgetInfo *gi;
7143   unsigned int event_mask;
7144   int i;
7145
7146   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
7147   {
7148     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7149     int gfx_unpressed, gfx_pressed;
7150     int x, y, width, height;
7151     int gd_x1, gd_x2, gd_y1, gd_y2;
7152     int id = menubutton_info[i].gadget_id;
7153
7154     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
7155
7156     menubutton_info[i].get_gadget_position(&x, &y, id);
7157
7158     width = SC_MENUBUTTON_XSIZE;
7159     height = SC_MENUBUTTON_YSIZE;
7160
7161     gfx_unpressed = menubutton_info[i].gfx_unpressed;
7162     gfx_pressed   = menubutton_info[i].gfx_pressed;
7163     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7164     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7165     gd_x1 = graphic_info[gfx_unpressed].src_x;
7166     gd_y1 = graphic_info[gfx_unpressed].src_y;
7167     gd_x2 = graphic_info[gfx_pressed].src_x;
7168     gd_y2 = graphic_info[gfx_pressed].src_y;
7169
7170     gi = CreateGadget(GDI_CUSTOM_ID, id,
7171                       GDI_CUSTOM_TYPE_ID, i,
7172                       GDI_INFO_TEXT, menubutton_info[i].infotext,
7173                       GDI_X, x,
7174                       GDI_Y, y,
7175                       GDI_WIDTH, width,
7176                       GDI_HEIGHT, height,
7177                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
7178                       GDI_STATE, GD_BUTTON_UNPRESSED,
7179                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7180                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7181                       GDI_DIRECT_DRAW, FALSE,
7182                       GDI_EVENT_MASK, event_mask,
7183                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7184                       GDI_END);
7185
7186     if (gi == NULL)
7187       Error(ERR_EXIT, "cannot create gadget");
7188
7189     screen_gadget[id] = gi;
7190   }
7191 }
7192
7193 static void CreateScreenScrollbuttons()
7194 {
7195   struct GadgetInfo *gi;
7196   unsigned int event_mask;
7197   int i;
7198
7199   /* these values are not constant, but can change at runtime */
7200   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
7201   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
7202   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
7203   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
7204
7205   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
7206   {
7207     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7208     int gfx_unpressed, gfx_pressed;
7209     int x, y, width, height;
7210     int gd_x1, gd_x2, gd_y1, gd_y2;
7211     int id = scrollbutton_info[i].gadget_id;
7212
7213     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
7214
7215     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
7216     y = mSY + scrollbutton_info[i].y;
7217     width = SC_SCROLLBUTTON_XSIZE;
7218     height = SC_SCROLLBUTTON_YSIZE;
7219
7220     /* correct scrollbar position if placed outside menu (playfield) area */
7221     if (x > SX + SC_SCROLL_UP_XPOS)
7222       x = SX + SC_SCROLL_UP_XPOS;
7223
7224     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
7225       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
7226                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
7227
7228     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
7229     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
7230     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7231     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7232     gd_x1 = graphic_info[gfx_unpressed].src_x;
7233     gd_y1 = graphic_info[gfx_unpressed].src_y;
7234     gd_x2 = graphic_info[gfx_pressed].src_x;
7235     gd_y2 = graphic_info[gfx_pressed].src_y;
7236
7237     gi = CreateGadget(GDI_CUSTOM_ID, id,
7238                       GDI_CUSTOM_TYPE_ID, i,
7239                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
7240                       GDI_X, x,
7241                       GDI_Y, y,
7242                       GDI_WIDTH, width,
7243                       GDI_HEIGHT, height,
7244                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
7245                       GDI_STATE, GD_BUTTON_UNPRESSED,
7246                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7247                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7248                       GDI_DIRECT_DRAW, FALSE,
7249                       GDI_EVENT_MASK, event_mask,
7250                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7251                       GDI_END);
7252
7253     if (gi == NULL)
7254       Error(ERR_EXIT, "cannot create gadget");
7255
7256     screen_gadget[id] = gi;
7257   }
7258 }
7259
7260 static void CreateScreenScrollbars()
7261 {
7262   int i;
7263
7264   /* these values are not constant, but can change at runtime */
7265   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
7266   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
7267   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
7268   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
7269
7270   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
7271   {
7272     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7273     int gfx_unpressed, gfx_pressed;
7274     int x, y, width, height;
7275     int gd_x1, gd_x2, gd_y1, gd_y2;
7276     struct GadgetInfo *gi;
7277     int items_max, items_visible, item_position;
7278     unsigned int event_mask;
7279     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
7280     int id = scrollbar_info[i].gadget_id;
7281
7282     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
7283
7284     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
7285     y = mSY + scrollbar_info[i].y;
7286     width  = scrollbar_info[i].width;
7287     height = scrollbar_info[i].height;
7288
7289     /* correct scrollbar position if placed outside menu (playfield) area */
7290     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
7291       x = SX + SC_SCROLL_VERTICAL_XPOS;
7292
7293     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
7294       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
7295
7296     items_max = num_page_entries;
7297     items_visible = num_page_entries;
7298     item_position = 0;
7299
7300     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
7301     gfx_pressed   = scrollbar_info[i].gfx_pressed;
7302     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7303     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7304     gd_x1 = graphic_info[gfx_unpressed].src_x;
7305     gd_y1 = graphic_info[gfx_unpressed].src_y;
7306     gd_x2 = graphic_info[gfx_pressed].src_x;
7307     gd_y2 = graphic_info[gfx_pressed].src_y;
7308
7309     gi = CreateGadget(GDI_CUSTOM_ID, id,
7310                       GDI_CUSTOM_TYPE_ID, i,
7311                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
7312                       GDI_X, x,
7313                       GDI_Y, y,
7314                       GDI_WIDTH, width,
7315                       GDI_HEIGHT, height,
7316                       GDI_TYPE, scrollbar_info[i].type,
7317                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
7318                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
7319                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
7320                       GDI_WHEEL_AREA_X, SX,
7321                       GDI_WHEEL_AREA_Y, SY,
7322                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
7323                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
7324                       GDI_STATE, GD_BUTTON_UNPRESSED,
7325                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7326                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7327                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
7328                       GDI_DIRECT_DRAW, FALSE,
7329                       GDI_EVENT_MASK, event_mask,
7330                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7331                       GDI_END);
7332
7333     if (gi == NULL)
7334       Error(ERR_EXIT, "cannot create gadget");
7335
7336     screen_gadget[id] = gi;
7337   }
7338 }
7339
7340 void CreateScreenGadgets()
7341 {
7342   CreateScreenMenubuttons();
7343
7344   CreateScreenScrollbuttons();
7345   CreateScreenScrollbars();
7346 }
7347
7348 void FreeScreenGadgets()
7349 {
7350   int i;
7351
7352   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
7353     FreeGadget(screen_gadget[i]);
7354 }
7355
7356 void MapScreenMenuGadgets(int screen_mask)
7357 {
7358   int i;
7359
7360   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
7361     if (screen_mask & menubutton_info[i].screen_mask)
7362       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
7363 }
7364
7365 void MapScreenGadgets(int num_entries)
7366 {
7367   int i;
7368
7369   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
7370     return;
7371
7372   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
7373     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
7374
7375   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
7376     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
7377 }
7378
7379 void MapScreenTreeGadgets(TreeInfo *ti)
7380 {
7381   MapScreenGadgets(numTreeInfoInGroup(ti));
7382 }
7383
7384 static void HandleScreenGadgets(struct GadgetInfo *gi)
7385 {
7386   int id = gi->custom_id;
7387   int button = gi->event.button;
7388   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
7389
7390   switch (id)
7391   {
7392     case SCREEN_CTRL_ID_PREV_LEVEL:
7393       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
7394       break;
7395
7396     case SCREEN_CTRL_ID_NEXT_LEVEL:
7397       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
7398       break;
7399
7400     case SCREEN_CTRL_ID_PREV_PLAYER:
7401       HandleSetupScreen_Input_Player(step, -1);
7402       break;
7403
7404     case SCREEN_CTRL_ID_NEXT_PLAYER:
7405       HandleSetupScreen_Input_Player(step, +1);
7406       break;
7407
7408     case SCREEN_CTRL_ID_SCROLL_UP:
7409       if (game_status == GAME_MODE_LEVELS)
7410         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7411       else if (game_status == GAME_MODE_LEVELNR)
7412         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7413       else if (game_status == GAME_MODE_SETUP)
7414         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7415       else if (game_status == GAME_MODE_INFO)
7416         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7417       break;
7418
7419     case SCREEN_CTRL_ID_SCROLL_DOWN:
7420       if (game_status == GAME_MODE_LEVELS)
7421         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7422       else if (game_status == GAME_MODE_LEVELNR)
7423         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7424       else if (game_status == GAME_MODE_SETUP)
7425         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7426       else if (game_status == GAME_MODE_INFO)
7427         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7428       break;
7429
7430     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
7431       if (game_status == GAME_MODE_LEVELS)
7432         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
7433       else if (game_status == GAME_MODE_LEVELNR)
7434         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
7435       else if (game_status == GAME_MODE_SETUP)
7436         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
7437       else if (game_status == GAME_MODE_INFO)
7438         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
7439       break;
7440
7441     default:
7442       break;
7443   }
7444 }