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