added new setup option type "yes/no/ask"
[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 //                  https://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 #include "api.h"
26
27
28 #define DEBUG_JOYSTICKS                         0
29
30
31 // screens on the info screen
32 #define INFO_MODE_MAIN                          0
33 #define INFO_MODE_TITLE                         1
34 #define INFO_MODE_ELEMENTS                      2
35 #define INFO_MODE_MUSIC                         3
36 #define INFO_MODE_CREDITS                       4
37 #define INFO_MODE_PROGRAM                       5
38 #define INFO_MODE_VERSION                       6
39 #define INFO_MODE_LEVELSET                      7
40
41 #define MAX_INFO_MODES                          8
42
43 // screens on the setup screen
44 // (must match GFX_SPECIAL_ARG_SETUP_* values as defined in src/main.h)
45 // (should also match corresponding entries in src/conf_gfx.c)
46 #define SETUP_MODE_MAIN                         0
47 #define SETUP_MODE_GAME                         1
48 #define SETUP_MODE_ENGINES                      2
49 #define SETUP_MODE_EDITOR                       3
50 #define SETUP_MODE_GRAPHICS                     4
51 #define SETUP_MODE_SOUND                        5
52 #define SETUP_MODE_ARTWORK                      6
53 #define SETUP_MODE_INPUT                        7
54 #define SETUP_MODE_TOUCH                        8
55 #define SETUP_MODE_SHORTCUTS                    9
56 #define SETUP_MODE_SHORTCUTS_1                  10
57 #define SETUP_MODE_SHORTCUTS_2                  11
58 #define SETUP_MODE_SHORTCUTS_3                  12
59 #define SETUP_MODE_SHORTCUTS_4                  13
60 #define SETUP_MODE_SHORTCUTS_5                  14
61 #define SETUP_MODE_SHORTCUTS_6                  15
62
63 // sub-screens on the setup screen (generic)
64 #define SETUP_MODE_CHOOSE_ARTWORK               16
65 #define SETUP_MODE_CHOOSE_OTHER                 17
66
67 // sub-screens on the setup screen (specific)
68 #define SETUP_MODE_CHOOSE_SCORES_TYPE           18
69 #define SETUP_MODE_CHOOSE_GAME_SPEED            19
70 #define SETUP_MODE_CHOOSE_SCROLL_DELAY          20
71 #define SETUP_MODE_CHOOSE_SNAPSHOT_MODE         21
72 #define SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE      22
73 #define SETUP_MODE_CHOOSE_BD_PALETTE_C64        23
74 #define SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV     24
75 #define SETUP_MODE_CHOOSE_BD_PALETTE_ATARI      25
76 #define SETUP_MODE_CHOOSE_BD_COLOR_TYPE         26
77 #define SETUP_MODE_CHOOSE_WINDOW_SIZE           27
78 #define SETUP_MODE_CHOOSE_SCALING_TYPE          28
79 #define SETUP_MODE_CHOOSE_RENDERING             29
80 #define SETUP_MODE_CHOOSE_VSYNC                 30
81 #define SETUP_MODE_CHOOSE_GRAPHICS              31
82 #define SETUP_MODE_CHOOSE_SOUNDS                32
83 #define SETUP_MODE_CHOOSE_MUSIC                 33
84 #define SETUP_MODE_CHOOSE_VOLUME_SIMPLE         34
85 #define SETUP_MODE_CHOOSE_VOLUME_LOOPS          35
86 #define SETUP_MODE_CHOOSE_VOLUME_MUSIC          36
87 #define SETUP_MODE_CHOOSE_TOUCH_CONTROL         37
88 #define SETUP_MODE_CHOOSE_MOVE_DISTANCE         38
89 #define SETUP_MODE_CHOOSE_DROP_DISTANCE         39
90 #define SETUP_MODE_CHOOSE_TRANSPARENCY          40
91 #define SETUP_MODE_CHOOSE_GRID_XSIZE_0          41
92 #define SETUP_MODE_CHOOSE_GRID_YSIZE_0          42
93 #define SETUP_MODE_CHOOSE_GRID_XSIZE_1          43
94 #define SETUP_MODE_CHOOSE_GRID_YSIZE_1          44
95 #define SETUP_MODE_CONFIG_VIRT_BUTTONS          45
96
97 #define MAX_SETUP_MODES                         46
98
99 #define MAX_MENU_MODES                          MAX(MAX_INFO_MODES, MAX_SETUP_MODES)
100
101 // info screen titles
102 #define STR_INFO_MAIN                           "Info Screen"
103 #define STR_INFO_TITLE                          "Title Screen"
104 #define STR_INFO_ELEMENTS                       "Game Elements"
105 #define STR_INFO_MUSIC                          "Music Info"
106 #define STR_INFO_CREDITS                        "Credits"
107 #define STR_INFO_PROGRAM                        "Program Info"
108 #define STR_INFO_VERSION                        "Version Info"
109 #define STR_INFO_LEVELSET                       "Level Set Info"
110 #define STR_INFO_EXIT                           "Exit"
111
112 // setup screen titles
113 #define STR_SETUP_MAIN                          "Setup"
114 #define STR_SETUP_GAME                          "Game & Menu"
115 #define STR_SETUP_ENGINES                       "Game Engines"
116 #define STR_SETUP_EDITOR                        "Editor"
117 #define STR_SETUP_GRAPHICS                      "Graphics"
118 #define STR_SETUP_SOUND                         "Sound & Music"
119 #define STR_SETUP_ARTWORK                       "Custom Artwork"
120 #define STR_SETUP_INPUT                         "Input Devices"
121 #define STR_SETUP_TOUCH                         "Touch Controls"
122 #define STR_SETUP_SHORTCUTS                     "Key Shortcuts"
123 #define STR_SETUP_EXIT                          "Exit"
124 #define STR_SETUP_SAVE_AND_EXIT                 "Save and Exit"
125
126 #define STR_SETUP_CHOOSE_SCORES_TYPE            "Scores Type"
127 #define STR_SETUP_CHOOSE_GAME_SPEED             "Game Speed"
128 #define STR_SETUP_CHOOSE_SCROLL_DELAY           "Scroll Delay"
129 #define STR_SETUP_CHOOSE_SNAPSHOT_MODE          "Snapshot Mode"
130 #define STR_SETUP_CHOOSE_GAME_ENGINE_TYPE       "Game Engine"
131 #define STR_SETUP_CHOOSE_BD_PALETTE_C64         "Palette (C64)"
132 #define STR_SETUP_CHOOSE_BD_PALETTE_C64DTV      "Palette (C64DTV)"
133 #define STR_SETUP_CHOOSE_BD_PALETTE_ATARI       "Palette (Atari)"
134 #define STR_SETUP_CHOOSE_BD_COLOR_TYPE          "Color Type"
135 #define STR_SETUP_CHOOSE_WINDOW_SIZE            "Window Scaling"
136 #define STR_SETUP_CHOOSE_SCALING_TYPE           "Anti-Aliasing"
137 #define STR_SETUP_CHOOSE_RENDERING              "Rendering Mode"
138 #define STR_SETUP_CHOOSE_VSYNC                  "VSync Mode"
139 #define STR_SETUP_CHOOSE_VOLUME_SIMPLE          "Sound Volume"
140 #define STR_SETUP_CHOOSE_VOLUME_LOOPS           "Loops Volume"
141 #define STR_SETUP_CHOOSE_VOLUME_MUSIC           "Music Volume"
142 #define STR_SETUP_CHOOSE_TOUCH_CONTROL          "Control Type"
143 #define STR_SETUP_CHOOSE_MOVE_DISTANCE          "Move Distance"
144 #define STR_SETUP_CHOOSE_DROP_DISTANCE          "Drop Distance"
145 #define STR_SETUP_CHOOSE_TRANSPARENCY           "Transparency"
146 #define STR_SETUP_CHOOSE_GRID_XSIZE_0           "Horiz. Buttons"
147 #define STR_SETUP_CHOOSE_GRID_YSIZE_0           "Vert. Buttons"
148 #define STR_SETUP_CHOOSE_GRID_XSIZE_1           "Horiz. Buttons"
149 #define STR_SETUP_CHOOSE_GRID_YSIZE_1           "Vert. Buttons"
150
151 // other screen text constants
152 #define STR_CHOOSE_TREE_EDIT                    "Edit"
153 #define MENU_CHOOSE_TREE_FONT(x)                (FONT_TEXT_1 + (x))
154 #define MENU_CHOOSE_TREE_COLOR(ti, a)           TREE_COLOR(ti, a)
155
156 #define TEXT_MAIN_MENU                          "Press any key or button for main menu"
157 #define TEXT_INFO_MENU                          "Press any key or button for info menu"
158 #define TEXT_NEXT_PAGE                          "Press any key or button for next page"
159 #define TEXT_NEXT_MENU                          (info_screens_from_main ?               \
160                                                  TEXT_MAIN_MENU : TEXT_INFO_MENU)
161
162 // for input setup functions
163 #define SETUPINPUT_SCREEN_POS_START             0
164 #define SETUPINPUT_SCREEN_POS_EMPTY1            3
165 #define SETUPINPUT_SCREEN_POS_EMPTY2            12
166 #define SETUPINPUT_SCREEN_POS_END               13
167
168 #define MENU_SETUP_FONT_TITLE                   FONT_TEXT_1
169 #define MENU_SETUP_FONT_TEXT                    FONT_TITLE_2
170
171 #define MAX_SETUP_TEXT_INPUT_LEN                28
172
173 // for various menu stuff
174 #define MENU_SCREEN_START_XPOS                  1
175 #define MENU_SCREEN_START_YPOS                  2
176 #define MENU_SCREEN_VALUE_XPOS                  (SCR_FIELDX - 3)
177 #define MENU_SCREEN_TEXT2_XPOS                  (SCR_FIELDX - 2)
178 #define MENU_SCREEN_MAX_XPOS                    (SCR_FIELDX - 1)
179 #define MENU_TITLE1_YPOS                        8
180 #define MENU_TITLE2_YPOS                        46
181 #define MENU_INFO_FONT_TITLE                    FONT_TEXT_1
182 #define MENU_INFO_FONT_HEAD                     FONT_TEXT_2
183 #define MENU_INFO_FONT_TEXT                     FONT_TEXT_3
184 #define MENU_INFO_FONT_FOOT                     FONT_TEXT_4
185 #define MENU_INFO_SPACE_HEAD                    (menu.headline2_spacing_info[info_mode])
186 #define MENU_SCREEN_INFO_SPACE_LEFT             (menu.left_spacing_info[info_mode])
187 #define MENU_SCREEN_INFO_SPACE_MIDDLE           (menu.middle_spacing_info[info_mode])
188 #define MENU_SCREEN_INFO_SPACE_RIGHT            (menu.right_spacing_info[info_mode])
189 #define MENU_SCREEN_INFO_SPACE_TOP              (menu.top_spacing_info[info_mode])
190 #define MENU_SCREEN_INFO_SPACE_BOTTOM           (menu.bottom_spacing_info[info_mode])
191 #define MENU_SCREEN_INFO_SPACE_LINE             (menu.line_spacing_info[info_mode])
192 #define MENU_SCREEN_INFO_SPACE_EXTRA            (menu.extra_spacing_info[info_mode])
193 #define MENU_SCREEN_INFO_TILE_SIZE_RAW          (menu.tile_size_info[info_mode])
194 #define MENU_SCREEN_INFO_TILE_SIZE              (MENU_SCREEN_INFO_TILE_SIZE_RAW > 0 ?           \
195                                                  MENU_SCREEN_INFO_TILE_SIZE_RAW : TILEY)
196 #define MENU_SCREEN_INFO_ENTRY_SIZE_RAW         (menu.list_entry_size_info[info_mode])
197 #define MENU_SCREEN_INFO_ENTRY_SIZE             (MAX(MENU_SCREEN_INFO_ENTRY_SIZE_RAW,           \
198                                                      MENU_SCREEN_INFO_TILE_SIZE))
199 #define MENU_SCREEN_INFO_YSTART                 MENU_SCREEN_INFO_SPACE_TOP
200 #define MENU_SCREEN_INFO_YSTEP                  (MENU_SCREEN_INFO_ENTRY_SIZE +                  \
201                                                  MENU_SCREEN_INFO_SPACE_EXTRA)
202 #define MENU_SCREEN_INFO_YBOTTOM                (SYSIZE - MENU_SCREEN_INFO_SPACE_BOTTOM)
203 #define MENU_SCREEN_INFO_YSIZE                  (MENU_SCREEN_INFO_YBOTTOM -                     \
204                                                  MENU_SCREEN_INFO_YSTART - TILEY / 2)
205 #define MAX_INFO_ELEMENTS_IN_ARRAY              128
206 #define MAX_INFO_ELEMENTS_ON_SCREEN             (SYSIZE / TILEY)
207 #define MAX_INFO_ELEMENTS                       MIN(MAX_INFO_ELEMENTS_IN_ARRAY,                 \
208                                                     MAX_INFO_ELEMENTS_ON_SCREEN)
209 #define STD_INFO_ELEMENTS_ON_SCREEN             10
210 #define DYN_INFO_ELEMENTS_ON_SCREEN             (MENU_SCREEN_INFO_YSIZE / MENU_SCREEN_INFO_YSTEP)
211 #define DEFAULT_INFO_ELEMENTS                   MIN(STD_INFO_ELEMENTS_ON_SCREEN,                \
212                                                     DYN_INFO_ELEMENTS_ON_SCREEN)
213 #define NUM_INFO_ELEMENTS_FROM_CONF                                     \
214                                 (menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] > 0 ?       \
215                                  menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] :           \
216                                  DEFAULT_INFO_ELEMENTS)
217 #define NUM_INFO_ELEMENTS_ON_SCREEN             MIN(NUM_INFO_ELEMENTS_FROM_CONF, MAX_INFO_ELEMENTS)
218 #define MAX_MENU_ENTRIES_ON_SCREEN              (SCR_FIELDY - MENU_SCREEN_START_YPOS)
219 #define MAX_MENU_TEXT_LENGTH_BIG                13
220 #define MAX_MENU_TEXT_LENGTH_MEDIUM             (MAX_MENU_TEXT_LENGTH_BIG * 2)
221
222 // screen gadget identifiers
223 #define SCREEN_CTRL_ID_PREV_LEVEL               0
224 #define SCREEN_CTRL_ID_NEXT_LEVEL               1
225 #define SCREEN_CTRL_ID_PREV_LEVEL2              2
226 #define SCREEN_CTRL_ID_NEXT_LEVEL2              3
227 #define SCREEN_CTRL_ID_PREV_SCORE               4
228 #define SCREEN_CTRL_ID_NEXT_SCORE               5
229 #define SCREEN_CTRL_ID_PLAY_TAPE                6
230 #define SCREEN_CTRL_ID_FIRST_LEVEL              7
231 #define SCREEN_CTRL_ID_LAST_LEVEL               8
232 #define SCREEN_CTRL_ID_LEVEL_NUMBER             9
233 #define SCREEN_CTRL_ID_PREV_PLAYER              10
234 #define SCREEN_CTRL_ID_NEXT_PLAYER              11
235 #define SCREEN_CTRL_ID_INSERT_SOLUTION          12
236 #define SCREEN_CTRL_ID_PLAY_SOLUTION            13
237 #define SCREEN_CTRL_ID_LEVELSET_INFO            14
238 #define SCREEN_CTRL_ID_SWITCH_ECS_AGA           15
239 #define SCREEN_CTRL_ID_TOUCH_PREV_PAGE          16
240 #define SCREEN_CTRL_ID_TOUCH_NEXT_PAGE          17
241 #define SCREEN_CTRL_ID_TOUCH_PREV_PAGE2         18
242 #define SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2         19
243
244 #define NUM_SCREEN_MENUBUTTONS                  20
245
246 #define SCREEN_CTRL_ID_SCROLL_UP                20
247 #define SCREEN_CTRL_ID_SCROLL_DOWN              21
248 #define SCREEN_CTRL_ID_SCROLL_VERTICAL          22
249 #define SCREEN_CTRL_ID_NETWORK_SERVER           23
250
251 #define NUM_SCREEN_GADGETS                      24
252
253 #define NUM_SCREEN_SCROLLBUTTONS                2
254 #define NUM_SCREEN_SCROLLBARS                   1
255 #define NUM_SCREEN_TEXTINPUT                    1
256
257 #define SCREEN_MASK_MAIN                        (1 << 0)
258 #define SCREEN_MASK_MAIN_HAS_SOLUTION           (1 << 1)
259 #define SCREEN_MASK_MAIN_HAS_SET_INFO           (1 << 2)
260 #define SCREEN_MASK_INPUT                       (1 << 3)
261 #define SCREEN_MASK_TOUCH                       (1 << 4)
262 #define SCREEN_MASK_TOUCH2                      (1 << 5)
263 #define SCREEN_MASK_SCORES                      (1 << 6)
264 #define SCREEN_MASK_SCORES_INFO                 (1 << 7)
265
266 // graphic position and size values for buttons and scrollbars
267 #define SC_MENUBUTTON_XSIZE                     TILEX
268 #define SC_MENUBUTTON_YSIZE                     TILEY
269
270 #define SC_SCROLLBUTTON_XSIZE                   TILEX
271 #define SC_SCROLLBUTTON_YSIZE                   TILEY
272
273 #define SC_SCROLLBAR_XPOS                       (SXSIZE - SC_SCROLLBUTTON_XSIZE)
274
275 #define SC_SCROLL_VERTICAL_XSIZE                SC_SCROLLBUTTON_XSIZE
276 #define SC_SCROLL_VERTICAL_YSIZE                ((MAX_MENU_ENTRIES_ON_SCREEN - 2) * \
277                                                  SC_SCROLLBUTTON_YSIZE)
278
279 #define SC_SCROLL_UP_XPOS                       SC_SCROLLBAR_XPOS
280 #define SC_SCROLL_UP_YPOS                       (2 * SC_SCROLLBUTTON_YSIZE)
281
282 #define SC_SCROLL_VERTICAL_XPOS                 SC_SCROLLBAR_XPOS
283 #define SC_SCROLL_VERTICAL_YPOS                 (SC_SCROLL_UP_YPOS + \
284                                                  SC_SCROLLBUTTON_YSIZE)
285
286 #define SC_SCROLL_DOWN_XPOS                     SC_SCROLLBAR_XPOS
287 #define SC_SCROLL_DOWN_YPOS                     (SC_SCROLL_VERTICAL_YPOS + \
288                                                  SC_SCROLL_VERTICAL_YSIZE)
289
290 #define SC_BORDER_SIZE                          14
291
292
293 // forward declarations of internal functions
294 static void HandleScreenGadgets(struct GadgetInfo *);
295 static void HandleSetupScreen_Generic(int, int, int, int, int);
296 static void HandleSetupScreen_Input(int, int, int, int, int);
297 static void CustomizeKeyboard(int);
298 static void ConfigureJoystick(int);
299 static void ConfigureVirtualButtons(void);
300 static void execSetupGame(void);
301 static void execSetupEngines(void);
302 static void execSetupEditor(void);
303 static void execSetupGraphics(void);
304 static void execSetupSound(void);
305 static void execSetupTouch(void);
306 static void execSetupArtwork(void);
307 static void HandleChooseTree(int, int, int, int, int, TreeInfo **);
308
309 static void DrawChoosePlayerName(void);
310 static void DrawChooseLevelSet(void);
311 static void DrawChooseLevelNr(void);
312 static void DrawScoreInfo(int);
313 static void DrawScoreInfo_Content(int);
314 static void DrawInfoScreen(void);
315 static void DrawSetupScreen(void);
316 static void DrawTypeName(void);
317
318 static void DrawInfoScreen_NotAvailable(char *, char *);
319 static void DrawInfoScreen_HelpAnim(int, int, boolean);
320 static void DrawInfoScreen_HelpText(int, int, int, int);
321 static void HandleInfoScreen_Main(int, int, int, int, int);
322 static void HandleInfoScreen_TitleScreen(int, int, int);
323 static void HandleInfoScreen_Elements(int, int, int);
324 static void HandleInfoScreen_Music(int, int, int);
325 static void HandleInfoScreen_Version(int);
326 static void HandleInfoScreen_Generic(int, int, int);
327
328 static void ModifyGameSpeedIfNeeded(void);
329 static void DisableVsyncIfNeeded(void);
330
331 static void RedrawScreenMenuGadgets(int);
332 static void MapScreenMenuGadgets(int);
333 static void UnmapScreenMenuGadgets(int);
334 static void MapScreenGadgets(int);
335 static void UnmapScreenGadgets(void);
336 static void MapScreenTreeGadgets(TreeInfo *);
337 static void UnmapScreenTreeGadgets(void);
338
339 static void UpdateScreenMenuGadgets(int, boolean);
340 static void AdjustScoreInfoButtons_SelectScore(int, int, int);
341 static void AdjustScoreInfoButtons_PlayTape(int, int, boolean);
342
343 static boolean OfferUploadTapes(void);
344 static void execOfferUploadTapes(void);
345
346 static void DrawHallOfFame_setScoreEntries(void);
347 static void HandleHallOfFame_SelectLevel(int, int);
348 static char *getHallOfFameRankText(int, int);
349 static char *getHallOfFameScoreText(int, int);
350 static char *getInfoScreenTitle_Generic(void);
351 static int getInfoScreenBackgroundImage_Generic(void);
352 static int getInfoScreenBackgroundSound_Generic(void);
353 static int getInfoScreenBackgroundMusic_Generic(void);
354
355 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *);
356
357 static struct GadgetInfo *screen_gadget[NUM_SCREEN_GADGETS];
358
359 static int info_mode = INFO_MODE_MAIN;
360 static int setup_mode = SETUP_MODE_MAIN;
361
362 static boolean info_screens_from_main = FALSE;
363
364 static TreeInfo *window_sizes = NULL;
365 static TreeInfo *window_size_current = NULL;
366
367 static TreeInfo *scaling_types = NULL;
368 static TreeInfo *scaling_type_current = NULL;
369
370 static TreeInfo *rendering_modes = NULL;
371 static TreeInfo *rendering_mode_current = NULL;
372
373 static TreeInfo *vsync_modes = NULL;
374 static TreeInfo *vsync_mode_current = NULL;
375
376 static TreeInfo *scroll_delays = NULL;
377 static TreeInfo *scroll_delay_current = NULL;
378
379 static TreeInfo *snapshot_modes = NULL;
380 static TreeInfo *snapshot_mode_current = NULL;
381
382 static TreeInfo *game_engine_types = NULL;
383 static TreeInfo *game_engine_type_current = NULL;
384
385 static TreeInfo *bd_palettes_c64 = NULL;
386 static TreeInfo *bd_palette_c64_current = NULL;
387
388 static TreeInfo *bd_palettes_c64dtv = NULL;
389 static TreeInfo *bd_palette_c64dtv_current = NULL;
390
391 static TreeInfo *bd_palettes_atari = NULL;
392 static TreeInfo *bd_palette_atari_current = NULL;
393
394 static TreeInfo *bd_color_types = NULL;
395 static TreeInfo *bd_color_type_current = NULL;
396
397 static TreeInfo *scores_types = NULL;
398 static TreeInfo *scores_type_current = NULL;
399
400 static TreeInfo *game_speeds_normal = NULL;
401 static TreeInfo *game_speeds_extended = NULL;
402 static TreeInfo *game_speeds = NULL;
403 static TreeInfo *game_speed_current = NULL;
404
405 static TreeInfo *volumes_simple = NULL;
406 static TreeInfo *volume_simple_current = NULL;
407
408 static TreeInfo *volumes_loops = NULL;
409 static TreeInfo *volume_loops_current = NULL;
410
411 static TreeInfo *volumes_music = NULL;
412 static TreeInfo *volume_music_current = NULL;
413
414 static TreeInfo *touch_controls = NULL;
415 static TreeInfo *touch_control_current = NULL;
416
417 static TreeInfo *move_distances = NULL;
418 static TreeInfo *move_distance_current = NULL;
419
420 static TreeInfo *drop_distances = NULL;
421 static TreeInfo *drop_distance_current = NULL;
422
423 static TreeInfo *transparencies = NULL;
424 static TreeInfo *transparency_current = NULL;
425
426 static TreeInfo *grid_sizes[2][2] = { { NULL, NULL }, { NULL, NULL } };
427 static TreeInfo *grid_size_current[2][2] = { { NULL, NULL }, { NULL, NULL } };
428
429 static TreeInfo *player_name = NULL;
430 static TreeInfo *player_name_current = NULL;
431
432 static TreeInfo *level_number = NULL;
433 static TreeInfo *level_number_current = NULL;
434
435 static TreeInfo *score_entries = NULL;
436 static TreeInfo *score_entry_current = NULL;
437
438 static struct ValueTextInfo window_sizes_list[] =
439 {
440   { 50,                                 "50 %"                          },
441   { 80,                                 "80 %"                          },
442   { 90,                                 "90 %"                          },
443   { 100,                                "100 % (Default)"               },
444   { 110,                                "110 %"                         },
445   { 120,                                "120 %"                         },
446   { 130,                                "130 %"                         },
447   { 140,                                "140 %"                         },
448   { 150,                                "150 %"                         },
449   { 200,                                "200 %"                         },
450   { 250,                                "250 %"                         },
451   { 300,                                "300 %"                         },
452
453   { -1,                                 NULL                            },
454 };
455
456 static struct StringValueTextInfo scaling_types_list[] =
457 {
458   { SCALING_QUALITY_NEAREST,             "Off"                          },
459   { SCALING_QUALITY_LINEAR,              "Linear"                       },
460   { SCALING_QUALITY_BEST,                "Anisotropic"                  },
461
462   { NULL,                                NULL                           },
463 };
464
465 static struct StringValueTextInfo rendering_modes_list[] =
466 {
467   { STR_SPECIAL_RENDERING_OFF,          "Off (May show artifacts, fast)"},
468   { STR_SPECIAL_RENDERING_BITMAP,       "Bitmap/Texture mode (slower)"  },
469 #if DEBUG
470   // this mode may work under certain conditions, but does not work on Windows
471   { STR_SPECIAL_RENDERING_TARGET,       "Target Texture mode (slower)"  },
472 #endif
473   { STR_SPECIAL_RENDERING_DOUBLE,       "Double Texture mode (slower)"  },
474
475   { NULL,                                NULL                           },
476 };
477
478 static struct StringValueTextInfo vsync_modes_list[] =
479 {
480   { STR_VSYNC_MODE_OFF,                 "Off"                           },
481   { STR_VSYNC_MODE_NORMAL,              "Normal"                        },
482   { STR_VSYNC_MODE_ADAPTIVE,            "Adaptive"                      },
483
484   { NULL,                               NULL                            },
485 };
486
487 static struct StringValueTextInfo scores_types_list[] =
488 {
489   { STR_SCORES_TYPE_LOCAL_ONLY,         "Local scores only"             },
490   { STR_SCORES_TYPE_SERVER_ONLY,        "Server scores only"            },
491   { STR_SCORES_TYPE_LOCAL_AND_SERVER,   "Local and server scores"       },
492
493   { NULL,                               NULL                            },
494 };
495
496 static struct ValueTextInfo game_speeds_list_normal[] =
497 {
498   { 30,                                 "Very Slow"                     },
499   { 25,                                 "Slow"                          },
500   { 20,                                 "Normal"                        },
501   { 15,                                 "Fast"                          },
502   { 10,                                 "Very Fast"                     },
503
504   { -1,                                 NULL                            },
505 };
506
507 static struct ValueTextInfo game_speeds_list_extended[] =
508 {
509   { 1000,                               "1 fps (Extremely Slow)"        },
510   { 500,                                "2 fps"                         },
511   { 200,                                "5 fps"                         },
512   { 100,                                "10 fps"                        },
513   { 50,                                 "20 fps"                        },
514   { 29,                                 "35 fps (Original Supaplex)"    },
515   { 25,                                 "40 fps"                        },
516   { 20,                                 "50 fps (=== Normal Speed ===)" },
517   { 16,                                 "60 fps (60 Hz VSync Speed)"    },
518   { 14,                                 "70 fps (Maximum Supaplex)"     },
519   { 10,                                 "100 fps"                       },
520   { 5,                                  "200 fps"                       },
521   { 2,                                  "500 fps"                       },
522   { 1,                                  "1000 fps (Extremely Fast)"     },
523
524   { -1,                                 NULL                            },
525 };
526
527 static struct ValueTextInfo *game_speeds_list;
528
529 static struct ValueTextInfo scroll_delays_list[] =
530 {
531   { 0,                                  "0 Tiles (No Scroll Delay)"     },
532   { 1,                                  "1 Tile"                        },
533   { 2,                                  "2 Tiles"                       },
534   { 3,                                  "3 Tiles (Default)"             },
535   { 4,                                  "4 Tiles"                       },
536   { 5,                                  "5 Tiles"                       },
537   { 6,                                  "6 Tiles"                       },
538   { 7,                                  "7 Tiles"                       },
539   { 8,                                  "8 Tiles (Maximum Scroll Delay)"},
540
541   { -1,                                 NULL                            },
542 };
543
544 static struct StringValueTextInfo snapshot_modes_list[] =
545 {
546   { STR_SNAPSHOT_MODE_OFF,              "Off"                           },
547   { STR_SNAPSHOT_MODE_EVERY_STEP,       "Every Step"                    },
548   { STR_SNAPSHOT_MODE_EVERY_MOVE,       "Every Move"                    },
549   { STR_SNAPSHOT_MODE_EVERY_COLLECT,    "Every Collect"                 },
550
551   { NULL,                               NULL                            },
552 };
553
554 static struct ValueTextInfo game_engine_types_list[] =
555 {
556   { GAME_ENGINE_TYPE_RND,               "Rocks'n'Diamonds"              },
557   { GAME_ENGINE_TYPE_BD,                "Boulder Dash"                  },
558   { GAME_ENGINE_TYPE_EM,                "Emerald Mine"                  },
559   { GAME_ENGINE_TYPE_SP,                "Supaplex"                      },
560   { GAME_ENGINE_TYPE_MM,                "Mirror Magic"                  },
561
562   { -1,                                 NULL                            }
563 };
564
565 static struct ValueTextInfo bd_palettes_c64_list[] =
566 {
567   { GD_PALETTE_C64_VICE_NEW,            "Vice new"                      },
568   { GD_PALETTE_C64_VICE_OLD,            "Vice old"                      },
569   { GD_PALETTE_C64_VIDE_DEFAULT,        "Vice default"                  },
570   { GD_PALETTE_C64_C64HQ,               "C64HQ"                         },
571   { GD_PALETTE_C64_C64S,                "C64S"                          },
572   { GD_PALETTE_C64_CCS64,               "CCS64"                         },
573   { GD_PALETTE_C64_FRODO,               "Frodo"                         },
574   { GD_PALETTE_C64_GODOT,               "GoDot"                         },
575   { GD_PALETTE_C64_PC64,                "PC64"                          },
576   { GD_PALETTE_C64_RTADASH,             "RTADash"                       },
577
578   { -1,                                 NULL                            },
579 };
580
581 static struct ValueTextInfo bd_palettes_c64dtv_list[] =
582 {
583   { GD_PALETTE_C64DTV_SPIFF,            "Spiff"                         },
584   { GD_PALETTE_C64DTV_MURRAY,           "Murray"                        },
585
586   { -1,                                 NULL                            },
587 };
588
589 static struct ValueTextInfo bd_palettes_atari_list[] =
590 {
591   { GD_PALETTE_ATARI_BUILTIN,           "BuiltIn"                       },
592   { GD_PALETTE_ATARI_BUILTIN_CONTRAST,  "BuiltIn contrast"              },
593   { GD_PALETTE_ATARI_DEFAULT,           "Default"                       },
594   { GD_PALETTE_ATARI_JAKUB,             "Jakub"                         },
595   { GD_PALETTE_ATARI_JAKUB_CONTRAST,    "Jakub contrast"                },
596   { GD_PALETTE_ATARI_REAL,              "Real"                          },
597   { GD_PALETTE_ATARI_REAL_CONTRAST,     "Real contrast"                 },
598   { GD_PALETTE_ATARI_XFORMER,           "XFormer"                       },
599
600   { -1,                                 NULL                            },
601 };
602
603 static struct ValueTextInfo bd_color_types_list[] =
604 {
605   { GD_COLOR_TYPE_RGB,                  "RGB colors"                    },
606   { GD_COLOR_TYPE_C64,                  "C64 colors"                    },
607   { GD_COLOR_TYPE_C64DTV,               "C64DTV colors"                 },
608   { GD_COLOR_TYPE_ATARI,                "Atari colors"                  },
609
610   { -1,                                 NULL                            },
611 };
612
613 static struct ValueTextInfo volumes_list[] =
614 {
615   { 0,                                  "0 %"                           },
616   { 1,                                  "1 %"                           },
617   { 2,                                  "2 %"                           },
618   { 5,                                  "5 %"                           },
619   { 10,                                 "10 %"                          },
620   { 20,                                 "20 %"                          },
621   { 30,                                 "30 %"                          },
622   { 40,                                 "40 %"                          },
623   { 50,                                 "50 %"                          },
624   { 60,                                 "60 %"                          },
625   { 70,                                 "70 %"                          },
626   { 80,                                 "80 %"                          },
627   { 90,                                 "90 %"                          },
628   { 100,                                "100 %"                         },
629
630   { -1,                                 NULL                            },
631 };
632
633 static struct StringValueTextInfo touch_controls_list[] =
634 {
635   { TOUCH_CONTROL_OFF,                  "Off"                           },
636   { TOUCH_CONTROL_VIRTUAL_BUTTONS,      "Virtual Buttons"               },
637   { TOUCH_CONTROL_WIPE_GESTURES,        "Wipe Gestures"                 },
638   { TOUCH_CONTROL_FOLLOW_FINGER,        "Follow Finger"                 },
639
640   { NULL,                               NULL                            },
641 };
642
643 static struct ValueTextInfo distances_list[] =
644 {
645   { 1,                                  "1 %"                           },
646   { 2,                                  "2 %"                           },
647   { 3,                                  "3 %"                           },
648   { 4,                                  "4 %"                           },
649   { 5,                                  "5 %"                           },
650   { 10,                                 "10 %"                          },
651   { 15,                                 "15 %"                          },
652   { 20,                                 "20 %"                          },
653   { 25,                                 "25 %"                          },
654
655   { -1,                                 NULL                            },
656 };
657
658 static struct ValueTextInfo transparencies_list[] =
659 {
660   { 0,                                  "0 % (Opaque)"                  },
661   { 10,                                 "10 %"                          },
662   { 20,                                 "20 %"                          },
663   { 30,                                 "30 %"                          },
664   { 40,                                 "40 %"                          },
665   { 50,                                 "50 %"                          },
666   { 60,                                 "60 %"                          },
667   { 70,                                 "70 %"                          },
668   { 80,                                 "80 %"                          },
669   { 90,                                 "90 %"                          },
670   { 100,                                "100 % (Invisible)"             },
671
672   { -1,                                 NULL                            },
673 };
674
675 static struct ValueTextInfo grid_sizes_list[] =
676 {
677   { 3,                                  "3"                             },
678   { 4,                                  "4"                             },
679   { 5,                                  "5"                             },
680   { 6,                                  "6"                             },
681   { 7,                                  "7"                             },
682   { 8,                                  "8"                             },
683   { 9,                                  "9"                             },
684   { 10,                                 "10"                            },
685   { 11,                                 "11"                            },
686   { 12,                                 "12"                            },
687   { 13,                                 "13"                            },
688   { 14,                                 "14"                            },
689   { 15,                                 "15"                            },
690   { 16,                                 "16"                            },
691   { 17,                                 "17"                            },
692   { 18,                                 "18"                            },
693   { 19,                                 "19"                            },
694   { 20,                                 "20"                            },
695   { 21,                                 "21"                            },
696   { 22,                                 "22"                            },
697   { 23,                                 "23"                            },
698   { 24,                                 "24"                            },
699   { 25,                                 "25"                            },
700   { 26,                                 "26"                            },
701   { 27,                                 "27"                            },
702   { 28,                                 "28"                            },
703   { 29,                                 "29"                            },
704   { 30,                                 "30"                            },
705   { 31,                                 "31"                            },
706   { 32,                                 "32"                            },
707
708   { -1,                                 NULL                            },
709 };
710
711 static int align_xoffset = 0;
712 static int align_yoffset = 0;
713
714 #define DRAW_MODE(s)            ((s) >= GAME_MODE_MAIN &&                       \
715                                  (s) <= GAME_MODE_SETUP ? (s) :                 \
716                                  (s) == GAME_MODE_PSEUDO_TYPENAME ?             \
717                                  GAME_MODE_MAIN :                               \
718                                  (s) == GAME_MODE_PSEUDO_TYPENAMES ?            \
719                                  GAME_MODE_NAMES : GAME_MODE_DEFAULT)
720
721 // (there are no draw offset definitions needed for INFO_MODE_TITLE)
722 #define DRAW_MODE_INFO(i)       ((i) >= INFO_MODE_TITLE &&                      \
723                                  (i) <= INFO_MODE_LEVELSET ? (i) :              \
724                                  INFO_MODE_MAIN)
725
726 #define DRAW_MODE_SETUP(i)      ((i) >= SETUP_MODE_MAIN &&                      \
727                                  (i) <= SETUP_MODE_SHORTCUTS_6 ? (i) :          \
728                                  (i) >= SETUP_MODE_CHOOSE_GRAPHICS &&           \
729                                  (i) <= SETUP_MODE_CHOOSE_MUSIC ?               \
730                                  SETUP_MODE_CHOOSE_ARTWORK :                    \
731                                  SETUP_MODE_CHOOSE_OTHER)
732
733 #define DRAW_XOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?          \
734                                  menu.draw_xoffset[GAME_MODE_INFO] :            \
735                                  menu.draw_xoffset_info[DRAW_MODE_INFO(i)])
736 #define DRAW_YOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?          \
737                                  menu.draw_yoffset[GAME_MODE_INFO] :            \
738                                  menu.draw_yoffset_info[DRAW_MODE_INFO(i)])
739 #define EXTRA_SPACING_INFO(i)   (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?          \
740                                  menu.extra_spacing[GAME_MODE_INFO] :           \
741                                  menu.extra_spacing_info[DRAW_MODE_INFO(i)])
742
743 #define DRAW_XOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ?        \
744                                  menu.draw_xoffset[GAME_MODE_SETUP] :           \
745                                  menu.draw_xoffset_setup[DRAW_MODE_SETUP(i)])
746 #define DRAW_YOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ?        \
747                                  menu.draw_yoffset[GAME_MODE_SETUP] :           \
748                                  menu.draw_yoffset_setup[DRAW_MODE_SETUP(i)])
749 #define EXTRA_SPACING_SETUP(i)  (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ?        \
750                                  menu.extra_spacing[GAME_MODE_SETUP] :          \
751                                  menu.extra_spacing_setup[DRAW_MODE_SETUP(i)])
752
753 #define EXTRA_SPACING_SCORES(i) (EXTRA_SPACING_INFO(i))
754
755 #define EXTRA_SPACING_SCOREINFO(i) (menu.extra_spacing[GAME_MODE_SCOREINFO])
756
757 #define DRAW_XOFFSET(s)         ((s) == GAME_MODE_INFO  ? DRAW_XOFFSET_INFO(info_mode) :        \
758                                  (s) == GAME_MODE_SETUP ? DRAW_XOFFSET_SETUP(setup_mode) :      \
759                                  menu.draw_xoffset[DRAW_MODE(s)])
760
761 #define DRAW_YOFFSET(s)         ((s) == GAME_MODE_INFO  ? DRAW_YOFFSET_INFO(info_mode) :        \
762                                  (s) == GAME_MODE_SETUP ? DRAW_YOFFSET_SETUP(setup_mode) :      \
763                                  menu.draw_yoffset[DRAW_MODE(s)])
764
765 #define EXTRA_SPACING(s)        ((s) == GAME_MODE_INFO   ? EXTRA_SPACING_INFO(info_mode) :      \
766                                  (s) == GAME_MODE_SETUP  ? EXTRA_SPACING_SETUP(setup_mode) :    \
767                                  (s) == GAME_MODE_SCORES ? EXTRA_SPACING_SCORES(info_mode) :    \
768                                  menu.extra_spacing[DRAW_MODE(s)])
769
770 #define mSX                     (SX + DRAW_XOFFSET(game_status))
771 #define mSY                     (SY + DRAW_YOFFSET(game_status))
772
773 #define amSX                    (mSX + align_xoffset)
774 #define amSY                    (mSY + align_yoffset)
775
776 #define NUM_MENU_ENTRIES_ON_SCREEN (menu.list_size[game_status] > 2 ?   \
777                                     menu.list_size[game_status] :       \
778                                     MAX_MENU_ENTRIES_ON_SCREEN)
779
780 #define IN_VIS_MENU(x, y)       IN_FIELD(x, y, SCR_FIELDX, NUM_MENU_ENTRIES_ON_SCREEN)
781
782
783 // title display and control definitions
784
785 #define MAX_NUM_TITLE_SCREENS   (2 * MAX_NUM_TITLE_IMAGES + 2 * MAX_NUM_TITLE_MESSAGES)
786
787 #define NO_DIRECT_LEVEL_SELECT  (-1)
788
789
790 static int num_title_screens = 0;
791
792 struct TitleControlInfo
793 {
794   boolean is_image;
795   boolean initial;
796   boolean first;
797   int local_nr;
798   int sort_priority;
799 };
800
801 struct TitleControlInfo title_controls[MAX_NUM_TITLE_SCREENS];
802
803
804 // main menu display and control definitions
805
806 #define MAIN_CONTROL_NAME                       0
807 #define MAIN_CONTROL_LEVELS                     1
808 #define MAIN_CONTROL_SCORES                     2
809 #define MAIN_CONTROL_EDITOR                     3
810 #define MAIN_CONTROL_INFO                       4
811 #define MAIN_CONTROL_GAME                       5
812 #define MAIN_CONTROL_SETUP                      6
813 #define MAIN_CONTROL_QUIT                       7
814 #define MAIN_CONTROL_PREV_LEVEL                 8
815 #define MAIN_CONTROL_NEXT_LEVEL                 9
816 #define MAIN_CONTROL_FIRST_LEVEL                10
817 #define MAIN_CONTROL_LAST_LEVEL                 11
818 #define MAIN_CONTROL_LEVEL_NUMBER               12
819 #define MAIN_CONTROL_LEVEL_INFO_1               13
820 #define MAIN_CONTROL_LEVEL_INFO_2               14
821 #define MAIN_CONTROL_LEVEL_NAME                 15
822 #define MAIN_CONTROL_LEVEL_AUTHOR               16
823 #define MAIN_CONTROL_LEVEL_YEAR                 17
824 #define MAIN_CONTROL_LEVEL_IMPORTED_FROM        18
825 #define MAIN_CONTROL_LEVEL_IMPORTED_BY          19
826 #define MAIN_CONTROL_LEVEL_TESTED_BY            20
827 #define MAIN_CONTROL_TITLE_1                    21
828 #define MAIN_CONTROL_TITLE_2                    22
829 #define MAIN_CONTROL_TITLE_3                    23
830
831 static char str_main_text_name[10];
832 static char str_main_text_first_level[10];
833 static char str_main_text_last_level[10];
834 static char str_main_text_level_number[10];
835
836 static char network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN + 1];
837
838 static char *main_text_name                     = str_main_text_name;
839 static char *main_text_first_level              = str_main_text_first_level;
840 static char *main_text_last_level               = str_main_text_last_level;
841 static char *main_text_level_number             = str_main_text_level_number;
842 static char *main_text_levels                   = "Levelset";
843 static char *main_text_scores                   = "Hall Of Fame";
844 static char *main_text_editor                   = "Level Creator";
845 static char *main_text_info                     = "Info Screen";
846 static char *main_text_game                     = "Start Game";
847 static char *main_text_setup                    = "Setup";
848 static char *main_text_quit                     = "Quit";
849 static char *main_text_level_name               = level.name;
850 static char *main_text_level_author             = level.author;
851 static char *main_text_level_year               = NULL;
852 static char *main_text_level_imported_from      = NULL;
853 static char *main_text_level_imported_by        = NULL;
854 static char *main_text_level_tested_by          = NULL;
855 static char *main_text_title_1                  = NULL;
856 static char *main_text_title_2                  = NULL;
857 static char *main_text_title_3                  = NULL;
858
859 extern char debug_xsn_mode[];
860
861 struct MainControlInfo
862 {
863   int nr;
864
865   struct MenuPosInfo *pos_button;
866   int button_graphic;
867
868   struct TextPosInfo *pos_text;
869   char **text;
870
871   struct TextPosInfo *pos_input;
872   char **input;
873 };
874
875 static struct MainControlInfo main_controls[] =
876 {
877   {
878     MAIN_CONTROL_NAME,
879     &menu.main.button.name,             IMG_MENU_BUTTON_NAME,
880     &menu.main.text.name,               &main_text_name,
881     &menu.main.input.name,              &setup.player_name,
882   },
883   {
884     MAIN_CONTROL_LEVELS,
885     &menu.main.button.levels,           IMG_MENU_BUTTON_LEVELS,
886     &menu.main.text.levels,             &main_text_levels,
887     NULL,                               NULL,
888   },
889   {
890     MAIN_CONTROL_SCORES,
891     &menu.main.button.scores,           IMG_MENU_BUTTON_SCORES,
892     &menu.main.text.scores,             &main_text_scores,
893     NULL,                               NULL,
894   },
895   {
896     MAIN_CONTROL_EDITOR,
897     &menu.main.button.editor,           IMG_MENU_BUTTON_EDITOR,
898     &menu.main.text.editor,             &main_text_editor,
899     NULL,                               NULL,
900   },
901   {
902     MAIN_CONTROL_INFO,
903     &menu.main.button.info,             IMG_MENU_BUTTON_INFO,
904     &menu.main.text.info,               &main_text_info,
905     NULL,                               NULL,
906   },
907   {
908     MAIN_CONTROL_GAME,
909     &menu.main.button.game,             IMG_MENU_BUTTON_GAME,
910     &menu.main.text.game,               &main_text_game,
911     NULL,                               NULL,
912   },
913   {
914     MAIN_CONTROL_SETUP,
915     &menu.main.button.setup,            IMG_MENU_BUTTON_SETUP,
916     &menu.main.text.setup,              &main_text_setup,
917     NULL,                               NULL,
918   },
919   {
920     MAIN_CONTROL_QUIT,
921     &menu.main.button.quit,             IMG_MENU_BUTTON_QUIT,
922     &menu.main.text.quit,               &main_text_quit,
923     NULL,                               NULL,
924   },
925   {
926     MAIN_CONTROL_PREV_LEVEL,
927     NULL,                               -1,
928     NULL,                               NULL,
929     NULL,                               NULL,
930   },
931   {
932     MAIN_CONTROL_NEXT_LEVEL,
933     NULL,                               -1,
934     NULL,                               NULL,
935     NULL,                               NULL,
936   },
937   {
938     MAIN_CONTROL_FIRST_LEVEL,
939     NULL,                               -1,
940     &menu.main.text.first_level,        &main_text_first_level,
941     NULL,                               NULL,
942   },
943   {
944     MAIN_CONTROL_LAST_LEVEL,
945     NULL,                               -1,
946     &menu.main.text.last_level,         &main_text_last_level,
947     NULL,                               NULL,
948   },
949   {
950     MAIN_CONTROL_LEVEL_NUMBER,
951     NULL,                               -1,
952     &menu.main.text.level_number,       &main_text_level_number,
953     NULL,                               NULL,
954   },
955   {
956     MAIN_CONTROL_LEVEL_INFO_1,
957     NULL,                               -1,
958     &menu.main.text.level_info_1,       NULL,
959     NULL,                               NULL,
960   },
961   {
962     MAIN_CONTROL_LEVEL_INFO_2,
963     NULL,                               -1,
964     &menu.main.text.level_info_2,       NULL,
965     NULL,                               NULL,
966   },
967   {
968     MAIN_CONTROL_LEVEL_NAME,
969     NULL,                               -1,
970     &menu.main.text.level_name,         &main_text_level_name,
971     NULL,                               NULL,
972   },
973   {
974     MAIN_CONTROL_LEVEL_AUTHOR,
975     NULL,                               -1,
976     &menu.main.text.level_author,       &main_text_level_author,
977     NULL,                               NULL,
978   },
979   {
980     MAIN_CONTROL_LEVEL_YEAR,
981     NULL,                               -1,
982     &menu.main.text.level_year,         &main_text_level_year,
983     NULL,                               NULL,
984   },
985   {
986     MAIN_CONTROL_LEVEL_IMPORTED_FROM,
987     NULL,                               -1,
988     &menu.main.text.level_imported_from, &main_text_level_imported_from,
989     NULL,                               NULL,
990   },
991   {
992     MAIN_CONTROL_LEVEL_IMPORTED_BY,
993     NULL,                               -1,
994     &menu.main.text.level_imported_by,  &main_text_level_imported_by,
995     NULL,                               NULL,
996   },
997   {
998     MAIN_CONTROL_LEVEL_TESTED_BY,
999     NULL,                               -1,
1000     &menu.main.text.level_tested_by,    &main_text_level_tested_by,
1001     NULL,                               NULL,
1002   },
1003   {
1004     MAIN_CONTROL_TITLE_1,
1005     NULL,                               -1,
1006     &menu.main.text.title_1,            &main_text_title_1,
1007     NULL,                               NULL,
1008   },
1009   {
1010     MAIN_CONTROL_TITLE_2,
1011     NULL,                               -1,
1012     &menu.main.text.title_2,            &main_text_title_2,
1013     NULL,                               NULL,
1014   },
1015   {
1016     MAIN_CONTROL_TITLE_3,
1017     NULL,                               -1,
1018     &menu.main.text.title_3,            &main_text_title_3,
1019     NULL,                               NULL,
1020   },
1021
1022   {
1023     -1,
1024     NULL,                               -1,
1025     NULL,                               NULL,
1026     NULL,                               NULL,
1027   }
1028 };
1029
1030
1031 static boolean hasLevelSetInfo(void)
1032 {
1033   return (getLevelSetInfoFilename(0) != NULL);
1034 }
1035
1036 static int getTitleScreenGraphic(int nr, boolean initial)
1037 {
1038   return (initial ? IMG_TITLESCREEN_INITIAL_1 : IMG_TITLESCREEN_1) + nr;
1039 }
1040
1041 static struct TitleMessageInfo *getTitleMessageInfo(int nr, boolean initial)
1042 {
1043   return (initial ? &titlemessage_initial[nr] : &titlemessage[nr]);
1044 }
1045
1046 #if 0
1047 static int getTitleScreenGameMode(boolean initial)
1048 {
1049   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
1050 }
1051 #endif
1052
1053 static int getTitleMessageGameMode(boolean initial)
1054 {
1055   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
1056 }
1057
1058 static int getTitleAnimMode(struct TitleControlInfo *tci)
1059 {
1060   int base = (tci->initial ? GAME_MODE_TITLE_INITIAL_1 : GAME_MODE_TITLE_1);
1061
1062   return base + tci->local_nr;
1063 }
1064
1065 #if 0
1066 static int getTitleScreenBackground(boolean initial)
1067 {
1068   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
1069 }
1070 #endif
1071
1072 #if 0
1073 static int getTitleMessageBackground(int nr, boolean initial)
1074 {
1075   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
1076 }
1077 #endif
1078
1079 static int getTitleBackground(int nr, boolean initial, boolean is_image)
1080 {
1081   int base = (is_image ?
1082               (initial ? IMG_BACKGROUND_TITLESCREEN_INITIAL_1 :
1083                          IMG_BACKGROUND_TITLESCREEN_1) :
1084               (initial ? IMG_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
1085                          IMG_BACKGROUND_TITLEMESSAGE_1));
1086   int graphic_global = (initial ? IMG_BACKGROUND_TITLE_INITIAL :
1087                                   IMG_BACKGROUND_TITLE);
1088   int graphic_local = base + nr;
1089
1090   if (graphic_info[graphic_local].bitmap != NULL)
1091     return graphic_local;
1092
1093   if (graphic_info[graphic_global].bitmap != NULL)
1094     return graphic_global;
1095
1096   return IMG_UNDEFINED;
1097 }
1098
1099 static int getTitleSound(struct TitleControlInfo *tci)
1100 {
1101   boolean is_image = tci->is_image;
1102   int initial = tci->initial;
1103   int nr = tci->local_nr;
1104   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
1105   int base = (is_image ?
1106               (initial ? SND_BACKGROUND_TITLESCREEN_INITIAL_1 :
1107                          SND_BACKGROUND_TITLESCREEN_1) :
1108               (initial ? SND_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
1109                          SND_BACKGROUND_TITLEMESSAGE_1));
1110   int sound_global = menu.sound[mode];
1111   int sound_local = base + nr;
1112
1113 #if 0
1114   Debug("screens:getTitleSound", "%d, %d, %d: %d ['%s'], %d ['%s']",
1115         nr, initial, is_image,
1116         sound_global, getSoundListEntry(sound_global)->filename,
1117         sound_local, getSoundListEntry(sound_local)->filename);
1118 #endif
1119
1120   if (!strEqual(getSoundListEntry(sound_local)->filename, UNDEFINED_FILENAME))
1121     return sound_local;
1122
1123   if (!strEqual(getSoundListEntry(sound_global)->filename, UNDEFINED_FILENAME))
1124     return sound_global;
1125
1126   return SND_UNDEFINED;
1127 }
1128
1129 static int getTitleMusic(struct TitleControlInfo *tci)
1130 {
1131   boolean is_image = tci->is_image;
1132   int initial = tci->initial;
1133   int nr = tci->local_nr;
1134   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
1135   int base = (is_image ?
1136               (initial ? MUS_BACKGROUND_TITLESCREEN_INITIAL_1 :
1137                          MUS_BACKGROUND_TITLESCREEN_1) :
1138               (initial ? MUS_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
1139                          MUS_BACKGROUND_TITLEMESSAGE_1));
1140   int music_global = menu.music[mode];
1141   int music_local = base + nr;
1142
1143 #if 0
1144   Debug("screens:getTitleMusic", "%d, %d, %d: %d ['%s'], %d ['%s']",
1145         nr, initial, is_image,
1146         music_global, getMusicListEntry(music_global)->filename,
1147         music_local, getMusicListEntry(music_local)->filename);
1148 #endif
1149
1150   if (!strEqual(getMusicListEntry(music_local)->filename, UNDEFINED_FILENAME))
1151     return music_local;
1152
1153   if (!strEqual(getMusicListEntry(music_global)->filename, UNDEFINED_FILENAME))
1154     return music_global;
1155
1156   return MUS_UNDEFINED;
1157 }
1158
1159 static struct TitleFadingInfo getTitleFading(struct TitleControlInfo *tci)
1160 {
1161   boolean is_image = tci->is_image;
1162   boolean initial = tci->initial;
1163   boolean first = tci->first;
1164   int nr = tci->local_nr;
1165   struct TitleMessageInfo tmi;
1166   struct TitleFadingInfo ti;
1167
1168   tmi = (is_image ? (initial ? (first ?
1169                                 titlescreen_initial_first[nr] :
1170                                 titlescreen_initial[nr])
1171                              : (first ?
1172                                 titlescreen_first[nr] :
1173                                 titlescreen[nr]))
1174                   : (initial ? (first ?
1175                                 titlemessage_initial_first[nr] :
1176                                 titlemessage_initial[nr])
1177                              : (first ?
1178                                 titlemessage_first[nr] :
1179                                 titlemessage[nr])));
1180
1181   ti.fade_mode  = tmi.fade_mode;
1182   ti.fade_delay = tmi.fade_delay;
1183   ti.post_delay = tmi.post_delay;
1184   ti.auto_delay = tmi.auto_delay;
1185   ti.auto_delay_unit = tmi.auto_delay_unit;
1186
1187   return ti;
1188 }
1189
1190 static int compareTitleControlInfo(const void *object1, const void *object2)
1191 {
1192   const struct TitleControlInfo *tci1 = (struct TitleControlInfo *)object1;
1193   const struct TitleControlInfo *tci2 = (struct TitleControlInfo *)object2;
1194   int compare_result;
1195
1196   if (tci1->initial != tci2->initial)
1197     compare_result = (tci1->initial ? -1 : +1);
1198   else if (tci1->sort_priority != tci2->sort_priority)
1199     compare_result = tci1->sort_priority - tci2->sort_priority;
1200   else if (tci1->is_image != tci2->is_image)
1201     compare_result = (tci1->is_image ? -1 : +1);
1202   else
1203     compare_result = tci1->local_nr - tci2->local_nr;
1204
1205   return compare_result;
1206 }
1207
1208 static boolean CheckTitleScreen_BD(int nr, boolean initial)
1209 {
1210   // only show BD style title screen for native BD level sets
1211   if (level.game_engine_type != GAME_ENGINE_TYPE_BD)
1212     return FALSE;
1213
1214   // only show BD style title screen for first title screen of a level set
1215   if (initial || nr != 0)
1216     return FALSE;
1217
1218   int graphic = getTitleScreenGraphic(nr, initial);
1219   Bitmap *bitmap = graphic_info[graphic].bitmap;
1220
1221   // only show BD style title screen if no other title screen defined
1222   if (bitmap != NULL)
1223     return FALSE;
1224
1225   // check if BD style title screen defined
1226   return (GetTitleScreenBitmaps_BD() != NULL);
1227 }
1228
1229 static void InitializeTitleControlsExt_AddTitleInfo(boolean is_image,
1230                                                     boolean initial,
1231                                                     int nr, int sort_priority)
1232 {
1233   title_controls[num_title_screens].is_image = is_image;
1234   title_controls[num_title_screens].initial = initial;
1235   title_controls[num_title_screens].local_nr = nr;
1236   title_controls[num_title_screens].sort_priority = sort_priority;
1237
1238   title_controls[num_title_screens].first = FALSE;      // will be set later
1239
1240   num_title_screens++;
1241 }
1242
1243 static void InitializeTitleControls_CheckTitleInfo(boolean initial)
1244 {
1245   int i;
1246
1247   for (i = 0; i < MAX_NUM_TITLE_IMAGES; i++)
1248   {
1249     int graphic = getTitleScreenGraphic(i, initial);
1250     Bitmap *bitmap = graphic_info[graphic].bitmap;
1251     int sort_priority = graphic_info[graphic].sort_priority;
1252     boolean has_title_screen = (bitmap != NULL);
1253
1254     // check for optional title screen of native BD style level set
1255     if (CheckTitleScreen_BD(i, initial))
1256       has_title_screen = TRUE;
1257
1258     if (has_title_screen)
1259       InitializeTitleControlsExt_AddTitleInfo(TRUE, initial, i, sort_priority);
1260   }
1261
1262   for (i = 0; i < MAX_NUM_TITLE_MESSAGES; i++)
1263   {
1264     struct TitleMessageInfo *tmi = getTitleMessageInfo(i, initial);
1265     char *filename = getLevelSetTitleMessageFilename(i, initial);
1266     int sort_priority = tmi->sort_priority;
1267
1268     if (filename != NULL)
1269       InitializeTitleControlsExt_AddTitleInfo(FALSE, initial, i, sort_priority);
1270   }
1271 }
1272
1273 static void InitializeTitleControls(boolean show_title_initial)
1274 {
1275   num_title_screens = 0;
1276
1277   // 1st step: initialize title screens for game start (only when starting)
1278   if (show_title_initial)
1279     InitializeTitleControls_CheckTitleInfo(TRUE);
1280
1281   // 2nd step: initialize title screens for current level set
1282   InitializeTitleControls_CheckTitleInfo(FALSE);
1283
1284   // sort title screens according to sort_priority and title number
1285   qsort(title_controls, num_title_screens, sizeof(struct TitleControlInfo),
1286         compareTitleControlInfo);
1287
1288   // mark first title screen
1289   title_controls[0].first = TRUE;
1290 }
1291
1292 static boolean visibleMenuPos(struct MenuPosInfo *pos)
1293 {
1294   return (pos != NULL && pos->x != -1 && pos->y != -1);
1295 }
1296
1297 static boolean visibleTextPos(struct TextPosInfo *pos)
1298 {
1299   return (pos != NULL && pos->x != -1 && pos->y != -1);
1300 }
1301
1302 static void InitializeMainControls(void)
1303 {
1304   boolean local_team_mode = (!network.enabled && setup.team_mode);
1305   int i;
1306
1307   // set main control text values to dynamically determined values
1308   sprintf(main_text_name,         "%s",   local_team_mode ? "Team:" : "Name:");
1309
1310   strcpy(main_text_first_level,  int2str(leveldir_current->first_level,
1311                                          menu.main.text.first_level.size));
1312   strcpy(main_text_last_level,   int2str(leveldir_current->last_level,
1313                                          menu.main.text.last_level.size));
1314   strcpy(main_text_level_number, int2str(level_nr,
1315                                          menu.main.text.level_number.size));
1316
1317   main_text_level_year          = leveldir_current->year;
1318   main_text_level_imported_from = leveldir_current->imported_from;
1319   main_text_level_imported_by   = leveldir_current->imported_by;
1320   main_text_level_tested_by     = leveldir_current->tested_by;
1321
1322   main_text_title_1 = getConfigProgramTitleString();
1323   main_text_title_2 = getConfigProgramCopyrightString();
1324   main_text_title_3 = getConfigProgramCompanyString();
1325
1326   // set main control screen positions to dynamically determined values
1327   for (i = 0; main_controls[i].nr != -1; i++)
1328   {
1329     struct MainControlInfo *mci = &main_controls[i];
1330     int nr                         = mci->nr;
1331     struct MenuPosInfo *pos_button = mci->pos_button;
1332     struct TextPosInfo *pos_text   = mci->pos_text;
1333     struct TextPosInfo *pos_input  = mci->pos_input;
1334     char *text                     = (mci->text  ? *mci->text  : NULL);
1335     char *input                    = (mci->input ? *mci->input : NULL);
1336     int button_graphic             = mci->button_graphic;
1337     int font_text                  = (pos_text  ? pos_text->font  : -1);
1338     int font_input                 = (pos_input ? pos_input->font : -1);
1339
1340     int font_text_width   = (font_text  != -1 ? getFontWidth(font_text)   : 0);
1341     int font_text_height  = (font_text  != -1 ? getFontHeight(font_text)  : 0);
1342     int font_input_width  = (font_input != -1 ? getFontWidth(font_input)  : 0);
1343     int font_input_height = (font_input != -1 ? getFontHeight(font_input) : 0);
1344     int text_chars  = (text  != NULL ? strlen(text)  : 0);
1345     int input_chars = (input != NULL ? strlen(input) : 0);
1346
1347     int button_width =
1348       (button_graphic != -1 ? graphic_info[button_graphic].width  : 0);
1349     int button_height =
1350       (button_graphic != -1 ? graphic_info[button_graphic].height : 0);
1351     int text_width   = font_text_width * text_chars;
1352     int text_height  = font_text_height;
1353     int input_width  = font_input_width * input_chars;
1354     int input_height = font_input_height;
1355
1356     if (nr == MAIN_CONTROL_NAME)
1357     {
1358       menu.main.input.name.width  = input_width;
1359       menu.main.input.name.height = input_height;
1360     }
1361
1362     if (pos_button != NULL)             // (x/y may be -1/-1 here)
1363     {
1364       pos_button->width  = button_width;
1365       pos_button->height = button_height;
1366     }
1367
1368     if (pos_text != NULL)               // (x/y may be -1/-1 here)
1369     {
1370       // calculate text size -- needed for text alignment
1371       boolean calculate_text_size = (text != NULL);
1372
1373       if (pos_text->width == -1 || calculate_text_size)
1374         pos_text->width = text_width;
1375       if (pos_text->height == -1 || calculate_text_size)
1376         pos_text->height = text_height;
1377
1378       if (visibleMenuPos(pos_button))
1379       {
1380         if (pos_text->x == -1)
1381           pos_text->x = pos_button->x + pos_button->width;
1382         if (pos_text->y == -1)
1383           pos_text->y =
1384             pos_button->y + (pos_button->height - pos_text->height) / 2;
1385       }
1386     }
1387
1388     if (pos_input != NULL)              // (x/y may be -1/-1 here)
1389     {
1390       if (visibleTextPos(pos_text))
1391       {
1392         if (pos_input->x == -1)
1393           pos_input->x = pos_text->x + pos_text->width;
1394         if (pos_input->y == -1)
1395           pos_input->y = pos_text->y;
1396       }
1397
1398       if (pos_input->width == -1)
1399         pos_input->width = input_width;
1400       if (pos_input->height == -1)
1401         pos_input->height = input_height;
1402     }
1403   }
1404 }
1405
1406 static void DrawPressedGraphicThruMask(int dst_x, int dst_y,
1407                                        int graphic, boolean pressed)
1408 {
1409   struct GraphicInfo *g = &graphic_info[graphic];
1410   Bitmap *src_bitmap;
1411   int src_x, src_y;
1412   int xoffset = (pressed ? g->pressed_xoffset : 0);
1413   int yoffset = (pressed ? g->pressed_yoffset : 0);
1414
1415   getFixedGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
1416
1417   BlitBitmapMasked(src_bitmap, drawto, src_x + xoffset, src_y + yoffset,
1418                    g->width, g->height, dst_x, dst_y);
1419 }
1420
1421 static void DrawCursorAndText_Main_Ext(int nr, boolean active_text,
1422                                        boolean active_input,
1423                                        boolean pressed_button)
1424 {
1425   int i;
1426
1427   for (i = 0; main_controls[i].nr != -1; i++)
1428   {
1429     struct MainControlInfo *mci = &main_controls[i];
1430
1431     if (mci->nr == nr || nr == -1)
1432     {
1433       struct MenuPosInfo *pos_button = mci->pos_button;
1434       struct TextPosInfo *pos_text   = mci->pos_text;
1435       struct TextPosInfo *pos_input  = mci->pos_input;
1436       char *text                     = (mci->text  ? *mci->text  : NULL);
1437       char *input                    = (mci->input ? *mci->input : NULL);
1438       int button_graphic             = mci->button_graphic;
1439       int font_text                  = (pos_text  ? pos_text->font  : -1);
1440       int font_input                 = (pos_input ? pos_input->font : -1);
1441
1442       if (active_text)
1443       {
1444         button_graphic = BUTTON_ACTIVE(button_graphic);
1445         font_text = FONT_ACTIVE(font_text);
1446       }
1447
1448       if (active_input)
1449       {
1450         font_input = FONT_ACTIVE(font_input);
1451       }
1452
1453       if (visibleMenuPos(pos_button))
1454       {
1455         struct MenuPosInfo *pos = pos_button;
1456         int x = mSX + pos->x;
1457         int y = mSY + pos->y;
1458
1459         DrawBackgroundForGraphic(x, y, pos->width, pos->height, button_graphic);
1460         DrawPressedGraphicThruMask(x, y, button_graphic, pressed_button);
1461       }
1462
1463       if (visibleTextPos(pos_text) && text != NULL)
1464       {
1465         struct TextPosInfo *pos = pos_text;
1466         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1467         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1468
1469 #if 1
1470         // (check why/if this is needed)
1471         DrawBackgroundForFont(x, y, pos->width, pos->height, font_text);
1472 #endif
1473         DrawText(x, y, text, font_text);
1474       }
1475
1476       if (visibleTextPos(pos_input) && input != NULL)
1477       {
1478         struct TextPosInfo *pos = pos_input;
1479         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1480         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1481
1482 #if 1
1483         // (check why/if this is needed)
1484         DrawBackgroundForFont(x, y, pos->width, pos->height, font_input);
1485 #endif
1486         DrawText(x, y, input, font_input);
1487       }
1488     }
1489   }
1490 }
1491
1492 static void DrawCursorAndText_Main(int nr, boolean active_text,
1493                                    boolean pressed_button)
1494 {
1495   DrawCursorAndText_Main_Ext(nr, active_text, FALSE, pressed_button);
1496 }
1497
1498 #if 0
1499 static void DrawCursorAndText_Main_Input(int nr, boolean active_text,
1500                                          boolean pressed_button)
1501 {
1502   DrawCursorAndText_Main_Ext(nr, active_text, TRUE, pressed_button);
1503 }
1504 #endif
1505
1506 static struct MainControlInfo *getMainControlInfo(int nr)
1507 {
1508   int i;
1509
1510   for (i = 0; main_controls[i].nr != -1; i++)
1511     if (main_controls[i].nr == nr)
1512       return &main_controls[i];
1513
1514   return NULL;
1515 }
1516
1517 static boolean insideMenuPosRect(struct MenuPosInfo *rect, int x, int y)
1518 {
1519   if (rect == NULL)
1520     return FALSE;
1521
1522   int rect_x = ALIGNED_TEXT_XPOS(rect);
1523   int rect_y = ALIGNED_TEXT_YPOS(rect);
1524
1525   return (x >= rect_x && x < rect_x + rect->width &&
1526           y >= rect_y && y < rect_y + rect->height);
1527 }
1528
1529 static boolean insideTextPosRect(struct TextPosInfo *rect, int x, int y)
1530 {
1531   if (rect == NULL)
1532     return FALSE;
1533
1534   int rect_x = ALIGNED_TEXT_XPOS(rect);
1535   int rect_y = ALIGNED_TEXT_YPOS(rect);
1536
1537 #if 0
1538   Debug("screens:insideTextPosRect",
1539         "(%d, %d), (%d, %d) [%d, %d] (%d, %d) => %d",
1540         x, y, rect_x, rect_y, rect->x, rect->y, rect->width, rect->height,
1541         (x >= rect_x && x < rect_x + rect->width &&
1542          y >= rect_y && y < rect_y + rect->height));
1543 #endif
1544
1545   return (x >= rect_x && x < rect_x + rect->width &&
1546           y >= rect_y && y < rect_y + rect->height);
1547 }
1548
1549 static boolean insidePreviewRect(struct PreviewInfo *preview, int x, int y)
1550 {
1551   int rect_width  = preview->xsize * preview->tile_size;
1552   int rect_height = preview->ysize * preview->tile_size;
1553   int rect_x = ALIGNED_XPOS(preview->x, rect_width,  preview->align);
1554   int rect_y = ALIGNED_YPOS(preview->y, rect_height, preview->valign);
1555
1556   return (x >= rect_x && x < rect_x + rect_width &&
1557           y >= rect_y && y < rect_y + rect_height);
1558 }
1559
1560 static void AdjustScrollbar(int id, int items_max, int items_visible,
1561                             int item_position)
1562 {
1563   struct GadgetInfo *gi = screen_gadget[id];
1564
1565   if (item_position > items_max - items_visible)
1566     item_position = items_max - items_visible;
1567
1568   ModifyGadget(gi, GDI_SCROLLBAR_ITEMS_MAX, items_max,
1569                GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
1570                GDI_SCROLLBAR_ITEM_POSITION, item_position, GDI_END);
1571 }
1572
1573 static void AdjustChooseTreeScrollbar(TreeInfo *ti, int id)
1574 {
1575   AdjustScrollbar(id, numTreeInfoInGroup(ti), NUM_MENU_ENTRIES_ON_SCREEN,
1576                   ti->cl_first);
1577 }
1578
1579 static void clearMenuListArea(void)
1580 {
1581   int scrollbar_xpos = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
1582
1583   // correct scrollbar position if placed outside menu (playfield) area
1584   if (scrollbar_xpos > SX + SC_SCROLLBAR_XPOS)
1585     scrollbar_xpos = SX + SC_SCROLLBAR_XPOS;
1586
1587   // clear menu list area, but not title or scrollbar
1588   DrawBackground(mSX, mSY + MENU_SCREEN_START_YPOS * 32,
1589                  scrollbar_xpos - mSX, NUM_MENU_ENTRIES_ON_SCREEN * 32);
1590
1591   // special compatibility handling for "Snake Bite" graphics set
1592   if (strPrefix(leveldir_current->identifier, "snake_bite"))
1593     ClearRectangle(drawto, mSX, mSY + MENU_SCREEN_START_YPOS * 32,
1594                    scrollbar_xpos - mSX, NUM_MENU_ENTRIES_ON_SCREEN * 32);
1595 }
1596
1597 static void drawCursorExt(int xpos, int ypos, boolean active, int graphic)
1598 {
1599   static int cursor_array[MAX_LEV_FIELDY];
1600   int x = amSX + TILEX * xpos;
1601   int y = amSY + TILEY * (MENU_SCREEN_START_YPOS + ypos);
1602
1603   if (xpos == 0)
1604   {
1605     if (graphic != -1)
1606       cursor_array[ypos] = graphic;
1607     else
1608       graphic = cursor_array[ypos];
1609   }
1610
1611   if (active)
1612     graphic = BUTTON_ACTIVE(graphic);
1613
1614   DrawBackgroundForGraphic(x, y, TILEX, TILEY, graphic);
1615   DrawFixedGraphicThruMaskExt(drawto, x, y, graphic, 0);
1616 }
1617
1618 static void initCursor(int ypos, int graphic)
1619 {
1620   drawCursorExt(0, ypos, FALSE, graphic);
1621 }
1622
1623 static void drawCursor(int ypos, boolean active)
1624 {
1625   drawCursorExt(0, ypos, active, -1);
1626 }
1627
1628 static void drawCursorXY(int xpos, int ypos, int graphic)
1629 {
1630   drawCursorExt(xpos, ypos, FALSE, graphic);
1631 }
1632
1633 static void drawChooseTreeCursor(int ypos, boolean active)
1634 {
1635   drawCursorExt(0, ypos, active, -1);
1636 }
1637
1638 static int getChooseTreeEditFont(boolean active)
1639 {
1640   return (active ? FONT_MENU_2_ACTIVE : FONT_MENU_2);
1641 }
1642
1643 static int getChooseTreeEditXPos(int pos)
1644 {
1645   boolean has_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->mapped;
1646   int xoffset = (has_scrollbar ? -1 : 0);
1647   int xpos = MENU_SCREEN_TEXT2_XPOS + xoffset;
1648   int sx = amSX + xpos * TILEX;
1649   int font_nr = getChooseTreeEditFont(FALSE);
1650   int width = getTextWidth(STR_CHOOSE_TREE_EDIT, font_nr);
1651
1652   return (pos == POS_RIGHT ? sx + width - 1 : sx);
1653 }
1654
1655 static int getChooseTreeEditYPos(int ypos_raw)
1656 {
1657   int ypos = MENU_SCREEN_START_YPOS + ypos_raw;
1658   int sy = amSY + ypos * TILEY;
1659
1660   return sy;
1661 }
1662
1663 static int getChooseTreeEditXPosReal(int pos)
1664 {
1665   int xpos = getChooseTreeEditXPos(pos);
1666   int font_nr = getChooseTreeEditFont(FALSE);
1667   int font_xoffset = getFontDrawOffsetX(font_nr);
1668
1669   return xpos + font_xoffset;
1670 }
1671
1672 static void drawChooseTreeEdit(int ypos_raw, boolean active)
1673 {
1674   int sx = getChooseTreeEditXPos(POS_LEFT);
1675   int sy = getChooseTreeEditYPos(ypos_raw);
1676   int font_nr = getChooseTreeEditFont(active);
1677
1678   DrawText(sx, sy, STR_CHOOSE_TREE_EDIT, font_nr);
1679 }
1680
1681 static void DrawInfoScreen_Headline(int screen_nr, int num_screens,
1682                                     int use_global_screens)
1683 {
1684   char *info_text_title_1 = getInfoScreenTitle_Generic();
1685   char info_text_title_2[MAX_LINE_LEN + 1];
1686
1687   if (num_screens > 1)
1688   {
1689     sprintf(info_text_title_2, "Page %d of %d", screen_nr + 1, num_screens);
1690   }
1691   else
1692   {
1693     char *text_format = (use_global_screens ? "for %s" : "for \"%s\"");
1694     int text_format_len = strlen(text_format) - strlen("%s");
1695     int max_text_len = SXSIZE / getFontWidth(FONT_TITLE_2);
1696     int max_name_len = max_text_len - text_format_len;
1697     char name_cut[max_name_len];
1698     char *name_full = (use_global_screens ? getProgramTitleString() :
1699                        leveldir_current->name);
1700
1701     snprintf(name_cut, max_name_len, "%s", name_full);
1702     snprintf(info_text_title_2, max_text_len, text_format, name_cut);
1703   }
1704
1705   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, info_text_title_1);
1706   DrawTextSCentered(MENU_TITLE2_YPOS, FONT_TITLE_2, info_text_title_2);
1707 }
1708
1709 static void DrawTitleScreenImage(int nr, boolean initial)
1710 {
1711   static int frame_counter = 0;
1712   int graphic = getTitleScreenGraphic(nr, initial);
1713   Bitmap *bitmap = graphic_info[graphic].bitmap;
1714   Bitmap *bitmap_background = NULL;
1715   int draw_masked = graphic_info[graphic].draw_masked;
1716   int width  = graphic_info[graphic].width;
1717   int height = graphic_info[graphic].height;
1718   int src_x = graphic_info[graphic].src_x;
1719   int src_y = graphic_info[graphic].src_y;
1720   int dst_x, dst_y;
1721
1722   // check for optional title screen of native BD style level set
1723   if (CheckTitleScreen_BD(nr, initial))
1724   {
1725     Bitmap **title_screen_bitmaps = GetTitleScreenBitmaps_BD();
1726
1727     bitmap            = title_screen_bitmaps[0];
1728     bitmap_background = title_screen_bitmaps[1];
1729
1730     if (bitmap != NULL)
1731     {
1732       width  = bitmap->width;
1733       height = bitmap->height;
1734       src_x = 0;
1735       src_y = 0;
1736     }
1737   }
1738
1739   if (bitmap == NULL)
1740     return;
1741
1742   if (width > WIN_XSIZE)
1743   {
1744     // image width too large for window => center image horizontally
1745     src_x = (width - WIN_XSIZE) / 2;
1746     width = WIN_XSIZE;
1747   }
1748
1749   if (height > WIN_YSIZE)
1750   {
1751     // image height too large for window => center image vertically
1752     src_y = (height - WIN_YSIZE) / 2;
1753     height = WIN_YSIZE;
1754   }
1755
1756   // always display title screens centered
1757   dst_x = (WIN_XSIZE - width) / 2;
1758   dst_y = (WIN_YSIZE - height) / 2;
1759
1760   SetDrawBackgroundMask(REDRAW_ALL);
1761   SetWindowBackgroundImage(getTitleBackground(nr, initial, TRUE));
1762
1763   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1764
1765   boolean draw_masked_final = (DrawingOnBackground(dst_x, dst_y) && draw_masked);
1766
1767   if (bitmap_background != NULL)
1768   {
1769     int size = bitmap_background->height - bitmap->height;
1770     int offset = frame_counter++ % size;
1771
1772     BlitBitmap(bitmap_background, drawto, src_x, src_y + offset, width, height, dst_x, dst_y);
1773
1774     draw_masked_final = TRUE;
1775   }
1776
1777   if (draw_masked_final)
1778     BlitBitmapMasked(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1779   else
1780     BlitBitmap(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1781
1782   redraw_mask = REDRAW_ALL;
1783 }
1784
1785 static void DrawTitleScreenMessage(int nr, boolean initial)
1786 {
1787   char *filename = getLevelSetTitleMessageFilename(nr, initial);
1788   struct TitleMessageInfo *tmi = getTitleMessageInfo(nr, initial);
1789
1790   if (filename == NULL)
1791     return;
1792
1793   // force TITLE font on title message screen
1794   SetFontStatus(getTitleMessageGameMode(initial));
1795
1796   // if chars *and* width set to "-1", automatically determine width
1797   if (tmi->chars == -1 && tmi->width == -1)
1798     tmi->width = viewport.window[game_status].width;
1799
1800   // if lines *and* height set to "-1", automatically determine height
1801   if (tmi->lines == -1 && tmi->height == -1)
1802     tmi->height = viewport.window[game_status].height;
1803
1804   // if chars set to "-1", automatically determine by text and font width
1805   if (tmi->chars == -1)
1806     tmi->chars = tmi->width / getFontWidth(tmi->font);
1807   else
1808     tmi->width = tmi->chars * getFontWidth(tmi->font);
1809
1810   // if lines set to "-1", automatically determine by text and font height
1811   if (tmi->lines == -1)
1812     tmi->lines = tmi->height / getFontHeight(tmi->font);
1813   else
1814     tmi->height = tmi->lines * getFontHeight(tmi->font);
1815
1816   // if x set to "-1", automatically determine by width and alignment
1817   if (tmi->x == -1)
1818     tmi->x = -1 * ALIGNED_XPOS(0, tmi->width, tmi->align);
1819
1820   // if y set to "-1", automatically determine by height and alignment
1821   if (tmi->y == -1)
1822     tmi->y = -1 * ALIGNED_YPOS(0, tmi->height, tmi->valign);
1823
1824   SetDrawBackgroundMask(REDRAW_ALL);
1825   SetWindowBackgroundImage(getTitleBackground(nr, initial, FALSE));
1826
1827   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1828
1829   DrawTextFile(ALIGNED_TEXT_XPOS(tmi), ALIGNED_TEXT_YPOS(tmi),
1830                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
1831                tmi->autowrap, tmi->centered, tmi->parse_comments);
1832
1833   ResetFontStatus();
1834 }
1835
1836 static void DrawTitleScreen(void)
1837 {
1838   KeyboardAutoRepeatOff();
1839
1840   HandleTitleScreen(0, 0, 0, 0, MB_MENU_INITIALIZE);
1841 }
1842
1843 static boolean CheckTitleScreen(boolean levelset_has_changed)
1844 {
1845   static boolean show_title_initial = TRUE;
1846   boolean show_titlescreen = FALSE;
1847
1848   // needed to be able to skip title screen, if no image or message defined
1849   InitializeTitleControls(show_title_initial);
1850
1851   if (setup.show_titlescreen && (show_title_initial || levelset_has_changed))
1852     show_titlescreen = TRUE;
1853
1854   // show initial title images and messages only once at program start
1855   show_title_initial = FALSE;
1856
1857   return (show_titlescreen && num_title_screens > 0);
1858 }
1859
1860 void DrawMainMenu(void)
1861 {
1862   static LevelDirTree *leveldir_last_valid = NULL;
1863   boolean levelset_has_changed = FALSE;
1864   int fade_mask = REDRAW_FIELD;
1865
1866   LimitScreenUpdates(FALSE);
1867
1868   FadeSetLeaveScreen();
1869
1870   // do not fade out here -- function may continue and fade on editor screen
1871
1872   UnmapAllGadgets();
1873   FadeMenuSoundsAndMusic();
1874
1875   ExpireSoundLoops(FALSE);
1876
1877   KeyboardAutoRepeatOn();
1878
1879   audio.sound_deactivated = FALSE;
1880
1881   GetPlayerConfig();
1882
1883   // needed if last screen was the playing screen, invoked from level editor
1884   if (level_editor_test_game)
1885   {
1886     CloseDoor(DOOR_CLOSE_ALL);
1887
1888     SetGameStatus(GAME_MODE_EDITOR);
1889
1890     DrawLevelEd();
1891
1892     return;
1893   }
1894
1895   // needed if last screen was the playing screen, invoked from hall of fame
1896   if (score_info_tape_play)
1897   {
1898     CloseDoor(DOOR_CLOSE_ALL);
1899
1900     SetGameStatus(GAME_MODE_SCOREINFO);
1901
1902     DrawScoreInfo(scores.last_entry_nr);
1903
1904     return;
1905   }
1906
1907   // reset flag to continue playing next level from hall of fame
1908   scores.continue_playing = FALSE;
1909
1910   // leveldir_current may be invalid (level group, parent link, node copy)
1911   leveldir_current = getValidLevelSeries(leveldir_current, leveldir_last_valid);
1912
1913   if (leveldir_current != leveldir_last_valid)
1914   {
1915     // level setup config may have been loaded to "last played" tree node copy,
1916     // but "leveldir_current" now points to the "original" level set tree node,
1917     // in which case "handicap_level" may still default to the first level
1918     LoadLevelSetup_SeriesInfo();
1919
1920     UpdateLastPlayedLevels_TreeInfo();
1921
1922     levelset_has_changed = TRUE;
1923   }
1924
1925   // store valid level series information
1926   leveldir_last_valid = leveldir_current;
1927
1928   // store first level of this level set for "level_nr" style animations
1929   SetAnimationFirstLevel(leveldir_current->first_level);
1930
1931   // level_nr may have been set to value over handicap with level editor
1932   if (setup.handicap && level_nr > leveldir_current->handicap_level)
1933     level_nr = leveldir_current->handicap_level;
1934
1935   LoadLevel(level_nr);
1936   LoadScore(level_nr);
1937
1938   SaveLevelSetup_SeriesInfo();
1939
1940   // needed if last screen (level choice) changed graphics, sounds or music
1941   ReloadCustomArtwork(0);
1942
1943   if (CheckTitleScreen(levelset_has_changed))
1944   {
1945     SetGameStatus(GAME_MODE_TITLE);
1946
1947     DrawTitleScreen();
1948
1949     return;
1950   }
1951
1952   if (redraw_mask & REDRAW_ALL)
1953     fade_mask = REDRAW_ALL;
1954
1955   if (CheckFadeAll())
1956     fade_mask = REDRAW_ALL;
1957
1958   FadeOut(fade_mask);
1959
1960   // needed if different viewport properties defined for menues
1961   ChangeViewportPropertiesIfNeeded();
1962
1963   SetDrawtoField(DRAW_TO_BACKBUFFER);
1964
1965   // set this after "ChangeViewportPropertiesIfNeeded()" (which may reset it)
1966   SetDrawDeactivationMask(REDRAW_NONE);
1967   SetDrawBackgroundMask(REDRAW_FIELD);
1968
1969   SetMainBackgroundImage(IMG_BACKGROUND_MAIN);
1970
1971 #if 0
1972   if (fade_mask == REDRAW_ALL)
1973     RedrawGlobalBorder();
1974 #endif
1975
1976   ClearField();
1977
1978   InitializeMainControls();
1979
1980   DrawCursorAndText_Main(-1, FALSE, FALSE);
1981   DrawPreviewLevelInitial();
1982   DrawNetworkPlayers();
1983
1984   HandleMainMenu(0, 0, 0, 0, MB_MENU_INITIALIZE);
1985
1986   TapeStop();
1987   if (TAPE_IS_EMPTY(tape))
1988     LoadTape(level_nr);
1989   DrawCompleteVideoDisplay();
1990
1991   PlayMenuSoundsAndMusic();
1992
1993   // create gadgets for main menu screen
1994   FreeScreenGadgets();
1995   CreateScreenGadgets();
1996
1997   // may be required if audio buttons shown on tape and changed in setup menu
1998   FreeGameButtons();
1999   CreateGameButtons();
2000
2001   // map gadgets for main menu screen
2002   MapTapeButtons();
2003   MapScreenMenuGadgets(SCREEN_MASK_MAIN);
2004   UpdateScreenMenuGadgets(SCREEN_MASK_MAIN_HAS_SOLUTION, hasSolutionTape());
2005   UpdateScreenMenuGadgets(SCREEN_MASK_MAIN_HAS_SET_INFO, hasLevelSetInfo());
2006
2007   // copy actual game door content to door double buffer for OpenDoor()
2008   BlitBitmap(drawto, bitmap_db_door_1, DX, DY, DXSIZE, DYSIZE, 0, 0);
2009   BlitBitmap(drawto, bitmap_db_door_2, VX, VY, VXSIZE, VYSIZE, 0, 0);
2010
2011   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
2012
2013   DrawMaskedBorder(fade_mask);
2014
2015   FadeIn(fade_mask);
2016   FadeSetEnterMenu();
2017
2018   // update screen area with special editor door
2019   redraw_mask |= REDRAW_ALL;
2020   BackToFront();
2021
2022   SetMouseCursor(CURSOR_DEFAULT);
2023
2024   OpenDoor(DOOR_CLOSE_1 | DOOR_OPEN_2);
2025
2026   SyncEmscriptenFilesystem();
2027
2028   // needed once after program start or after user change
2029   CheckApiServerTasks();
2030 }
2031
2032 static void gotoTopLevelDir(void)
2033 {
2034   // move upwards until inside (but not above) top level directory
2035   while (leveldir_current->node_parent &&
2036          !strEqual(leveldir_current->node_parent->subdir, STRING_TOP_DIRECTORY))
2037   {
2038     // write a "path" into level tree for easy navigation to last level
2039     if (leveldir_current->node_parent->node_group->cl_first == -1)
2040     {
2041       int num_leveldirs = numTreeInfoInGroup(leveldir_current);
2042       int leveldir_pos = getPosFromTreeInfo(leveldir_current);
2043       int num_page_entries = MIN(num_leveldirs, NUM_MENU_ENTRIES_ON_SCREEN);
2044       int cl_first, cl_cursor;
2045
2046       cl_first = MAX(0, leveldir_pos - num_page_entries + 1);
2047       cl_cursor = leveldir_pos - cl_first;
2048
2049       leveldir_current->node_parent->node_group->cl_first = cl_first;
2050       leveldir_current->node_parent->node_group->cl_cursor = cl_cursor;
2051     }
2052
2053     leveldir_current = leveldir_current->node_parent;
2054   }
2055 }
2056
2057 static unsigned int getAutoDelayCounter(struct TitleFadingInfo *fi)
2058 {
2059   boolean use_frame_counter = (fi->auto_delay_unit == AUTO_DELAY_UNIT_FRAMES);
2060
2061   return (use_frame_counter ? video.frame_counter : Counter());
2062 }
2063
2064 static boolean TitleAutoDelayReached(unsigned int *counter_var,
2065                                      struct TitleFadingInfo *fi)
2066 {
2067   return DelayReachedExt2(counter_var, fi->auto_delay, getAutoDelayCounter(fi));
2068 }
2069
2070 static void ResetTitleAutoDelay(unsigned int *counter_var,
2071                                 struct TitleFadingInfo *fi)
2072 {
2073   *counter_var = getAutoDelayCounter(fi);
2074 }
2075
2076 void HandleTitleScreen(int mx, int my, int dx, int dy, int button)
2077 {
2078   static unsigned int title_delay = 0;
2079   static int title_screen_nr = 0;
2080   static int last_sound = -1, last_music = -1;
2081   boolean return_to_main_menu = FALSE;
2082   struct TitleControlInfo *tci;
2083   int sound, music;
2084
2085   if (button == MB_MENU_INITIALIZE)
2086   {
2087     title_delay = 0;
2088     title_screen_nr = 0;
2089     tci = &title_controls[title_screen_nr];
2090
2091     SetAnimStatus(getTitleAnimMode(tci));
2092
2093     last_sound = SND_UNDEFINED;
2094     last_music = MUS_UNDEFINED;
2095
2096     if (num_title_screens != 0)
2097     {
2098       FadeSetEnterScreen();
2099
2100       // use individual title fading instead of global "enter screen" fading
2101       fading = getTitleFading(tci);
2102     }
2103
2104     if (game_status_last_screen == GAME_MODE_INFO)
2105     {
2106       if (num_title_screens == 0)
2107       {
2108         // switch game mode from title screen mode back to info screen mode
2109         SetGameStatus(GAME_MODE_INFO);
2110
2111         // store that last screen was info screen, not main menu screen
2112         game_status_last_screen = GAME_MODE_INFO;
2113
2114         DrawInfoScreen_NotAvailable("Title screen information:",
2115                                     "No title screen for this level set.");
2116         return;
2117       }
2118     }
2119
2120     FadeMenuSoundsAndMusic();
2121
2122     FadeOut(REDRAW_ALL);
2123
2124     // title screens may have different window size
2125     ChangeViewportPropertiesIfNeeded();
2126
2127     // only required to update logic for redrawing global border
2128     ClearField();
2129
2130     if (tci->is_image)
2131       DrawTitleScreenImage(tci->local_nr, tci->initial);
2132     else
2133       DrawTitleScreenMessage(tci->local_nr, tci->initial);
2134
2135     sound = getTitleSound(tci);
2136     music = getTitleMusic(tci);
2137
2138     if (sound != last_sound)
2139       PlayMenuSoundExt(sound);
2140     if (music != last_music)
2141       PlayMenuMusicExt(music);
2142
2143     last_sound = sound;
2144     last_music = music;
2145
2146     SetMouseCursor(CURSOR_NONE);
2147
2148     FadeIn(REDRAW_ALL);
2149
2150     ResetTitleAutoDelay(&title_delay, &fading);
2151
2152     return;
2153   }
2154
2155   if (fading.auto_delay > 0 && TitleAutoDelayReached(&title_delay, &fading))
2156     button = MB_MENU_CHOICE;
2157
2158   if (button == MB_MENU_LEAVE)
2159   {
2160     return_to_main_menu = TRUE;
2161   }
2162   else if (button == MB_MENU_CHOICE || dx)
2163   {
2164     if (game_status_last_screen == GAME_MODE_INFO && num_title_screens == 0)
2165     {
2166       SetGameStatus(GAME_MODE_INFO);
2167
2168       info_mode = INFO_MODE_MAIN;
2169
2170       DrawInfoScreen();
2171
2172       return;
2173     }
2174
2175     title_screen_nr +=
2176       (game_status_last_screen == GAME_MODE_INFO && dx < 0 ? -1 : +1);
2177
2178     if (title_screen_nr >= 0 && title_screen_nr < num_title_screens)
2179     {
2180       tci = &title_controls[title_screen_nr];
2181
2182       SetAnimStatus(getTitleAnimMode(tci));
2183
2184       sound = getTitleSound(tci);
2185       music = getTitleMusic(tci);
2186
2187       if (last_sound != SND_UNDEFINED && sound != last_sound)
2188         FadeSound(last_sound);
2189       if (last_music != MUS_UNDEFINED && music != last_music)
2190         FadeMusic();
2191
2192       fading = getTitleFading(tci);
2193
2194       FadeOut(REDRAW_ALL);
2195
2196       if (tci->is_image)
2197         DrawTitleScreenImage(tci->local_nr, tci->initial);
2198       else
2199         DrawTitleScreenMessage(tci->local_nr, tci->initial);
2200
2201       sound = getTitleSound(tci);
2202       music = getTitleMusic(tci);
2203
2204       if (sound != last_sound)
2205         PlayMenuSoundExt(sound);
2206       if (music != last_music)
2207         PlayMenuMusicExt(music);
2208
2209       last_sound = sound;
2210       last_music = music;
2211
2212       FadeIn(REDRAW_ALL);
2213
2214       ResetTitleAutoDelay(&title_delay, &fading);
2215     }
2216     else
2217     {
2218       FadeMenuSoundsAndMusic();
2219
2220       return_to_main_menu = TRUE;
2221     }
2222   }
2223   else
2224   {
2225     tci = &title_controls[title_screen_nr];
2226
2227     // check for optional title screen of native BD style level set
2228     if (tci->is_image && CheckTitleScreen_BD(tci->local_nr, tci->initial))
2229     {
2230       Bitmap **title_screen_bitmaps = GetTitleScreenBitmaps_BD();
2231
2232       // if title screen is animated, draw title screen animation
2233       if (title_screen_bitmaps[0] != NULL &&
2234           title_screen_bitmaps[1] != NULL)
2235         DrawTitleScreenImage(tci->local_nr, tci->initial);
2236     }
2237   }
2238
2239   if (return_to_main_menu)
2240   {
2241     SetMouseCursor(CURSOR_DEFAULT);
2242
2243     // force full menu screen redraw after displaying title screens
2244     redraw_mask = REDRAW_ALL;
2245
2246     if (game_status_last_screen == GAME_MODE_INFO)
2247     {
2248       SetGameStatus(GAME_MODE_INFO);
2249
2250       info_mode = INFO_MODE_MAIN;
2251
2252       DrawInfoScreen();
2253     }
2254     else        // default: return to main menu
2255     {
2256       SetGameStatus(GAME_MODE_MAIN);
2257
2258       DrawMainMenu();
2259     }
2260   }
2261 }
2262
2263 static void HandleMainMenu_ToggleTeamMode(void)
2264 {
2265   setup.team_mode = !setup.team_mode;
2266
2267   InitializeMainControls();
2268   DrawCursorAndText_Main(MAIN_CONTROL_NAME, TRUE, FALSE);
2269
2270   DrawPreviewPlayers();
2271 }
2272
2273 static void HandleMainMenu_SelectLevel(int step, int direction,
2274                                        int selected_level_nr)
2275 {
2276   int old_level_nr = level_nr;
2277   int new_level_nr;
2278
2279   if (selected_level_nr != NO_DIRECT_LEVEL_SELECT)
2280     new_level_nr = selected_level_nr;
2281   else
2282     new_level_nr = old_level_nr + step * direction;
2283
2284   if (new_level_nr < leveldir_current->first_level)
2285     new_level_nr = leveldir_current->first_level;
2286   if (new_level_nr > leveldir_current->last_level)
2287     new_level_nr = leveldir_current->last_level;
2288
2289   if (setup.handicap && new_level_nr > leveldir_current->handicap_level)
2290   {
2291     // skipping levels is only allowed when trying to skip single level
2292     // (also, skipping BD style intermission levels is always possible)
2293     if (new_level_nr == old_level_nr + 1 &&
2294         (level.bd_intermission ||
2295          (setup.skip_levels && Request("Level still unsolved! Skip it anyway?", REQ_ASK))))
2296     {
2297       leveldir_current->handicap_level++;
2298       SaveLevelSetup_SeriesInfo();
2299     }
2300
2301     new_level_nr = leveldir_current->handicap_level;
2302   }
2303
2304   if (new_level_nr != old_level_nr)
2305   {
2306     struct MainControlInfo *mci = getMainControlInfo(MAIN_CONTROL_LEVEL_NUMBER);
2307
2308     PlaySound(SND_MENU_ITEM_SELECTING);
2309
2310     level_nr = new_level_nr;
2311
2312     DrawText(mSX + mci->pos_text->x, mSY + mci->pos_text->y,
2313              int2str(level_nr, menu.main.text.level_number.size),
2314              mci->pos_text->font);
2315
2316     LoadLevel(level_nr);
2317     DrawPreviewLevelInitial();
2318
2319     TapeErase();
2320     LoadTape(level_nr);
2321     DrawCompleteVideoDisplay();
2322
2323     SaveLevelSetup_SeriesInfo();
2324
2325     UpdateScreenMenuGadgets(SCREEN_MASK_MAIN_HAS_SOLUTION, hasSolutionTape());
2326
2327     // force redraw of playfield area (may be reset at this point)
2328     redraw_mask |= REDRAW_FIELD;
2329   }
2330 }
2331
2332 void HandleMainMenu(int mx, int my, int dx, int dy, int button)
2333 {
2334   static int choice = MAIN_CONTROL_GAME;
2335   static boolean button_pressed_last = FALSE;
2336   boolean button_pressed = FALSE;
2337   int pos = choice;
2338   int i = 0;    // needed to prevent compiler warning due to bad code below
2339
2340   if (button == MB_MENU_INITIALIZE)
2341   {
2342     DrawCursorAndText_Main(choice, TRUE, FALSE);
2343
2344     return;
2345   }
2346
2347   if (mx || my)         // mouse input
2348   {
2349     pos = -1;
2350
2351     for (i = 0; main_controls[i].nr != -1; i++)
2352     {
2353       if (insideMenuPosRect(main_controls[i].pos_button, mx - mSX, my - mSY) ||
2354           insideTextPosRect(main_controls[i].pos_text,   mx - mSX, my - mSY) ||
2355           insideTextPosRect(main_controls[i].pos_input,  mx - mSX, my - mSY))
2356       {
2357         pos = main_controls[i].nr;
2358
2359         break;
2360       }
2361     }
2362
2363     // check if level preview was clicked
2364     if (insidePreviewRect(&preview, mx - SX, my - SY))
2365       pos = MAIN_CONTROL_GAME;
2366
2367     // handle pressed/unpressed state for active/inactive menu buttons
2368     // (if pos != -1, "i" contains index position corresponding to "pos")
2369     if (button &&
2370         pos >= MAIN_CONTROL_NAME && pos <= MAIN_CONTROL_QUIT &&
2371         insideMenuPosRect(main_controls[i].pos_button, mx - mSX, my - mSY))
2372       button_pressed = TRUE;
2373
2374     if (button_pressed != button_pressed_last)
2375     {
2376       DrawCursorAndText_Main(choice, TRUE, button_pressed);
2377
2378       if (button_pressed)
2379         PlaySound(SND_MENU_BUTTON_PRESSING);
2380       else
2381         PlaySound(SND_MENU_BUTTON_RELEASING);
2382     }
2383   }
2384   else if (dx || dy)    // keyboard input
2385   {
2386     if (dx > 0 && (choice == MAIN_CONTROL_INFO ||
2387                    choice == MAIN_CONTROL_SETUP))
2388       button = MB_MENU_CHOICE;
2389     else if (dy)
2390       pos = choice + dy;
2391   }
2392
2393   if (pos == MAIN_CONTROL_FIRST_LEVEL && !button)
2394   {
2395     HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
2396   }
2397   else if (pos == MAIN_CONTROL_LAST_LEVEL && !button)
2398   {
2399     HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
2400   }
2401   else if (pos == MAIN_CONTROL_LEVEL_NUMBER && !button)
2402   {
2403     CloseDoor(DOOR_CLOSE_2);
2404
2405     SetGameStatus(GAME_MODE_LEVELNR);
2406
2407     DrawChooseLevelNr();
2408   }
2409   else if (pos >= MAIN_CONTROL_NAME && pos <= MAIN_CONTROL_QUIT)
2410   {
2411     if (button)
2412     {
2413       if (pos != choice)
2414       {
2415         PlaySound(SND_MENU_ITEM_ACTIVATING);
2416
2417         DrawCursorAndText_Main(choice, FALSE, FALSE);
2418         DrawCursorAndText_Main(pos, TRUE, button_pressed);
2419
2420         choice = pos;
2421       }
2422       else if (dx != 0)
2423       {
2424         if (choice == MAIN_CONTROL_NAME)
2425         {
2426           // special case: cursor left or right pressed -- toggle team mode
2427           HandleMainMenu_ToggleTeamMode();
2428         }
2429         else if (choice != MAIN_CONTROL_INFO &&
2430                  choice != MAIN_CONTROL_SETUP)
2431         {
2432           HandleMainMenu_SelectLevel(1, dx, NO_DIRECT_LEVEL_SELECT);
2433         }
2434       }
2435     }
2436     else
2437     {
2438       PlaySound(SND_MENU_ITEM_SELECTING);
2439
2440       if (pos == MAIN_CONTROL_NAME)
2441       {
2442         if ((mx || my) &&
2443             insideTextPosRect(main_controls[i].pos_text, mx - mSX, my - mSY))
2444         {
2445           // special case: menu text "name/team" clicked -- toggle team mode
2446           HandleMainMenu_ToggleTeamMode();
2447         }
2448         else
2449         {
2450           if (setup.multiple_users)
2451           {
2452             CloseDoor(DOOR_CLOSE_2);
2453
2454             SetGameStatus(GAME_MODE_NAMES);
2455
2456             DrawChoosePlayerName();
2457           }
2458           else
2459           {
2460             SetGameStatus(GAME_MODE_PSEUDO_TYPENAME);
2461
2462             DrawTypeName();
2463           }
2464         }
2465       }
2466       else if (pos == MAIN_CONTROL_LEVELS)
2467       {
2468         if (leveldir_first)
2469         {
2470           CloseDoor(DOOR_CLOSE_2);
2471
2472           SetGameStatus(GAME_MODE_LEVELS);
2473
2474           SaveLevelSetup_LastSeries();
2475           SaveLevelSetup_SeriesInfo();
2476
2477           // restore level set if chosen from "last played level set" menu
2478           RestoreLastPlayedLevels(&leveldir_current);
2479
2480           if (setup.internal.choose_from_top_leveldir)
2481             gotoTopLevelDir();
2482
2483           DrawChooseLevelSet();
2484         }
2485       }
2486       else if (pos == MAIN_CONTROL_SCORES)
2487       {
2488         CloseDoor(DOOR_CLOSE_2);
2489
2490         SetGameStatus(GAME_MODE_SCORES);
2491
2492         DrawHallOfFame(level_nr);
2493       }
2494       else if (pos == MAIN_CONTROL_EDITOR)
2495       {
2496         if (leveldir_current->readonly &&
2497             setup.editor.show_read_only_warning)
2498           Request("This level is read-only!", REQ_CONFIRM | REQ_STAY_OPEN);
2499
2500         CloseDoor(DOOR_CLOSE_ALL);
2501
2502         SetGameStatus(GAME_MODE_EDITOR);
2503
2504         FadeSetEnterScreen();
2505
2506         DrawLevelEd();
2507       }
2508       else if (pos == MAIN_CONTROL_INFO)
2509       {
2510         CloseDoor(DOOR_CLOSE_2);
2511
2512         SetGameStatus(GAME_MODE_INFO);
2513
2514         info_mode = INFO_MODE_MAIN;
2515
2516         DrawInfoScreen();
2517       }
2518       else if (pos == MAIN_CONTROL_GAME)
2519       {
2520         StartGameActions(network.enabled, setup.autorecord, level.random_seed);
2521       }
2522       else if (pos == MAIN_CONTROL_SETUP)
2523       {
2524         CloseDoor(DOOR_CLOSE_2);
2525
2526         SetGameStatus(GAME_MODE_SETUP);
2527
2528         setup_mode = SETUP_MODE_MAIN;
2529
2530         DrawSetupScreen();
2531       }
2532       else if (pos == MAIN_CONTROL_QUIT)
2533       {
2534         SaveLevelSetup_LastSeries();
2535         SaveLevelSetup_SeriesInfo();
2536
2537 #if defined(PLATFORM_EMSCRIPTEN)
2538         Request("Close the browser window to quit!", REQ_CONFIRM);
2539 #else
2540         if (!setup.ask_on_quit_program ||
2541             Request("Do you really want to quit?", REQ_ASK | REQ_STAY_CLOSED))
2542           SetGameStatus(GAME_MODE_QUIT);
2543 #endif
2544       }
2545     }
2546   }
2547
2548   button_pressed_last = button_pressed;
2549 }
2550
2551
2552 // ============================================================================
2553 // info screen functions
2554 // ============================================================================
2555
2556 static struct TokenInfo *info_info;
2557 static int num_info_info;       // number of info entries shown on screen
2558 static int max_info_info;       // total number of info entries in list
2559
2560 static void execInfoTitleScreen(void)
2561 {
2562   info_mode = INFO_MODE_TITLE;
2563
2564   DrawInfoScreen();
2565 }
2566
2567 static void execInfoElements(void)
2568 {
2569   info_mode = INFO_MODE_ELEMENTS;
2570
2571   DrawInfoScreen();
2572 }
2573
2574 static void execInfoMusic(void)
2575 {
2576   info_mode = INFO_MODE_MUSIC;
2577
2578   DrawInfoScreen();
2579 }
2580
2581 static void execInfoCredits(void)
2582 {
2583   info_mode = INFO_MODE_CREDITS;
2584
2585   DrawInfoScreen();
2586 }
2587
2588 static void execInfoProgram(void)
2589 {
2590   info_mode = INFO_MODE_PROGRAM;
2591
2592   DrawInfoScreen();
2593 }
2594
2595 static void execInfoVersion(void)
2596 {
2597   info_mode = INFO_MODE_VERSION;
2598
2599   DrawInfoScreen();
2600 }
2601
2602 static void execInfoLevelSet(void)
2603 {
2604   info_mode = INFO_MODE_LEVELSET;
2605
2606   DrawInfoScreen();
2607 }
2608
2609 static void execExitInfo(void)
2610 {
2611   SetGameStatus(GAME_MODE_MAIN);
2612
2613   DrawMainMenu();
2614 }
2615
2616 static struct TokenInfo info_info_main[] =
2617 {
2618   { TYPE_ENTER_SCREEN,  execInfoTitleScreen,    STR_INFO_TITLE          },
2619   { TYPE_ENTER_SCREEN,  execInfoElements,       STR_INFO_ELEMENTS       },
2620   { TYPE_ENTER_SCREEN,  execInfoMusic,          STR_INFO_MUSIC          },
2621   { TYPE_ENTER_SCREEN,  execInfoCredits,        STR_INFO_CREDITS        },
2622   { TYPE_ENTER_SCREEN,  execInfoProgram,        STR_INFO_PROGRAM        },
2623   { TYPE_ENTER_SCREEN,  execInfoVersion,        STR_INFO_VERSION        },
2624   { TYPE_ENTER_SCREEN,  execInfoLevelSet,       STR_INFO_LEVELSET       },
2625   { TYPE_EMPTY,         NULL,                   ""                      },
2626   { TYPE_LEAVE_MENU,    execExitInfo,           STR_INFO_EXIT           },
2627
2628   { 0,                  NULL,                   NULL                    }
2629 };
2630
2631 static int getMenuTextFont(int type)
2632 {
2633   if (type & (TYPE_SWITCH       |
2634               TYPE_YES_NO       |
2635               TYPE_YES_NO_AUTO  |
2636               TYPE_YES_NO_ASK   |
2637               TYPE_STRING       |
2638               TYPE_PLAYER       |
2639               TYPE_ECS_AGA      |
2640               TYPE_KEYTEXT      |
2641               TYPE_ENTER_LIST   |
2642               TYPE_TEXT_INPUT))
2643     return FONT_MENU_2;
2644   else
2645     return FONT_MENU_1;
2646 }
2647
2648 static struct TokenInfo *setup_info;
2649 static struct TokenInfo setup_info_input[];
2650
2651 static struct TokenInfo *menu_info;
2652
2653 static void PlayInfoSound(void)
2654 {
2655   int info_sound = getInfoScreenBackgroundSound_Generic();
2656   char *next_sound = getSoundInfoEntryFilename(info_sound);
2657
2658   if (next_sound != NULL)
2659     PlayMenuSoundExt(info_sound);
2660   else
2661     PlayMenuSound();
2662 }
2663
2664 static void PlayInfoSoundIfLoop(void)
2665 {
2666   int info_sound = getInfoScreenBackgroundSound_Generic();
2667   char *next_sound = getSoundInfoEntryFilename(info_sound);
2668
2669   if (next_sound != NULL)
2670     PlayMenuSoundIfLoopExt(info_sound);
2671   else
2672     PlayMenuSoundIfLoop();
2673 }
2674
2675 static void PlayInfoMusic(void)
2676 {
2677   int info_music = getInfoScreenBackgroundMusic_Generic();
2678   char *curr_music = getCurrentlyPlayingMusicFilename();
2679   char *next_music = getMusicInfoEntryFilename(info_music);
2680
2681   if (next_music != NULL)
2682   {
2683     // play music if info screen music differs from current music
2684     if (!strEqual(curr_music, next_music))
2685       PlayMenuMusicExt(info_music);
2686   }
2687   else
2688   {
2689     // only needed if info screen was directly invoked from main menu
2690     PlayMenuMusic();
2691   }
2692 }
2693
2694 static void PlayInfoSoundsAndMusic(void)
2695 {
2696   PlayInfoSound();
2697   PlayInfoMusic();
2698 }
2699
2700 static void FadeInfoSounds(void)
2701 {
2702   FadeSounds();
2703 }
2704
2705 static void FadeInfoMusic(void)
2706 {
2707   int info_music = getInfoScreenBackgroundMusic_Generic();
2708   char *curr_music = getCurrentlyPlayingMusicFilename();
2709   char *next_music = getMusicInfoEntryFilename(info_music);
2710
2711   if (next_music != NULL)
2712   {
2713     // fade music if info screen music differs from current music
2714     if (!strEqual(curr_music, next_music))
2715       FadeMusic();
2716   }
2717 }
2718
2719 static void FadeInfoSoundsAndMusic(void)
2720 {
2721   FadeInfoSounds();
2722   FadeInfoMusic();
2723 }
2724
2725 static void DrawCursorAndText_Menu_Ext(struct TokenInfo *token_info,
2726                                        int screen_pos, int menu_info_pos_raw,
2727                                        boolean active)
2728 {
2729   int pos = (menu_info_pos_raw < 0 ? screen_pos : menu_info_pos_raw);
2730   struct TokenInfo *ti = &token_info[pos];
2731   int xpos = MENU_SCREEN_START_XPOS;
2732   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
2733   int font_nr = getMenuTextFont(ti->type);
2734
2735   if (setup_mode == SETUP_MODE_INPUT)
2736     font_nr = FONT_MENU_1;
2737
2738   if (active)
2739     font_nr = FONT_ACTIVE(font_nr);
2740
2741   DrawText(mSX + xpos * 32, mSY + ypos * 32, ti->text, font_nr);
2742
2743   if (ti->type & ~TYPE_SKIP_ENTRY)
2744     drawCursor(screen_pos, active);
2745 }
2746
2747 static void DrawCursorAndText_Menu(int screen_pos, int menu_info_pos_raw,
2748                                    boolean active)
2749 {
2750   DrawCursorAndText_Menu_Ext(menu_info, screen_pos, menu_info_pos_raw, active);
2751 }
2752
2753 static void DrawCursorAndText_Setup(int screen_pos, int menu_info_pos_raw,
2754                                     boolean active)
2755 {
2756   DrawCursorAndText_Menu_Ext(setup_info, screen_pos, menu_info_pos_raw, active);
2757 }
2758
2759 static char *window_size_text;
2760 static char *scaling_type_text;
2761 static char *network_server_text;
2762
2763 static void drawSetupValue(int, int);
2764
2765 static void drawMenuInfoList(int first_entry, int num_page_entries,
2766                              int max_page_entries)
2767 {
2768   int i;
2769
2770   if (first_entry + num_page_entries > max_page_entries)
2771     first_entry = 0;
2772
2773   clearMenuListArea();
2774
2775   for (i = 0; i < num_page_entries; i++)
2776   {
2777     int menu_info_pos = first_entry + i;
2778     struct TokenInfo *si = &menu_info[menu_info_pos];
2779     void *value_ptr = si->value;
2780
2781     // set some entries to "unchangeable" according to other variables
2782     if ((value_ptr == &setup.sound_simple && !audio.sound_available) ||
2783         (value_ptr == &setup.sound_loops  && !audio.loops_available) ||
2784         (value_ptr == &setup.sound_music  && !audio.music_available) ||
2785         (value_ptr == &setup.fullscreen   && !video.fullscreen_available) ||
2786         (value_ptr == &window_size_text   && !video.window_scaling_available) ||
2787         (value_ptr == &scaling_type_text  && !video.window_scaling_available))
2788       si->type |= TYPE_GHOSTED;
2789
2790     if (si->type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
2791       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
2792     else if (si->type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
2793       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
2794     else if (si->type & ~TYPE_SKIP_ENTRY)
2795       initCursor(i, IMG_MENU_BUTTON);
2796
2797     DrawCursorAndText_Menu(i, menu_info_pos, FALSE);
2798
2799     if (si->type & TYPE_STRING)
2800     {
2801       int gadget_id = -1;
2802
2803       if (value_ptr == &network_server_text)
2804         gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
2805
2806       if (gadget_id != -1)
2807       {
2808         struct GadgetInfo *gi = screen_gadget[gadget_id];
2809         int xpos = MENU_SCREEN_START_XPOS;
2810         int ypos = MENU_SCREEN_START_YPOS + i;
2811         int x = mSX + xpos * 32;
2812         int y = mSY + ypos * 32;
2813
2814         ModifyGadget(gi, GDI_X, x, GDI_Y, y, GDI_END);
2815       }
2816     }
2817
2818     if (si->type & TYPE_VALUE &&
2819         menu_info == setup_info)
2820       drawSetupValue(i, menu_info_pos);
2821   }
2822 }
2823
2824 static void DrawInfoScreen_Main(void)
2825 {
2826   int fade_mask = REDRAW_FIELD;
2827   int i;
2828
2829   // (needed after displaying info sub-screens directly from main menu)
2830   if (info_screens_from_main)
2831   {
2832     info_screens_from_main = FALSE;
2833
2834     SetGameStatus(GAME_MODE_MAIN);
2835
2836     DrawMainMenu();
2837
2838     return;
2839   }
2840
2841   if (redraw_mask & REDRAW_ALL)
2842     fade_mask = REDRAW_ALL;
2843
2844   if (CheckFadeAll())
2845     fade_mask = REDRAW_ALL;
2846
2847   UnmapAllGadgets();
2848   FadeMenuSoundsAndMusic();
2849
2850   FreeScreenGadgets();
2851   CreateScreenGadgets();
2852
2853   // (needed after displaying title screens which disable auto repeat)
2854   KeyboardAutoRepeatOn();
2855
2856   FadeSetLeaveScreen();
2857
2858   FadeOut(fade_mask);
2859
2860   // needed if different viewport properties defined for info screen
2861   ChangeViewportPropertiesIfNeeded();
2862
2863   SetMainBackgroundImage(IMG_BACKGROUND_INFO);
2864
2865   ClearField();
2866
2867   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
2868
2869   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_INFO_MAIN);
2870
2871   info_info = info_info_main;
2872
2873   // use modified info screen info without info screen entries marked as hidden
2874   info_info = getSetupInfoFinal(info_info);
2875
2876   // determine maximal number of info entries that can be displayed on screen
2877   num_info_info = 0;
2878   for (i = 0; info_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
2879     num_info_info++;
2880
2881   // determine maximal number of info entries available for menu of info screen
2882   max_info_info = 0;
2883   for (i = 0; info_info[i].type != 0; i++)
2884     max_info_info++;
2885
2886   HandleInfoScreen_Main(0, 0, 0, 0, MB_MENU_INITIALIZE);
2887
2888   MapScreenGadgets(max_info_info);
2889
2890   PlayMenuSoundsAndMusic();
2891
2892   DrawMaskedBorder(fade_mask);
2893
2894   FadeIn(fade_mask);
2895 }
2896
2897 static void changeSetupValue(int, int, int);
2898
2899 static void HandleMenuScreen(int mx, int my, int dx, int dy, int button,
2900                              int mode, int num_page_entries,
2901                              int max_page_entries)
2902 {
2903   static int num_page_entries_all_last[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2904   static int choice_stores[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2905   static int first_entry_stores[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2906   boolean has_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->mapped;
2907   int mx_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x;
2908   int mx_right_border = (has_scrollbar ? mx_scrollbar : SX + SXSIZE);
2909   int *num_page_entries_last = num_page_entries_all_last[game_status];
2910   int *choice_store = choice_stores[game_status];
2911   int *first_entry_store = first_entry_stores[game_status];
2912   int choice = choice_store[mode];              // starts with 0
2913   int first_entry = first_entry_store[mode];    // starts with 0
2914   int x = 0;
2915   int y = choice - first_entry;
2916   int y_old = y;
2917   boolean position_set_by_scrollbar = (dx == 999);
2918   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
2919   int i;
2920
2921   if (button == MB_MENU_INITIALIZE)
2922   {
2923     // check if number of menu page entries has changed (may happen by change
2924     // of custom artwork definition value for 'list_size' for this menu screen)
2925     // (in this case, the last menu position most probably has to be corrected)
2926     if (num_page_entries != num_page_entries_last[mode])
2927     {
2928       choice_store[mode] = first_entry_store[mode] = 0;
2929
2930       choice = first_entry = 0;
2931       y = y_old = 0;
2932
2933       num_page_entries_last[mode] = num_page_entries;
2934     }
2935
2936     // advance to first valid menu entry
2937     while (choice < num_page_entries &&
2938            menu_info[choice].type & TYPE_SKIP_ENTRY)
2939       choice++;
2940
2941     if (position_set_by_scrollbar)
2942       first_entry = first_entry_store[mode] = dy;
2943     else
2944       AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2945                       NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2946
2947     drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2948
2949     if (choice < first_entry)
2950     {
2951       choice = first_entry;
2952
2953       if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2954         choice++;
2955     }
2956     else if (choice > first_entry + num_page_entries - 1)
2957     {
2958       choice = first_entry + num_page_entries - 1;
2959
2960       if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2961         choice--;
2962     }
2963
2964     choice_store[mode] = choice;
2965
2966     DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2967
2968     return;
2969   }
2970   else if (button == MB_MENU_LEAVE)
2971   {
2972     PlaySound(SND_MENU_ITEM_SELECTING);
2973
2974     for (i = 0; i < max_page_entries; i++)
2975     {
2976       if (menu_info[i].type & TYPE_LEAVE_MENU)
2977       {
2978         void (*menu_callback_function)(void) = menu_info[i].value;
2979
2980         FadeSetLeaveMenu();
2981
2982         menu_callback_function();
2983
2984         break;  // absolutely needed because function changes 'menu_info'!
2985       }
2986     }
2987
2988     return;
2989   }
2990
2991   if (mx || my)         // mouse input
2992   {
2993     x = (mx - mSX) / 32;
2994     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
2995   }
2996   else if (dx || dy)    // keyboard or scrollbar/scrollbutton input
2997   {
2998     // move cursor instead of scrolling when already at start/end of list
2999     if (dy == -1 * SCROLL_LINE && first_entry == 0)
3000       dy = -1;
3001     else if (dy == +1 * SCROLL_LINE &&
3002              first_entry + num_page_entries == max_page_entries)
3003       dy = 1;
3004
3005     // handle scrolling screen one line or page
3006     if (y + dy < 0 ||
3007         y + dy > num_page_entries - 1)
3008     {
3009       boolean redraw = FALSE;
3010
3011       if (ABS(dy) == SCROLL_PAGE)
3012         step = num_page_entries - 1;
3013
3014       if (dy < 0 && first_entry > 0)
3015       {
3016         // scroll page/line up
3017
3018         first_entry -= step;
3019         if (first_entry < 0)
3020           first_entry = 0;
3021
3022         redraw = TRUE;
3023       }
3024       else if (dy > 0 && first_entry + num_page_entries < max_page_entries)
3025       {
3026         // scroll page/line down
3027
3028         first_entry += step;
3029         if (first_entry + num_page_entries > max_page_entries)
3030           first_entry = MAX(0, max_page_entries - num_page_entries);
3031
3032         redraw = TRUE;
3033       }
3034
3035       if (redraw)
3036       {
3037         choice += first_entry - first_entry_store[mode];
3038
3039         if (choice < first_entry)
3040         {
3041           choice = first_entry;
3042
3043           if (menu_info[choice].type & TYPE_SKIP_ENTRY)
3044             choice++;
3045         }
3046         else if (choice > first_entry + num_page_entries - 1)
3047         {
3048           choice = first_entry + num_page_entries - 1;
3049
3050           if (menu_info[choice].type & TYPE_SKIP_ENTRY)
3051             choice--;
3052         }
3053         else if (menu_info[choice].type & TYPE_SKIP_ENTRY)
3054         {
3055           choice += SIGN(dy);
3056
3057           if (choice < first_entry ||
3058               choice > first_entry + num_page_entries - 1)
3059           first_entry += SIGN(dy);
3060         }
3061
3062         first_entry_store[mode] = first_entry;
3063         choice_store[mode] = choice;
3064
3065         drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
3066
3067         DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
3068
3069         AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
3070                         NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
3071       }
3072
3073       return;
3074     }
3075
3076     if (dx)
3077     {
3078       int menu_navigation_type = (dx < 0 ? TYPE_LEAVE : TYPE_ENTER);
3079
3080       if (menu_info[choice].type & menu_navigation_type ||
3081           menu_info[choice].type & TYPE_BOOLEAN_STYLE ||
3082           menu_info[choice].type & TYPE_YES_NO_AUTO ||
3083           menu_info[choice].type & TYPE_YES_NO_ASK ||
3084           menu_info[choice].type & TYPE_PLAYER)
3085         button = MB_MENU_CHOICE;
3086     }
3087     else if (dy)
3088       y += dy;
3089
3090     // jump to next non-empty menu entry (up or down)
3091     while (first_entry + y > 0 &&
3092            first_entry + y < max_page_entries - 1 &&
3093            menu_info[first_entry + y].type & TYPE_SKIP_ENTRY)
3094       y += dy;
3095
3096     if (!IN_VIS_MENU(x, y))
3097     {
3098       choice += y - y_old;
3099
3100       if (choice < first_entry)
3101         first_entry = choice;
3102       else if (choice > first_entry + num_page_entries - 1)
3103         first_entry = choice - num_page_entries + 1;
3104
3105       if (first_entry >= 0 &&
3106           first_entry + num_page_entries <= max_page_entries)
3107       {
3108         first_entry_store[mode] = first_entry;
3109
3110         if (choice < first_entry)
3111           choice = first_entry;
3112         else if (choice > first_entry + num_page_entries - 1)
3113           choice = first_entry + num_page_entries - 1;
3114
3115         choice_store[mode] = choice;
3116
3117         drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
3118
3119         DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
3120
3121         AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
3122                         NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
3123       }
3124
3125       return;
3126     }
3127   }
3128
3129   if (!anyScrollbarGadgetActive() &&
3130       IN_VIS_MENU(x, y) &&
3131       mx < mx_right_border &&
3132       y >= 0 && y < num_page_entries)
3133   {
3134     if (button)
3135     {
3136       if (first_entry + y != choice &&
3137           menu_info[first_entry + y].type & ~TYPE_SKIP_ENTRY)
3138       {
3139         PlaySound(SND_MENU_ITEM_ACTIVATING);
3140
3141         DrawCursorAndText_Menu(choice - first_entry, choice, FALSE);
3142         DrawCursorAndText_Menu(y, first_entry + y, TRUE);
3143
3144         choice = choice_store[mode] = first_entry + y;
3145       }
3146       else if (dx < 0)
3147       {
3148         PlaySound(SND_MENU_ITEM_SELECTING);
3149
3150         for (i = 0; menu_info[i].type != 0; i++)
3151         {
3152           if (menu_info[i].type & TYPE_LEAVE_MENU)
3153           {
3154             void (*menu_callback_function)(void) = menu_info[i].value;
3155
3156             FadeSetLeaveMenu();
3157
3158             menu_callback_function();
3159
3160             // absolutely needed because function changes 'menu_info'!
3161             break;
3162           }
3163         }
3164
3165         return;
3166       }
3167     }
3168     else if (!(menu_info[first_entry + y].type & TYPE_GHOSTED))
3169     {
3170       PlaySound(SND_MENU_ITEM_SELECTING);
3171
3172       // when selecting key headline, execute function for key value change
3173       if (menu_info[first_entry + y].type & TYPE_KEYTEXT &&
3174           menu_info[first_entry + y + 1].type & TYPE_KEY)
3175         y++;
3176
3177       // when selecting string value, execute function for list selection
3178       if (menu_info[first_entry + y].type & TYPE_STRING && y > 0 &&
3179           menu_info[first_entry + y - 1].type & TYPE_ENTER_LIST)
3180         y--;
3181
3182       // when selecting string value, execute function for text input gadget
3183       if (menu_info[first_entry + y].type & TYPE_STRING && y > 0 &&
3184           menu_info[first_entry + y - 1].type & TYPE_TEXT_INPUT)
3185         y--;
3186
3187       if (menu_info[first_entry + y].type & TYPE_ENTER_OR_LEAVE)
3188       {
3189         void (*menu_callback_function)(void) =
3190           menu_info[first_entry + y].value;
3191
3192         FadeSetFromType(menu_info[first_entry + y].type);
3193
3194         menu_callback_function();
3195       }
3196       else if (menu_info[first_entry + y].type & TYPE_TEXT_INPUT)
3197       {
3198         void (*gadget_callback_function)(void) =
3199           menu_info[first_entry + y].value;
3200
3201         gadget_callback_function();
3202       }
3203       else if (menu_info[first_entry + y].type & TYPE_VALUE &&
3204                menu_info == setup_info)
3205       {
3206         changeSetupValue(y, first_entry + y, dx);
3207       }
3208     }
3209   }
3210 }
3211
3212 void HandleInfoScreen_Main(int mx, int my, int dx, int dy, int button)
3213 {
3214   menu_info = info_info;
3215
3216   HandleMenuScreen(mx, my, dx, dy, button,
3217                    info_mode, num_info_info, max_info_info);
3218 }
3219
3220 static int getMenuFontSpacing(int spacing_height, int font_nr)
3221 {
3222   int font_spacing = getFontHeight(font_nr) + EXTRA_SPACING(game_status);
3223
3224   return (spacing_height < 0 ? ABS(spacing_height) * font_spacing :
3225           spacing_height);
3226 }
3227
3228 static int getMenuTextSpacing(int spacing_height, int font_nr)
3229 {
3230   return (getMenuFontSpacing(spacing_height, font_nr) +
3231           EXTRA_SPACING(game_status));
3232 }
3233
3234 static int getMenuTextStep(int spacing_height, int font_nr)
3235 {
3236   return getFontHeight(font_nr) + getMenuTextSpacing(spacing_height, font_nr);
3237 }
3238
3239 static int getHeadlineSpacing(void)
3240 {
3241   // special compatibility handling for "R'n'D jue 2022" game editions
3242   int spacing_check = menu.headline1_spacing[GAME_MODE_SCOREINFO];
3243   int spacing = (game_status == GAME_MODE_SCOREINFO ?
3244                  menu.headline1_spacing[GAME_MODE_SCOREINFO] :
3245                  menu.headline1_spacing_info[info_mode]);
3246   int font = MENU_INFO_FONT_TITLE;
3247
3248   return (spacing_check != -2 ? getMenuTextStep(spacing, font) : 0);
3249 }
3250
3251 void DrawInfoScreen_NotAvailable(char *text_title, char *text_error)
3252 {
3253   int font_error = FONT_TEXT_2;
3254   int font_foot  = MENU_INFO_FONT_FOOT;
3255   int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART + getHeadlineSpacing();
3256   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3257
3258   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO);
3259
3260   FadeOut(REDRAW_FIELD);
3261
3262   ClearField();
3263
3264   DrawInfoScreen_Headline(0, 1, FALSE);
3265
3266   DrawTextSCentered(ystart, font_error, text_error);
3267   DrawTextSCentered(ybottom, font_foot, TEXT_NEXT_MENU);
3268
3269   FadeIn(REDRAW_FIELD);
3270 }
3271
3272 void DrawInfoScreen_HelpAnim(int start, int max_anims, boolean init)
3273 {
3274   static int infoscreen_step[MAX_INFO_ELEMENTS_IN_ARRAY];
3275   static int infoscreen_frame[MAX_INFO_ELEMENTS_IN_ARRAY];
3276   int font_foot = MENU_INFO_FONT_FOOT;
3277   int xstart = mSX + MENU_SCREEN_INFO_SPACE_LEFT;
3278   int ystart = mSY + MENU_SCREEN_INFO_YSTART + getHeadlineSpacing();
3279   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3280   int ystep = MENU_SCREEN_INFO_YSTEP;
3281   int row_height = MENU_SCREEN_INFO_ENTRY_SIZE;
3282   int tilesize = MENU_SCREEN_INFO_TILE_SIZE;
3283   int yoffset = (row_height - tilesize) / 2;
3284   int element, action, direction;
3285   int graphic;
3286   int delay;
3287   int sync_frame;
3288   int i, j;
3289
3290   if (init)
3291   {
3292     for (i = 0; i < NUM_INFO_ELEMENTS_ON_SCREEN; i++)
3293       infoscreen_step[i] = infoscreen_frame[i] = 0;
3294
3295     DrawTextSCentered(ybottom, font_foot, TEXT_NEXT_PAGE);
3296
3297     FrameCounter = 0;
3298   }
3299
3300   i = j = 0;
3301   while (helpanim_info[j].element != HELPANIM_LIST_END)
3302   {
3303     if (i >= start + NUM_INFO_ELEMENTS_ON_SCREEN ||
3304         i >= max_anims)
3305       break;
3306     else if (i < start)
3307     {
3308       while (helpanim_info[j].element != HELPANIM_LIST_NEXT)
3309         j++;
3310
3311       j++;
3312       i++;
3313
3314       continue;
3315     }
3316
3317     int ypos = i - start;
3318     int ystart_pos = ystart + ypos * ystep + yoffset;
3319
3320     j += infoscreen_step[ypos];
3321
3322     element = helpanim_info[j].element;
3323     action = helpanim_info[j].action;
3324     direction = helpanim_info[j].direction;
3325
3326     if (element < 0)
3327       element = EL_UNKNOWN;
3328
3329     if (action != -1 && direction != -1)
3330       graphic = el_act_dir2img(element, action, direction);
3331     else if (action != -1)
3332       graphic = el_act2img(element, action);
3333     else if (direction != -1)
3334       graphic = el_dir2img(element, direction);
3335     else
3336       graphic = el2img(element);
3337
3338     delay = helpanim_info[j++].delay;
3339
3340     if (delay == -1)
3341       delay = 1000000;
3342
3343     if (infoscreen_frame[ypos] == 0)
3344     {
3345       sync_frame = 0;
3346       infoscreen_frame[ypos] = delay - 1;
3347     }
3348     else
3349     {
3350       sync_frame = delay - infoscreen_frame[ypos];
3351       infoscreen_frame[ypos]--;
3352     }
3353
3354     if (helpanim_info[j].element == HELPANIM_LIST_NEXT)
3355     {
3356       if (!infoscreen_frame[ypos])
3357         infoscreen_step[ypos] = 0;
3358     }
3359     else
3360     {
3361       if (!infoscreen_frame[ypos])
3362         infoscreen_step[ypos]++;
3363       while (helpanim_info[j].element != HELPANIM_LIST_NEXT)
3364         j++;
3365     }
3366
3367     j++;
3368
3369     ClearRectangleOnBackground(drawto, xstart, ystart_pos, tilesize, tilesize);
3370     DrawSizedGraphicAnimationExt(drawto, xstart, ystart_pos,
3371                                  graphic, sync_frame, tilesize, USE_MASKING);
3372
3373     if (init)
3374       DrawInfoScreen_HelpText(element, action, direction, ypos);
3375
3376     i++;
3377   }
3378
3379   redraw_mask |= REDRAW_FIELD;
3380
3381   FrameCounter++;
3382 }
3383
3384 static char *getHelpText(int element, int action, int direction)
3385 {
3386   char token[MAX_LINE_LEN];
3387
3388   strcpy(token, element_info[element].token_name);
3389
3390   if (action != -1)
3391     strcat(token, element_action_info[action].suffix);
3392
3393   if (direction != -1)
3394     strcat(token, element_direction_info[MV_DIR_TO_BIT(direction)].suffix);
3395
3396   return getHashEntry(helptext_info, token);
3397 }
3398
3399 void DrawInfoScreen_HelpText(int element, int action, int direction, int ypos)
3400 {
3401   int font_nr = FONT_INFO_ELEMENTS;
3402   int font_width = getFontWidth(font_nr);
3403   int font_height = getFontHeight(font_nr);
3404   int line_spacing = MENU_SCREEN_INFO_SPACE_LINE;
3405   int left_spacing = MENU_SCREEN_INFO_SPACE_LEFT;
3406   int middle_spacing = MENU_SCREEN_INFO_SPACE_MIDDLE;
3407   int right_spacing = MENU_SCREEN_INFO_SPACE_RIGHT;
3408   int line_height = font_height + line_spacing;
3409   int row_height = MENU_SCREEN_INFO_ENTRY_SIZE;
3410   int tilesize = MENU_SCREEN_INFO_TILE_SIZE;
3411   int xstart = mSX + left_spacing + tilesize + middle_spacing;
3412   int ystart = mSY + MENU_SCREEN_INFO_YSTART + getHeadlineSpacing();
3413   int ystep = MENU_SCREEN_INFO_YSTEP;
3414   int pad_left = xstart - SX;
3415   int pad_right = right_spacing;
3416   int max_chars_per_line = (SXSIZE - pad_left - pad_right) / font_width;
3417   int max_lines_per_text = (row_height + line_spacing) / line_height;
3418   char *text = NULL;
3419   boolean autowrap = TRUE;
3420   boolean centered = FALSE;
3421   boolean parse_comments = FALSE;
3422
3423   if (action != -1 && direction != -1)          // element.action.direction
3424     text = getHelpText(element, action, direction);
3425
3426   if (text == NULL && action != -1)             // element.action
3427     text = getHelpText(element, action, -1);
3428
3429   if (text == NULL && direction != -1)          // element.direction
3430     text = getHelpText(element, -1, direction);
3431
3432   if (text == NULL)                             // base element
3433     text = getHelpText(element, -1, -1);
3434
3435   if (text == NULL)                             // not found
3436     text = "No description available";
3437
3438   DisableDrawingText();
3439
3440   // first get number of text lines to calculate offset for centering text
3441   int num_lines_printed =
3442     DrawTextBuffer(0, 0, text, font_nr,
3443                    max_chars_per_line, -1, max_lines_per_text, line_spacing, -1,
3444                    autowrap, centered, parse_comments);
3445
3446   EnableDrawingText();
3447
3448   int size_lines_printed = num_lines_printed * line_height - line_spacing;
3449   int yoffset = (row_height - size_lines_printed) / 2;
3450
3451   DrawTextBuffer(xstart, ystart + ypos * ystep + yoffset, text, font_nr,
3452                  max_chars_per_line, -1, max_lines_per_text, line_spacing, -1,
3453                  autowrap, centered, parse_comments);
3454 }
3455
3456 static void DrawInfoScreen_TitleScreen(void)
3457 {
3458   SetGameStatus(GAME_MODE_TITLE);
3459
3460   UnmapAllGadgets();
3461
3462   DrawTitleScreen();
3463 }
3464
3465 void HandleInfoScreen_TitleScreen(int dx, int dy, int button)
3466 {
3467   HandleTitleScreen(0, 0, dx, dy, button);
3468 }
3469
3470 static void DrawInfoScreen_Elements(void)
3471 {
3472   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_ELEMENTS);
3473
3474   UnmapAllGadgets();
3475   FadeInfoSoundsAndMusic();
3476
3477   FadeOut(REDRAW_FIELD);
3478
3479   LoadHelpAnimInfo();
3480   LoadHelpTextInfo();
3481
3482   HandleInfoScreen_Elements(0, 0, MB_MENU_INITIALIZE);
3483
3484   PlayInfoSoundsAndMusic();
3485
3486   FadeIn(REDRAW_FIELD);
3487 }
3488
3489 void HandleInfoScreen_Elements(int dx, int dy, int button)
3490 {
3491   static DelayCounter info_delay = { 0 };
3492   static int num_anims;
3493   static int num_pages;
3494   static int page;
3495   int anims_per_page = NUM_INFO_ELEMENTS_ON_SCREEN;
3496   int i;
3497
3498   info_delay.value = GameFrameDelay;
3499
3500   if (button == MB_MENU_INITIALIZE)
3501   {
3502     boolean new_element = TRUE;
3503
3504     num_anims = 0;
3505
3506     for (i = 0; helpanim_info[i].element != HELPANIM_LIST_END; i++)
3507     {
3508       if (helpanim_info[i].element == HELPANIM_LIST_NEXT)
3509         new_element = TRUE;
3510       else if (new_element)
3511       {
3512         num_anims++;
3513         new_element = FALSE;
3514       }
3515     }
3516
3517     num_pages = (num_anims + anims_per_page - 1) / anims_per_page;
3518     page = 0;
3519   }
3520
3521   if (button == MB_MENU_LEAVE)
3522   {
3523     PlaySound(SND_MENU_ITEM_SELECTING);
3524
3525     info_mode = INFO_MODE_MAIN;
3526     DrawInfoScreen();
3527
3528     return;
3529   }
3530   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE || dx)
3531   {
3532     if (button != MB_MENU_INITIALIZE)
3533     {
3534       PlaySound(SND_MENU_ITEM_SELECTING);
3535
3536       page += (dx < 0 ? -1 : +1);
3537     }
3538
3539     if (page < 0 || page >= num_pages)
3540     {
3541       FadeInfoSoundsAndMusic();
3542
3543       info_mode = INFO_MODE_MAIN;
3544       DrawInfoScreen();
3545
3546       return;
3547     }
3548
3549     if (button != MB_MENU_INITIALIZE)
3550       FadeSetNextScreen();
3551
3552     if (button != MB_MENU_INITIALIZE)
3553       FadeOut(REDRAW_FIELD);
3554
3555     ClearField();
3556
3557     DrawInfoScreen_Headline(page, num_pages, TRUE);
3558     DrawInfoScreen_HelpAnim(page * anims_per_page, num_anims, TRUE);
3559
3560     if (button != MB_MENU_INITIALIZE)
3561       FadeIn(REDRAW_FIELD);
3562   }
3563   else
3564   {
3565     if (DelayReached(&info_delay))
3566       if (page < num_pages)
3567         DrawInfoScreen_HelpAnim(page * anims_per_page, num_anims, FALSE);
3568
3569     PlayInfoSoundIfLoop();
3570   }
3571 }
3572
3573 static void DrawInfoScreen_Music(void)
3574 {
3575   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_MUSIC);
3576
3577   UnmapAllGadgets();
3578
3579   FadeOut(REDRAW_FIELD);
3580
3581   ClearField();
3582
3583   DrawInfoScreen_Headline(0, 1, TRUE);
3584
3585   LoadMusicInfo();
3586
3587   HandleInfoScreen_Music(0, 0, MB_MENU_INITIALIZE);
3588
3589   FadeIn(REDRAW_FIELD);
3590 }
3591
3592 void HandleInfoScreen_Music(int dx, int dy, int button)
3593 {
3594   static struct MusicFileInfo *list = NULL;
3595   static int num_screens = 0;
3596   static int screen_nr = 0;
3597   int font_title = MENU_INFO_FONT_TITLE;
3598   int font_head  = MENU_INFO_FONT_HEAD;
3599   int font_text  = MENU_INFO_FONT_TEXT;
3600   int font_foot  = MENU_INFO_FONT_FOOT;
3601   int spacing_head = menu.headline2_spacing_info[info_mode];
3602   int ystep_head = getMenuTextStep(spacing_head,  font_head);
3603   int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART;
3604   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3605
3606   if (button == MB_MENU_INITIALIZE)
3607   {
3608     struct MusicFileInfo *list_ptr = music_file_info;
3609
3610     num_screens = 0;
3611     screen_nr = 0;
3612
3613     while (list_ptr != NULL)
3614     {
3615       list_ptr = list_ptr->next;
3616       num_screens++;
3617     }
3618
3619     list = music_file_info;
3620
3621     if (list == NULL)
3622     {
3623       FadeMenuSoundsAndMusic();
3624
3625       ClearField();
3626
3627       DrawInfoScreen_Headline(0, 1, TRUE);
3628
3629       DrawTextSCentered(ystart, font_title, "No music info for this level set.");
3630       DrawTextSCentered(ybottom, font_foot, TEXT_NEXT_MENU);
3631
3632       return;
3633     }
3634   }
3635
3636   if (button == MB_MENU_LEAVE)
3637   {
3638     PlaySound(SND_MENU_ITEM_SELECTING);
3639
3640     FadeMenuSoundsAndMusic();
3641
3642     info_mode = INFO_MODE_MAIN;
3643     DrawInfoScreen();
3644
3645     return;
3646   }
3647   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE || dx)
3648   {
3649     if (button != MB_MENU_INITIALIZE)
3650     {
3651       PlaySound(SND_MENU_ITEM_SELECTING);
3652
3653       if (list != NULL)
3654       {
3655         list = (dx < 0 ? list->prev : list->next);
3656         screen_nr += (dx < 0 ? -1 : +1);
3657       }
3658     }
3659
3660     if (list == NULL)
3661     {
3662       FadeMenuSoundsAndMusic();
3663
3664       info_mode = INFO_MODE_MAIN;
3665       DrawInfoScreen();
3666
3667       return;
3668     }
3669
3670     FadeMenuSoundsAndMusic();
3671
3672     if (list != music_file_info)
3673       FadeSetNextScreen();
3674
3675     if (button != MB_MENU_INITIALIZE)
3676       FadeOut(REDRAW_FIELD);
3677
3678     ClearField();
3679
3680     DrawInfoScreen_Headline(screen_nr, num_screens, TRUE);
3681
3682     if (list->is_sound)
3683     {
3684       int sound = list->music;
3685
3686       if (IS_LOOP_SOUND(sound))
3687         PlaySoundLoop(sound);
3688       else
3689         PlaySound(sound);
3690     }
3691     else
3692     {
3693       int music = list->music;
3694
3695       if (IS_LOOP_MUSIC(music))
3696         PlayMusicLoop(music);
3697       else
3698         PlayMusic(music);
3699     }
3700
3701     if (!strEqual(list->title, UNKNOWN_NAME))
3702     {
3703       if (!strEqual(list->title_header, UNKNOWN_NAME))
3704         DrawTextSCentered(ystart, font_head, list->title_header);
3705       else
3706         DrawTextSCentered(ystart, font_head, "Track");
3707
3708       ystart += ystep_head;
3709
3710       DrawTextFCentered(ystart, font_text, "\"%s\"", list->title);
3711       ystart += ystep_head;
3712     }
3713
3714     if (!strEqual(list->artist, UNKNOWN_NAME))
3715     {
3716       if (!strEqual(list->artist_header, UNKNOWN_NAME))
3717         DrawTextSCentered(ystart, font_head, list->artist_header);
3718       else
3719         DrawTextSCentered(ystart, font_head, "by");
3720
3721       ystart += ystep_head;
3722
3723       DrawTextFCentered(ystart, font_text, "%s", list->artist);
3724       ystart += ystep_head;
3725     }
3726
3727     if (!strEqual(list->album, UNKNOWN_NAME))
3728     {
3729       if (!strEqual(list->album_header, UNKNOWN_NAME))
3730         DrawTextSCentered(ystart, font_head, list->album_header);
3731       else
3732         DrawTextSCentered(ystart, font_head, "from the album");
3733
3734       ystart += ystep_head;
3735
3736       DrawTextFCentered(ystart, font_text, "\"%s\"", list->album);
3737       ystart += ystep_head;
3738     }
3739
3740     if (!strEqual(list->year, UNKNOWN_NAME))
3741     {
3742       if (!strEqual(list->year_header, UNKNOWN_NAME))
3743         DrawTextSCentered(ystart, font_head, list->year_header);
3744       else
3745         DrawTextSCentered(ystart, font_head, "from the year");
3746
3747       ystart += ystep_head;
3748
3749       DrawTextFCentered(ystart, font_text, "%s", list->year);
3750       ystart += ystep_head;
3751     }
3752
3753     if (!strEqual(list->played, UNKNOWN_NAME))
3754     {
3755       if (!strEqual(list->played_header, UNKNOWN_NAME))
3756         DrawTextSCentered(ystart, font_head, list->played_header);
3757       else
3758         DrawTextSCentered(ystart, font_head, "played in");
3759
3760       ystart += ystep_head;
3761
3762       DrawTextFCentered(ystart, font_text, "%s", list->played);
3763       ystart += ystep_head;
3764     }
3765     else if (!list->is_sound)
3766     {
3767       int music_level_nr = -1;
3768       int i;
3769
3770       // check if this music is configured for a certain level
3771       for (i = leveldir_current->first_level;
3772            i <= leveldir_current->last_level; i++)
3773       {
3774         // (special case: "list->music" may be negative for unconfigured music)
3775         if (levelset.music[i] != MUS_UNDEFINED &&
3776             levelset.music[i] == list->music)
3777         {
3778           music_level_nr = i;
3779
3780           break;
3781         }
3782       }
3783
3784       if (music_level_nr != -1)
3785       {
3786         if (!strEqual(list->played_header, UNKNOWN_NAME))
3787           DrawTextSCentered(ystart, font_head, list->played_header);
3788         else
3789           DrawTextSCentered(ystart, font_head, "played in");
3790
3791         ystart += ystep_head;
3792
3793         DrawTextFCentered(ystart, font_text, "level %03d", music_level_nr);
3794         ystart += ystep_head;
3795       }
3796     }
3797
3798     DrawTextSCentered(ybottom, font_foot, TEXT_NEXT_PAGE);
3799
3800     if (button != MB_MENU_INITIALIZE)
3801       FadeIn(REDRAW_FIELD);
3802   }
3803
3804   if (list != NULL && list->is_sound && IS_LOOP_SOUND(list->music))
3805     PlaySoundLoop(list->music);
3806 }
3807
3808 static void DrawInfoScreen_Version(void)
3809 {
3810   int font_head = MENU_INFO_FONT_HEAD;
3811   int font_text = MENU_INFO_FONT_TEXT;
3812   int font_foot = MENU_INFO_FONT_FOOT;
3813   int spacing_head = menu.headline2_spacing_info[info_mode];
3814   int spacing_para = menu.paragraph_spacing_info[info_mode];
3815   int spacing_line = menu.line_spacing_info[info_mode];
3816   int xstep = getFontWidth(font_text);
3817   int ystep_head = getMenuTextStep(spacing_head,  font_head);
3818   int ystep_para = getMenuTextStep(spacing_para,  font_text);
3819   int ystep_line = getMenuTextStep(spacing_line,  font_text);
3820   int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART + getHeadlineSpacing();
3821   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3822   int xstart1 = mSX - SX + 2 * xstep;
3823   int xstart2 = mSX - SX + 18 * xstep;
3824   int xstart3 = mSX - SX + 28 * xstep;
3825   SDL_version sdl_version_compiled;
3826   const SDL_version *sdl_version_linked;
3827   int driver_name_len = 10;
3828   SDL_version sdl_version_linked_ext;
3829   const char *driver_name = NULL;
3830
3831   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_VERSION);
3832
3833   UnmapAllGadgets();
3834   FadeInfoSoundsAndMusic();
3835
3836   FadeOut(REDRAW_FIELD);
3837
3838   ClearField();
3839
3840   DrawInfoScreen_Headline(0, 1, TRUE);
3841
3842   DrawTextF(xstart1, ystart, font_head, "Name");
3843   DrawTextF(xstart2, ystart, font_text, getProgramTitleString());
3844   ystart += ystep_line;
3845
3846   if (!strEqual(getProgramVersionString(), getProgramRealVersionString()))
3847   {
3848     DrawTextF(xstart1, ystart, font_head, "Version (fake)");
3849     DrawTextF(xstart2, ystart, font_text, getProgramVersionString());
3850     ystart += ystep_line;
3851
3852     DrawTextF(xstart1, ystart, font_head, "Version (real)");
3853     DrawTextF(xstart2, ystart, font_text, getProgramRealVersionString());
3854     ystart += ystep_line;
3855   }
3856   else
3857   {
3858     DrawTextF(xstart1, ystart, font_head, "Version");
3859     DrawTextF(xstart2, ystart, font_text, getProgramVersionString());
3860     ystart += ystep_line;
3861   }
3862
3863   DrawTextF(xstart1, ystart, font_head, "Platform");
3864   DrawTextF(xstart2, ystart, font_text, "%s (%s)",
3865             PLATFORM_STRING,
3866             PLATFORM_XX_BIT_STRING);
3867   ystart += ystep_line;
3868
3869   DrawTextF(xstart1, ystart, font_head, "Target");
3870   DrawTextF(xstart2, ystart, font_text, TARGET_STRING);
3871   ystart += ystep_line;
3872
3873   DrawTextF(xstart1, ystart, font_head, "Source date");
3874   DrawTextF(xstart2, ystart, font_text, getSourceDateString());
3875   ystart += ystep_line;
3876
3877   DrawTextF(xstart1, ystart, font_head, "Commit hash");
3878   DrawTextF(xstart2, ystart, font_text, getSourceHashString());
3879   ystart += ystep_para;
3880
3881   DrawTextF(xstart1, ystart, font_head, "Library");
3882   DrawTextF(xstart2, ystart, font_head, "compiled");
3883   DrawTextF(xstart3, ystart, font_head, "linked");
3884   ystart += ystep_head;
3885
3886   SDL_VERSION(&sdl_version_compiled);
3887   SDL_GetVersion(&sdl_version_linked_ext);
3888   sdl_version_linked = &sdl_version_linked_ext;
3889
3890   DrawTextF(xstart1, ystart, font_text, "SDL");
3891   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3892             sdl_version_compiled.major,
3893             sdl_version_compiled.minor,
3894             sdl_version_compiled.patch);
3895   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3896             sdl_version_linked->major,
3897             sdl_version_linked->minor,
3898             sdl_version_linked->patch);
3899   ystart += ystep_line;
3900
3901   SDL_IMAGE_VERSION(&sdl_version_compiled);
3902   sdl_version_linked = IMG_Linked_Version();
3903
3904   DrawTextF(xstart1, ystart, font_text, "SDL_image");
3905   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3906             sdl_version_compiled.major,
3907             sdl_version_compiled.minor,
3908             sdl_version_compiled.patch);
3909   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3910             sdl_version_linked->major,
3911             sdl_version_linked->minor,
3912             sdl_version_linked->patch);
3913   ystart += ystep_line;
3914
3915   SDL_MIXER_VERSION(&sdl_version_compiled);
3916   sdl_version_linked = Mix_Linked_Version();
3917
3918   DrawTextF(xstart1, ystart, font_text, "SDL_mixer");
3919   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3920             sdl_version_compiled.major,
3921             sdl_version_compiled.minor,
3922             sdl_version_compiled.patch);
3923   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3924             sdl_version_linked->major,
3925             sdl_version_linked->minor,
3926             sdl_version_linked->patch);
3927   ystart += ystep_line;
3928
3929   SDL_NET_VERSION(&sdl_version_compiled);
3930   sdl_version_linked = SDLNet_Linked_Version();
3931
3932   DrawTextF(xstart1, ystart, font_text, "SDL_net");
3933   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3934             sdl_version_compiled.major,
3935             sdl_version_compiled.minor,
3936             sdl_version_compiled.patch);
3937   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3938             sdl_version_linked->major,
3939             sdl_version_linked->minor,
3940             sdl_version_linked->patch);
3941   ystart += ystep_para;
3942
3943   DrawTextF(xstart1, ystart, font_head, "Driver");
3944   DrawTextF(xstart2, ystart, font_head, "Requested");
3945   DrawTextF(xstart3, ystart, font_head, "Used");
3946   ystart += ystep_head;
3947
3948   driver_name =
3949     getStringCopyNStatic(SDLGetRendererName(), driver_name_len);
3950
3951   DrawTextF(xstart1, ystart, font_text, "Render Driver");
3952   DrawTextF(xstart2, ystart, font_text, "%s", setup.system.sdl_renderdriver);
3953   DrawTextF(xstart3, ystart, font_text, "%s", driver_name);
3954   ystart += ystep_line;
3955
3956   driver_name =
3957     getStringCopyNStatic(SDL_GetCurrentVideoDriver(), driver_name_len);
3958
3959   DrawTextF(xstart1, ystart, font_text, "Video Driver");
3960   DrawTextF(xstart2, ystart, font_text, "%s", setup.system.sdl_videodriver);
3961   DrawTextF(xstart3, ystart, font_text, "%s", driver_name);
3962   ystart += ystep_line;
3963
3964   driver_name =
3965     getStringCopyNStatic(SDL_GetCurrentAudioDriver(), driver_name_len);
3966
3967   DrawTextF(xstart1, ystart, font_text, "Audio Driver");
3968   DrawTextF(xstart2, ystart, font_text, "%s", setup.system.sdl_audiodriver);
3969   DrawTextF(xstart3, ystart, font_text, "%s", driver_name);
3970
3971   DrawTextSCentered(ybottom, font_foot, TEXT_NEXT_MENU);
3972
3973   PlayInfoSoundsAndMusic();
3974
3975   FadeIn(REDRAW_FIELD);
3976 }
3977
3978 void HandleInfoScreen_Version(int button)
3979 {
3980   if (button == MB_MENU_LEAVE)
3981   {
3982     PlaySound(SND_MENU_ITEM_SELECTING);
3983
3984     info_mode = INFO_MODE_MAIN;
3985     DrawInfoScreen();
3986
3987     return;
3988   }
3989   else if (button == MB_MENU_CHOICE)
3990   {
3991     PlaySound(SND_MENU_ITEM_SELECTING);
3992
3993     FadeMenuSoundsAndMusic();
3994
3995     info_mode = INFO_MODE_MAIN;
3996     DrawInfoScreen();
3997   }
3998   else
3999   {
4000     PlayMenuSoundIfLoop();
4001   }
4002 }
4003
4004 static char *getInfoScreenTitle_Generic(void)
4005 {
4006   return (info_mode == INFO_MODE_MAIN     ? STR_INFO_MAIN     :
4007           info_mode == INFO_MODE_TITLE    ? STR_INFO_TITLE    :
4008           info_mode == INFO_MODE_ELEMENTS ? STR_INFO_ELEMENTS :
4009           info_mode == INFO_MODE_MUSIC    ? STR_INFO_MUSIC    :
4010           info_mode == INFO_MODE_CREDITS  ? STR_INFO_CREDITS  :
4011           info_mode == INFO_MODE_PROGRAM  ? STR_INFO_PROGRAM  :
4012           info_mode == INFO_MODE_VERSION  ? STR_INFO_VERSION  :
4013           info_mode == INFO_MODE_LEVELSET ? STR_INFO_LEVELSET :
4014           "");
4015 }
4016
4017 static int getInfoScreenBackgroundImage_Generic(void)
4018 {
4019   return (info_mode == INFO_MODE_ELEMENTS ? IMG_BACKGROUND_INFO_ELEMENTS :
4020           info_mode == INFO_MODE_MUSIC    ? IMG_BACKGROUND_INFO_MUSIC    :
4021           info_mode == INFO_MODE_CREDITS  ? IMG_BACKGROUND_INFO_CREDITS  :
4022           info_mode == INFO_MODE_PROGRAM  ? IMG_BACKGROUND_INFO_PROGRAM  :
4023           info_mode == INFO_MODE_VERSION  ? IMG_BACKGROUND_INFO_VERSION  :
4024           info_mode == INFO_MODE_LEVELSET ? IMG_BACKGROUND_INFO_LEVELSET :
4025           IMG_BACKGROUND_INFO);
4026 }
4027
4028 static int getInfoScreenBackgroundSound_Generic(void)
4029 {
4030   return (info_mode == INFO_MODE_ELEMENTS ? SND_BACKGROUND_INFO_ELEMENTS :
4031           info_mode == INFO_MODE_CREDITS  ? SND_BACKGROUND_INFO_CREDITS  :
4032           info_mode == INFO_MODE_PROGRAM  ? SND_BACKGROUND_INFO_PROGRAM  :
4033           info_mode == INFO_MODE_VERSION  ? SND_BACKGROUND_INFO_VERSION  :
4034           info_mode == INFO_MODE_LEVELSET ? SND_BACKGROUND_INFO_LEVELSET :
4035           SND_BACKGROUND_INFO);
4036 }
4037
4038 static int getInfoScreenBackgroundMusic_Generic(void)
4039 {
4040   return (info_mode == INFO_MODE_ELEMENTS ? MUS_BACKGROUND_INFO_ELEMENTS :
4041           info_mode == INFO_MODE_CREDITS  ? MUS_BACKGROUND_INFO_CREDITS  :
4042           info_mode == INFO_MODE_PROGRAM  ? MUS_BACKGROUND_INFO_PROGRAM  :
4043           info_mode == INFO_MODE_VERSION  ? MUS_BACKGROUND_INFO_VERSION  :
4044           info_mode == INFO_MODE_LEVELSET ? MUS_BACKGROUND_INFO_LEVELSET :
4045           MUS_BACKGROUND_INFO);
4046 }
4047
4048 static char *getInfoScreenFilename_Generic(int nr, boolean global)
4049 {
4050   return (info_mode == INFO_MODE_CREDITS  ? getCreditsFilename(nr, global) :
4051           info_mode == INFO_MODE_PROGRAM  ? getProgramInfoFilename(nr)     :
4052           info_mode == INFO_MODE_LEVELSET ? getLevelSetInfoFilename(nr)    :
4053           NULL);
4054 }
4055
4056 static void DrawInfoScreen_GenericScreen(int screen_nr, int num_screens,
4057                                          int use_global_screens)
4058 {
4059   char *filename = getInfoScreenFilename_Generic(screen_nr, use_global_screens);
4060   int font_text = MENU_INFO_FONT_TEXT;
4061   int font_foot = MENU_INFO_FONT_FOOT;
4062   int spacing_line = menu.line_spacing_info[info_mode];
4063   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
4064
4065   ClearField();
4066
4067   DrawInfoScreen_Headline(screen_nr, num_screens, use_global_screens);
4068
4069   if (info_mode == INFO_MODE_CREDITS ||
4070       info_mode == INFO_MODE_PROGRAM)
4071   {
4072     int width = SXSIZE;
4073     int height = MENU_SCREEN_INFO_YBOTTOM - MENU_SCREEN_INFO_YSTART;
4074     int chars = width / getFontWidth(font_text);
4075     int lines = height / getFontHeight(font_text);
4076     int padx = (width - chars * getFontWidth(font_text)) / 2;
4077     int line_spacing = getMenuTextSpacing(spacing_line, font_text);
4078     int xstart = mSX + padx;
4079     int ystart = mSY + MENU_SCREEN_INFO_YSTART + getHeadlineSpacing();
4080     boolean autowrap = FALSE;
4081     boolean centered = TRUE;
4082     boolean parse_comments = TRUE;
4083
4084     DrawTextFile(xstart, ystart,
4085                  filename, font_text, chars, -1, lines, line_spacing, -1,
4086                  autowrap, centered, parse_comments);
4087   }
4088   else if (info_mode == INFO_MODE_LEVELSET)
4089   {
4090     struct TitleMessageInfo *tmi = &readme;
4091
4092     // if x position set to "-1", automatically determine by playfield width
4093     if (tmi->x == -1)
4094       tmi->x = SXSIZE / 2;
4095
4096     // if y position set to "-1", use static default value
4097     if (tmi->y == -1)
4098       tmi->y = MENU_SCREEN_INFO_YSTART + getHeadlineSpacing();
4099
4100     // if width set to "-1", automatically determine by playfield width
4101     if (tmi->width == -1)
4102       tmi->width = SXSIZE - 2 * TILEX;
4103
4104     // if height set to "-1", automatically determine by playfield height
4105     if (tmi->height == -1)
4106       tmi->height = MENU_SCREEN_INFO_YBOTTOM - tmi->y - 10;
4107
4108     // if chars set to "-1", automatically determine by text and font width
4109     if (tmi->chars == -1)
4110       tmi->chars = tmi->width / getFontWidth(tmi->font);
4111     else
4112       tmi->width = tmi->chars * getFontWidth(tmi->font);
4113
4114     // if lines set to "-1", automatically determine by text and font height
4115     if (tmi->lines == -1)
4116       tmi->lines = tmi->height / getFontHeight(tmi->font);
4117     else
4118       tmi->height = tmi->lines * getFontHeight(tmi->font);
4119
4120     DrawTextFile(mSX + ALIGNED_TEXT_XPOS(tmi), mSY + ALIGNED_TEXT_YPOS(tmi),
4121                  filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
4122                  tmi->autowrap, tmi->centered, tmi->parse_comments);
4123   }
4124
4125   boolean last_screen = (screen_nr == num_screens - 1);
4126   char *text_foot = (last_screen ? TEXT_NEXT_MENU : TEXT_NEXT_PAGE);
4127
4128   DrawTextSCentered(ybottom, font_foot, text_foot);
4129 }
4130
4131 static void DrawInfoScreen_Generic(void)
4132 {
4133   SetMainBackgroundImageIfDefined(getInfoScreenBackgroundImage_Generic());
4134
4135   UnmapAllGadgets();
4136   FadeInfoSoundsAndMusic();
4137
4138   FadeOut(REDRAW_FIELD);
4139
4140   HandleInfoScreen_Generic(0, 0, MB_MENU_INITIALIZE);
4141
4142   PlayInfoSoundsAndMusic();
4143
4144   FadeIn(REDRAW_FIELD);
4145 }
4146
4147 void HandleInfoScreen_Generic(int dx, int dy, int button)
4148 {
4149   static char *text_no_info = "";
4150   static int num_screens = 0;
4151   static int screen_nr = 0;
4152   static boolean use_global_screens = FALSE;
4153
4154   if (button == MB_MENU_INITIALIZE)
4155   {
4156     num_screens = 0;
4157     screen_nr = 0;
4158
4159     if (info_mode == INFO_MODE_CREDITS)
4160     {
4161       int i;
4162
4163       for (i = 0; i < 2; i++)
4164       {
4165         use_global_screens = i;         // check for "FALSE", then "TRUE"
4166
4167         // determine number of (global or level set specific) credits screens
4168         while (getCreditsFilename(num_screens, use_global_screens) != NULL)
4169           num_screens++;
4170
4171         if (num_screens > 0)
4172           break;
4173       }
4174
4175       text_no_info = "No credits available.";
4176     }
4177     else if (info_mode == INFO_MODE_PROGRAM)
4178     {
4179       use_global_screens = TRUE;
4180
4181       // determine number of program info screens
4182       while (getProgramInfoFilename(num_screens) != NULL)
4183         num_screens++;
4184
4185       text_no_info = "No program info available.";
4186     }
4187     else if (info_mode == INFO_MODE_LEVELSET)
4188     {
4189       use_global_screens = FALSE;
4190
4191       // determine number of levelset info screens
4192       while (getLevelSetInfoFilename(num_screens) != NULL)
4193         num_screens++;
4194
4195       text_no_info = "No level set info available.";
4196     }
4197
4198     if (num_screens == 0)
4199     {
4200       int font_title = MENU_INFO_FONT_TITLE;
4201       int font_foot  = MENU_INFO_FONT_FOOT;
4202       int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART;
4203       int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
4204
4205       ClearField();
4206
4207       DrawInfoScreen_Headline(screen_nr, num_screens, use_global_screens);
4208
4209       DrawTextSCentered(ystart, font_title, text_no_info);
4210       DrawTextSCentered(ybottom, font_foot, TEXT_NEXT_MENU);
4211
4212       return;
4213     }
4214
4215     DrawInfoScreen_GenericScreen(screen_nr, num_screens, use_global_screens);
4216   }
4217   else if (button == MB_MENU_LEAVE)
4218   {
4219     PlaySound(SND_MENU_ITEM_SELECTING);
4220
4221     info_mode = INFO_MODE_MAIN;
4222     DrawInfoScreen();
4223   }
4224   else if (button == MB_MENU_CHOICE || dx)
4225   {
4226     PlaySound(SND_MENU_ITEM_SELECTING);
4227
4228     screen_nr += (dx < 0 ? -1 : +1);
4229
4230     if (screen_nr < 0 || screen_nr >= num_screens)
4231     {
4232       FadeInfoSoundsAndMusic();
4233
4234       info_mode = INFO_MODE_MAIN;
4235       DrawInfoScreen();
4236     }
4237     else
4238     {
4239       FadeSetNextScreen();
4240
4241       FadeOut(REDRAW_FIELD);
4242
4243       DrawInfoScreen_GenericScreen(screen_nr, num_screens, use_global_screens);
4244
4245       FadeIn(REDRAW_FIELD);
4246     }
4247   }
4248   else
4249   {
4250     PlayInfoSoundIfLoop();
4251   }
4252 }
4253
4254 static void DrawInfoScreen(void)
4255 {
4256   if (info_mode == INFO_MODE_TITLE)
4257     DrawInfoScreen_TitleScreen();
4258   else if (info_mode == INFO_MODE_ELEMENTS)
4259     DrawInfoScreen_Elements();
4260   else if (info_mode == INFO_MODE_MUSIC)
4261     DrawInfoScreen_Music();
4262   else if (info_mode == INFO_MODE_CREDITS)
4263     DrawInfoScreen_Generic();
4264   else if (info_mode == INFO_MODE_PROGRAM)
4265     DrawInfoScreen_Generic();
4266   else if (info_mode == INFO_MODE_VERSION)
4267     DrawInfoScreen_Version();
4268   else if (info_mode == INFO_MODE_LEVELSET)
4269     DrawInfoScreen_Generic();
4270   else
4271     DrawInfoScreen_Main();
4272 }
4273
4274 void DrawInfoScreen_FromMainMenu(int nr)
4275 {
4276   int fade_mask = REDRAW_FIELD;
4277
4278   if (nr < INFO_MODE_MAIN || nr >= MAX_INFO_MODES)
4279     return;
4280
4281   CloseDoor(DOOR_CLOSE_2);
4282
4283   SetGameStatus(GAME_MODE_INFO);
4284
4285   info_mode = nr;
4286   info_screens_from_main = TRUE;
4287
4288   if (redraw_mask & REDRAW_ALL)
4289     fade_mask = REDRAW_ALL;
4290
4291   if (CheckFadeAll())
4292     fade_mask = REDRAW_ALL;
4293
4294   UnmapAllGadgets();
4295   FadeMenuSoundsAndMusic();
4296
4297   FadeSetEnterScreen();
4298
4299   FadeOut(fade_mask);
4300
4301   FadeSkipNextFadeOut();
4302
4303   // needed if different viewport properties defined for info screen
4304   ChangeViewportPropertiesIfNeeded();
4305
4306   SetMainBackgroundImage(IMG_BACKGROUND_INFO);
4307
4308   DrawInfoScreen();
4309 }
4310
4311 void HandleInfoScreen(int mx, int my, int dx, int dy, int button)
4312 {
4313   if (info_mode == INFO_MODE_TITLE)
4314     HandleInfoScreen_TitleScreen(dx, dy, button);
4315   else if (info_mode == INFO_MODE_ELEMENTS)
4316     HandleInfoScreen_Elements(dx, dy, button);
4317   else if (info_mode == INFO_MODE_MUSIC)
4318     HandleInfoScreen_Music(dx, dy, button);
4319   else if (info_mode == INFO_MODE_CREDITS)
4320     HandleInfoScreen_Generic(dx, dy, button);
4321   else if (info_mode == INFO_MODE_PROGRAM)
4322     HandleInfoScreen_Generic(dx, dy, button);
4323   else if (info_mode == INFO_MODE_VERSION)
4324     HandleInfoScreen_Version(button);
4325   else if (info_mode == INFO_MODE_LEVELSET)
4326     HandleInfoScreen_Generic(dx, dy, button);
4327   else
4328     HandleInfoScreen_Main(mx, my, dx, dy, button);
4329 }
4330
4331
4332 // ============================================================================
4333 // type name functions
4334 // ============================================================================
4335
4336 static TreeInfo *type_name_node = NULL;
4337 static char type_name_last[MAX_PLAYER_NAME_LEN + 1] = { 0 };
4338 static int type_name_nr = 0;
4339
4340 static int getPlayerNameColor(char *name)
4341 {
4342   return (strEqual(name, EMPTY_PLAYER_NAME) ? FC_BLUE : FC_RED);
4343 }
4344
4345 static void drawTypeNameText(char *name, struct TextPosInfo *pos,
4346                              boolean active)
4347 {
4348   char text[MAX_PLAYER_NAME_LEN + 2] = { 0 };
4349   boolean multiple_users = (game_status == GAME_MODE_PSEUDO_TYPENAMES);
4350   int sx = (multiple_users ? amSX + pos->x : mSX + ALIGNED_TEXT_XPOS(pos));
4351   int sy = (multiple_users ? amSY + pos->y : mSY + ALIGNED_TEXT_YPOS(pos));
4352   int font_nr = (active ? FONT_ACTIVE(pos->font) : pos->font);
4353   int font_width = getFontWidth(font_nr);
4354   int font_xoffset = getFontDrawOffsetX(font_nr);
4355   int font_yoffset = getFontDrawOffsetY(font_nr);
4356   int font_sx = sx + font_xoffset;
4357   int font_sy = sy + font_yoffset;
4358
4359   DrawBackgroundForFont(font_sx, font_sy, pos->width, pos->height, font_nr);
4360
4361   sprintf(text, "%s%c", name, (active ? '_' : '\0'));
4362
4363   pos->width = strlen(text) * font_width;
4364   sx = (multiple_users ? amSX + pos->x : mSX + ALIGNED_TEXT_XPOS(pos));
4365
4366   DrawText(sx, sy, text, font_nr);
4367 }
4368
4369 static void getTypeNameValues(char *name, struct TextPosInfo *pos, int *xpos)
4370 {
4371   struct MainControlInfo *mci = getMainControlInfo(MAIN_CONTROL_NAME);
4372
4373   *pos = *mci->pos_input;
4374
4375   if (game_status == GAME_MODE_PSEUDO_TYPENAMES)
4376   {
4377     TreeInfo *ti = player_name_current;
4378     int first_entry = ti->cl_first;
4379     int entry_pos = first_entry + ti->cl_cursor;
4380     TreeInfo *node_first = getTreeInfoFirstGroupEntry(ti);
4381     int xpos = MENU_SCREEN_START_XPOS;
4382     int ypos = MENU_SCREEN_START_YPOS + ti->cl_cursor;
4383
4384     type_name_node = getTreeInfoFromPos(node_first, entry_pos);
4385     type_name_nr = entry_pos;
4386
4387     strcpy(name, type_name_node->name);
4388
4389     pos->x = xpos * 32;
4390     pos->y = ypos * 32;
4391     pos->width = MAX_PLAYER_NAME_LEN * 32;
4392   }
4393   else
4394   {
4395     type_name_nr = user.nr;
4396
4397     strcpy(name, setup.player_name);
4398   }
4399
4400   strcpy(type_name_last, name);
4401
4402   if (strEqual(name, EMPTY_PLAYER_NAME))
4403     strcpy(name, "");
4404
4405   *xpos = strlen(name);
4406 }
4407
4408 static void setTypeNameValues_Name(char *name, struct TextPosInfo *pos)
4409 {
4410   // change name of edited user in global list of user names
4411   setString(&global.user_names[type_name_nr], name);
4412
4413   if (game_status == GAME_MODE_PSEUDO_TYPENAMES)
4414   {
4415     TreeInfo *node = type_name_node;
4416
4417     // change name of edited user in local menu tree structure
4418     setString(&node->name, name);
4419     setString(&node->name_sorting, name);
4420
4421     node->color = getPlayerNameColor(name);
4422     pos->font = MENU_CHOOSE_TREE_FONT(node->color);
4423   }
4424 }
4425
4426 static void setTypeNameValues(char *name, struct TextPosInfo *pos,
4427                               boolean changed)
4428 {
4429   boolean reset_setup = strEqual(name, "");
4430   boolean remove_user = strEqual(name, EMPTY_PLAYER_NAME);
4431   boolean create_user = strEqual(type_name_last, EMPTY_PLAYER_NAME);
4432
4433   if (!changed)
4434     strcpy(name, type_name_last);
4435
4436   if (strEqual(name, ""))
4437     strcpy(name, EMPTY_PLAYER_NAME);
4438
4439   setTypeNameValues_Name(name, pos);
4440
4441   // if player name not changed, no further action required
4442   if (strEqual(name, type_name_last))
4443     return;
4444
4445   // redraw player name before (possibly) opening request dialogs
4446   drawTypeNameText(name, pos, FALSE);
4447
4448   int last_user_nr = user.nr;
4449
4450   if (game_status == GAME_MODE_PSEUDO_TYPENAMES)
4451   {
4452     // save setup of currently active user (may differ from edited user)
4453     SaveSetup();
4454
4455     // temporarily change active user to edited user
4456     user.nr = type_name_nr;
4457
4458     if (create_user &&
4459         Request("Use current setup values for the new player?", REQ_ASK))
4460     {
4461       // use current setup values for new user, but create new player UUID
4462       setup.player_uuid = getStringCopy(getUUID());
4463     }
4464     else
4465     {
4466       // load setup for existing user (or start with defaults for new user)
4467       LoadSetup();
4468     }
4469   }
4470
4471   char *setup_filename = getSetupFilename();
4472   boolean setup_exists = fileExists(setup_filename);
4473
4474   // change name of edited user in setup structure
4475   strcpy(setup.player_name, name);
4476
4477   // save setup of edited user
4478   SaveSetup();
4479
4480   // change name of edited user on score server
4481   ApiRenamePlayerAsThread();
4482
4483   if (game_status == GAME_MODE_PSEUDO_TYPENAMES || reset_setup)
4484   {
4485     if (reset_setup)
4486     {
4487       if (Request("Reset setup values for this player?", REQ_ASK))
4488       {
4489         // remove setup config file
4490         unlink(setup_filename);
4491
4492         // set player name to default player name
4493         LoadSetup();
4494
4495         // update player name used by name typing functions
4496         strcpy(name, setup.player_name);
4497
4498         setTypeNameValues_Name(name, pos);
4499       }
4500     }
4501     else if (remove_user && type_name_nr != 0)
4502     {
4503       if (Request("Remove settings and tapes for deleted player?", REQ_ASK))
4504       {
4505         char *user_dir = getUserGameDataDir();
4506         char *user_dir_removed =
4507           getStringCat3WithSeparator(user_dir, "REMOVED",
4508                                      getCurrentTimestamp(), ".");
4509
4510         if (rename(user_dir, user_dir_removed) != 0)
4511           Request("Removing settings and tapes failed!", REQ_CONFIRM);
4512
4513         checked_free(user_dir_removed);
4514       }
4515     }
4516     else if (create_user && type_name_nr != 0 && !setup_exists)
4517     {
4518       if (Request("Create empty level set for the new player?", REQ_ASK))
4519       {
4520         char *levelset_subdir = getNewUserLevelSubdir();
4521
4522         if (CreateUserLevelSet(levelset_subdir, name, name, 100, FALSE))
4523         {
4524           AddUserLevelSetToLevelInfo(levelset_subdir);
4525
4526           LevelDirTree *leveldir_current_last = leveldir_current;
4527
4528           leveldir_current = getTreeInfoFromIdentifier(leveldir_first,
4529                                                        levelset_subdir);
4530
4531           // set level number of newly created level set to default value
4532           LoadLevelSetup_SeriesInfo();
4533
4534           // set newly created level set as current level set for new user
4535           SaveLevelSetup_LastSeries();
4536           SaveLevelSetup_SeriesInfo();
4537
4538           leveldir_current = leveldir_current_last;
4539         }
4540         else
4541         {
4542           Request("Creating new level set failed!", REQ_CONFIRM);
4543         }
4544       }
4545     }
4546
4547     // restore currently active user
4548     user.nr = last_user_nr;
4549
4550     // restore setup of currently active user
4551     LoadSetup();
4552
4553     // restore last level set of currently active user
4554     LoadLevelSetup_LastSeries();
4555     LoadLevelSetup_SeriesInfo();
4556   }
4557 }
4558
4559 static void HandleTypeNameExt(boolean initialize, Key key)
4560 {
4561   static struct TextPosInfo pos_name = { 0 };
4562   static char name[MAX_PLAYER_NAME_LEN + 1] = { 0 };
4563   static int xpos = 0;
4564   struct TextPosInfo *pos = &pos_name;
4565   char key_char = getValidConfigValueChar(getCharFromKey(key));
4566   boolean is_valid_key_char = (key_char != 0 && (key_char != ' ' || xpos > 0));
4567   boolean active = TRUE;
4568
4569   if (initialize)
4570   {
4571     getTypeNameValues(name, pos, &xpos);
4572
4573     int sx = mSX + ALIGNED_TEXT_XPOS(pos);
4574     int sy = mSY + ALIGNED_TEXT_YPOS(pos);
4575
4576     StartTextInput(sx, sy, pos->width, pos->height);
4577   }
4578   else if (is_valid_key_char && xpos < MAX_PLAYER_NAME_LEN)
4579   {
4580     name[xpos] = key_char;
4581     name[xpos + 1] = 0;
4582
4583     xpos++;
4584   }
4585   else if ((key == KSYM_Delete || key == KSYM_BackSpace) && xpos > 0)
4586   {
4587     xpos--;
4588
4589     name[xpos] = 0;
4590   }
4591   else if (key == KSYM_Return || key == KSYM_Escape)
4592   {
4593     boolean changed = (key == KSYM_Return);
4594
4595     StopTextInput();
4596
4597     setTypeNameValues(name, pos, changed);
4598
4599     active = FALSE;
4600   }
4601
4602   drawTypeNameText(name, pos, active);
4603
4604   if (!active)
4605   {
4606     SetGameStatus(game_status_last_screen);
4607
4608     if (game_status == GAME_MODE_MAIN)
4609       InitializeMainControls();
4610   }
4611 }
4612
4613 static void DrawTypeName(void)
4614 {
4615   HandleTypeNameExt(TRUE, 0);
4616 }
4617
4618 void HandleTypeName(Key key)
4619 {
4620   HandleTypeNameExt(FALSE, key);
4621 }
4622
4623
4624 // ============================================================================
4625 // tree menu functions
4626 // ============================================================================
4627
4628 static int getAlignXOffsetFromTreeInfo(TreeInfo *ti)
4629 {
4630   if (game_status != GAME_MODE_SETUP ||
4631       DRAW_MODE_SETUP(setup_mode) != SETUP_MODE_CHOOSE_OTHER)
4632     return 0;
4633
4634   int max_text_size = 0;
4635   TreeInfo *node;
4636
4637   for (node = getTreeInfoFirstGroupEntry(ti); node != NULL; node = node->next)
4638     max_text_size = MAX(max_text_size, strlen(node->name));
4639
4640   int num_entries = numTreeInfoInGroup(ti);
4641   boolean scrollbar_needed = (num_entries > NUM_MENU_ENTRIES_ON_SCREEN);
4642   int font_nr = MENU_CHOOSE_TREE_FONT(FC_RED);
4643   int text_width = max_text_size * getFontWidth(font_nr);
4644   int button_width = SC_MENUBUTTON_XSIZE;
4645   int scrollbar_xpos = SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
4646   int screen_width = (scrollbar_needed ? scrollbar_xpos : SXSIZE);
4647   int align = menu.list_setup[SETUP_MODE_CHOOSE_OTHER].align;
4648   int x = ALIGNED_XPOS(0, screen_width, align) * -1;
4649   int align_xoffset_raw = ALIGNED_XPOS(x, button_width + text_width, align);
4650   int align_xoffset = MAX(0, align_xoffset_raw);
4651
4652   return align_xoffset;
4653 }
4654
4655 static int getAlignYOffsetFromTreeInfo(TreeInfo *ti)
4656 {
4657   if (game_status != GAME_MODE_SETUP ||
4658       DRAW_MODE_SETUP(setup_mode) != SETUP_MODE_CHOOSE_OTHER)
4659     return 0;
4660
4661   int num_entries = numTreeInfoInGroup(ti);
4662   int num_page_entries = MIN(num_entries, NUM_MENU_ENTRIES_ON_SCREEN);
4663   int font_nr = MENU_CHOOSE_TREE_FONT(FC_RED);
4664   int font_height = getFontHeight(font_nr);
4665   int text_height = font_height * num_page_entries;
4666   int page_height = font_height * NUM_MENU_ENTRIES_ON_SCREEN;
4667   int align = menu.list_setup[SETUP_MODE_CHOOSE_OTHER].valign;
4668   int y = ALIGNED_YPOS(0, page_height, align) * -1;
4669   int align_yoffset_raw = ALIGNED_YPOS(y, text_height, align);
4670   int align_yoffset = MAX(0, align_yoffset_raw);
4671
4672   return align_yoffset;
4673 }
4674
4675 static void StartPlayingFromHallOfFame(void)
4676 {
4677   level_nr = scores.next_level_nr;
4678   LoadLevel(level_nr);
4679
4680   StartGameActions(network.enabled, setup.autorecord, level.random_seed);
4681 }
4682
4683 static void DrawChooseTree(TreeInfo **ti_ptr)
4684 {
4685   int fade_mask = REDRAW_FIELD;
4686   boolean restart_music = (game_status != game_status_last_screen &&
4687                            game_status_last_screen != GAME_MODE_SCOREINFO);
4688
4689   scores.continue_on_return = (game_status == GAME_MODE_SCORES &&
4690                                game_status_last_screen == GAME_MODE_PLAYING);
4691
4692   if (CheckFadeAll())
4693     fade_mask = REDRAW_ALL;
4694
4695   if (*ti_ptr != NULL && strEqual((*ti_ptr)->subdir, STRING_TOP_DIRECTORY))
4696   {
4697     if (game_status == GAME_MODE_SETUP)
4698     {
4699       execSetupArtwork();
4700     }
4701     else if (game_status == GAME_MODE_SCORES && scores.continue_playing)
4702     {
4703       StartPlayingFromHallOfFame();
4704     }
4705     else
4706     {
4707       SetGameStatus(GAME_MODE_MAIN);
4708
4709       DrawMainMenu();
4710     }
4711
4712     return;
4713   }
4714
4715   UnmapAllGadgets();
4716
4717   FreeScreenGadgets();
4718   CreateScreenGadgets();
4719
4720   if (restart_music)
4721     FadeMenuSoundsAndMusic();
4722
4723   FadeOut(fade_mask);
4724
4725   // needed if different viewport properties defined for this screen
4726   ChangeViewportPropertiesIfNeeded();
4727
4728   if (game_status == GAME_MODE_NAMES)
4729     SetMainBackgroundImage(IMG_BACKGROUND_NAMES);
4730   else if (game_status == GAME_MODE_LEVELNR)
4731     SetMainBackgroundImage(IMG_BACKGROUND_LEVELNR);
4732   else if (game_status == GAME_MODE_LEVELS)
4733     SetMainBackgroundImage(IMG_BACKGROUND_LEVELS);
4734   else if (game_status == GAME_MODE_SCORES)
4735     SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
4736
4737   ClearField();
4738
4739   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
4740
4741   // map gadgets for high score screen
4742   if (game_status == GAME_MODE_SCORES)
4743     MapScreenMenuGadgets(SCREEN_MASK_SCORES);
4744
4745   MapScreenTreeGadgets(*ti_ptr);
4746
4747   HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, ti_ptr);
4748
4749   DrawMaskedBorder(fade_mask);
4750
4751   if (restart_music)
4752     PlayMenuSoundsAndMusic();
4753
4754   FadeIn(fade_mask);
4755 }
4756
4757 static int getChooseTreeFont(TreeInfo *node, boolean active)
4758 {
4759   if (game_status == GAME_MODE_SCORES)
4760     return (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4761   else
4762     return MENU_CHOOSE_TREE_FONT(MENU_CHOOSE_TREE_COLOR(node, active));
4763 }
4764
4765 static void drawChooseTreeText(TreeInfo *ti, int y, boolean active)
4766 {
4767   int num_entries = numTreeInfoInGroup(ti);
4768   boolean scrollbar_needed = (num_entries > NUM_MENU_ENTRIES_ON_SCREEN);
4769   int scrollbar_xpos = SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
4770   int screen_width = (scrollbar_needed ? scrollbar_xpos : SXSIZE);
4771   int first_entry = ti->cl_first;
4772   int entry_pos = first_entry + y;
4773   TreeInfo *node_first = getTreeInfoFirstGroupEntry(ti);
4774   TreeInfo *node = getTreeInfoFromPos(node_first, entry_pos);
4775   int font_nr = getChooseTreeFont(node, active);
4776   int font_xoffset = getFontDrawOffsetX(font_nr);
4777   int xpos = MENU_SCREEN_START_XPOS;
4778   int ypos = MENU_SCREEN_START_YPOS + y;
4779   int startdx = xpos * 32;
4780   int startdy = ypos * 32;
4781   int startx = amSX + startdx;
4782   int starty = amSY + startdy;
4783   int startx_text = startx + font_xoffset;
4784   int endx_text = amSX + screen_width;
4785   int max_text_size = endx_text - startx_text;
4786   int max_buffer_len = max_text_size / getFontWidth(font_nr);
4787   char buffer[max_buffer_len + 1];
4788
4789   if (game_status == GAME_MODE_SCORES && !node->parent_link)
4790   {
4791     int font_nr1 = (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4792     int font_nr2 = (active ? FONT_TEXT_2_ACTIVE : FONT_TEXT_2);
4793     int font_nr3 = (active ? FONT_TEXT_3_ACTIVE : FONT_TEXT_3);
4794     int font_nr4 = (active ? FONT_TEXT_4_ACTIVE : FONT_TEXT_4);
4795     int font_size_1 = getFontWidth(font_nr1);
4796     int font_size_3 = getFontWidth(font_nr3);
4797     int font_size_4 = getFontWidth(font_nr4);
4798     int text_size_1 = 4 * font_size_1;
4799     int text_size_4 = 5 * font_size_4;
4800     int border = amSX - SX + getFontDrawOffsetX(font_nr1);
4801     int dx1 = 0;
4802     int dx3 = text_size_1;
4803     int dx4 = SXSIZE - 2 * startdx - 2 * border - text_size_4;
4804     int num_dots = (dx4 - dx3) / font_size_3;
4805     int startx1 = startx + dx1;
4806     int startx3 = startx + dx3;
4807     int startx4 = startx + dx4;
4808     int pos = node->pos;
4809     char *pos_text = getHallOfFameRankText(pos, 3);
4810     int i;
4811
4812     // highlight all high score entries of the current player
4813     if (strEqual(scores.entry[pos].name, setup.player_name))
4814       font_nr2 = FONT_TEXT_2_ACTIVE;
4815
4816     DrawText(startx1, starty, pos_text, font_nr1);
4817
4818     for (i = 0; i < num_dots; i++)
4819       DrawText(startx3 + i * font_size_3, starty, ".", font_nr3);
4820
4821     if (!strEqual(scores.entry[pos].name, EMPTY_PLAYER_NAME))
4822       DrawText(startx3, starty, scores.entry[pos].name, font_nr2);
4823
4824     DrawText(startx4, starty, getHallOfFameScoreText(pos, 5), font_nr4);
4825   }
4826   else
4827   {
4828     strncpy(buffer, node->name, max_buffer_len);
4829     buffer[max_buffer_len] = '\0';
4830
4831     DrawText(startx, starty, buffer, font_nr);
4832   }
4833 }
4834
4835 static void drawChooseTreeHeadExt(int type, char *title_string)
4836 {
4837   int yoffset_sets = MENU_TITLE1_YPOS;
4838   int yoffset_setup = 16;
4839   int yoffset = (type == TREE_TYPE_SCORE_ENTRY ||
4840                  type == TREE_TYPE_LEVEL_DIR ||
4841                  type == TREE_TYPE_LEVEL_NR ? yoffset_sets : yoffset_setup);
4842
4843   DrawTextSCentered(mSY - SY + yoffset, FONT_TITLE_1, title_string);
4844 }
4845
4846 static void drawChooseTreeHead(TreeInfo *ti)
4847 {
4848   drawChooseTreeHeadExt(ti->type, ti->infotext);
4849 }
4850
4851 static void drawChooseTreeList(TreeInfo *ti)
4852 {
4853   int first_entry = ti->cl_first;
4854   int num_entries = numTreeInfoInGroup(ti);
4855   int num_page_entries = MIN(num_entries, NUM_MENU_ENTRIES_ON_SCREEN);
4856   int i;
4857
4858   clearMenuListArea();
4859
4860   for (i = 0; i < num_page_entries; i++)
4861   {
4862     TreeInfo *node, *node_first;
4863     int entry_pos = first_entry + i;
4864
4865     node_first = getTreeInfoFirstGroupEntry(ti);
4866     node = getTreeInfoFromPos(node_first, entry_pos);
4867
4868     drawChooseTreeText(ti, i, FALSE);
4869
4870     if (node->parent_link)
4871       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
4872     else if (node->level_group)
4873       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
4874     else
4875       initCursor(i, IMG_MENU_BUTTON);
4876
4877     if (game_status == GAME_MODE_SCORES && node->pos == scores.last_added)
4878       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
4879
4880     if (game_status == GAME_MODE_NAMES)
4881       drawChooseTreeEdit(i, FALSE);
4882   }
4883
4884   redraw_mask |= REDRAW_FIELD;
4885 }
4886
4887 static void drawChooseTreeInfo(TreeInfo *ti)
4888 {
4889   int entry_pos = ti->cl_first + ti->cl_cursor;
4890   int last_redraw_mask = redraw_mask;
4891   int ypos = MENU_TITLE2_YPOS;
4892   int font_nr = FONT_TITLE_2;
4893   int x;
4894
4895   if (ti->type == TREE_TYPE_LEVEL_NR)
4896     DrawTextFCentered(ypos, font_nr, leveldir_current->name);
4897
4898   if (ti->type == TREE_TYPE_SCORE_ENTRY)
4899     DrawTextFCentered(ypos, font_nr, "HighScores of Level %d",
4900                       scores.last_level_nr);
4901
4902   if (ti->type != TREE_TYPE_LEVEL_DIR)
4903     return;
4904
4905   TreeInfo *node_first = getTreeInfoFirstGroupEntry(ti);
4906   TreeInfo *node = getTreeInfoFromPos(node_first, entry_pos);
4907
4908   DrawBackgroundForFont(SX, SY + ypos, SXSIZE, getFontHeight(font_nr), font_nr);
4909
4910   if (node->parent_link)
4911     DrawTextFCentered(ypos, font_nr, "leave \"%s\"",
4912                       node->node_parent->name);
4913   else if (node->level_group)
4914     DrawTextFCentered(ypos, font_nr, "enter \"%s\"",
4915                       node->name);
4916   else if (ti->type == TREE_TYPE_LEVEL_DIR)
4917     DrawTextFCentered(ypos, font_nr, "%3d %s (%s)",
4918                       node->levels, (node->levels > 1 ? "levels" : "level"),
4919                       node->class_desc);
4920
4921   // let BackToFront() redraw only what is needed
4922   redraw_mask = last_redraw_mask;
4923   for (x = 0; x < SCR_FIELDX; x++)
4924     MarkTileDirty(x, 1);
4925 }
4926
4927 static void drawChooseTreeCursorAndText(TreeInfo *ti, boolean active)
4928 {
4929   drawChooseTreeCursor(ti->cl_cursor, active);
4930   drawChooseTreeText(ti, ti->cl_cursor, active);
4931 }
4932
4933 static void drawChooseTreeScreen(TreeInfo *ti)
4934 {
4935   drawChooseTreeHead(ti);
4936   drawChooseTreeList(ti);
4937   drawChooseTreeInfo(ti);
4938   drawChooseTreeCursorAndText(ti, TRUE);
4939
4940   AdjustChooseTreeScrollbar(ti, SCREEN_CTRL_ID_SCROLL_VERTICAL);
4941
4942   // scroll bar and buttons may just have been added after reloading scores
4943   if (game_status == GAME_MODE_SCORES)
4944     MapScreenTreeGadgets(ti);
4945 }
4946
4947 static TreeInfo *setHallOfFameActiveEntry(TreeInfo **ti_ptr)
4948 {
4949   int score_pos = scores.last_added;
4950
4951   if (game_status_last_screen == GAME_MODE_SCOREINFO)
4952     score_pos = scores.last_entry_nr;
4953
4954   // set current tree entry to last added score entry
4955   *ti_ptr = getTreeInfoFromIdentifier(score_entries, i_to_a(score_pos));
4956
4957   // if that fails, set current tree entry to first entry (back link)
4958   if (*ti_ptr == NULL)
4959     *ti_ptr = score_entries->node_group;
4960
4961   int num_entries = numTreeInfoInGroup(*ti_ptr);
4962   int num_page_entries = MIN(num_entries, NUM_MENU_ENTRIES_ON_SCREEN);
4963   int pos_score = getPosFromTreeInfo(*ti_ptr);
4964   int pos_first_raw = pos_score - (num_page_entries + 1) / 2 + 1;
4965   int pos_first = MIN(MAX(0, pos_first_raw), num_entries - num_page_entries);
4966
4967   (*ti_ptr)->cl_first = pos_first;
4968   (*ti_ptr)->cl_cursor = pos_score - pos_first;
4969
4970   return *ti_ptr;
4971 }
4972
4973 static void HandleChooseTree(int mx, int my, int dx, int dy, int button,
4974                              TreeInfo **ti_ptr)
4975 {
4976   TreeInfo *ti = *ti_ptr;
4977   boolean has_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->mapped;
4978   int mx_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x;
4979   int mx_right_border = (has_scrollbar ? mx_scrollbar : SX + SXSIZE);
4980   int sx1_edit_name = getChooseTreeEditXPosReal(POS_LEFT);
4981   int sx2_edit_name = getChooseTreeEditXPosReal(POS_RIGHT);
4982   int x = 0;
4983   int y = (ti != NULL ? ti->cl_cursor : 0);
4984   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
4985   int num_entries = numTreeInfoInGroup(ti);
4986   int num_page_entries = MIN(num_entries, NUM_MENU_ENTRIES_ON_SCREEN);
4987   boolean position_set_by_scrollbar = (dx == 999);
4988
4989   if (game_status == GAME_MODE_SCORES)
4990   {
4991     if (server_scores.updated)
4992     {
4993       // reload scores, using updated server score cache file
4994       LoadLocalAndServerScore(scores.last_level_nr, FALSE);
4995
4996       server_scores.updated = FALSE;
4997
4998       DrawHallOfFame_setScoreEntries();
4999
5000       ti = setHallOfFameActiveEntry(ti_ptr);
5001
5002       if (button != MB_MENU_INITIALIZE)
5003         drawChooseTreeScreen(ti);
5004     }
5005   }
5006
5007   if (button == MB_MENU_INITIALIZE)
5008   {
5009     int num_entries = numTreeInfoInGroup(ti);
5010     int entry_pos = getPosFromTreeInfo(ti);
5011
5012     align_xoffset = getAlignXOffsetFromTreeInfo(ti);
5013     align_yoffset = getAlignYOffsetFromTreeInfo(ti);
5014
5015     if (game_status == GAME_MODE_SCORES)
5016     {
5017       ti = setHallOfFameActiveEntry(ti_ptr);
5018     }
5019     else if (ti->cl_first == -1)
5020     {
5021       // only on initialization
5022       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
5023       ti->cl_cursor = entry_pos - ti->cl_first;
5024
5025     }
5026     else if (ti->cl_cursor >= num_page_entries ||
5027              (num_entries > num_page_entries &&
5028               num_entries - ti->cl_first < num_page_entries))
5029     {
5030       // only after change of list size (by custom graphic configuration)
5031       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
5032       ti->cl_cursor = entry_pos - ti->cl_first;
5033     }
5034
5035     if (position_set_by_scrollbar)
5036       ti->cl_first = dy;
5037
5038     drawChooseTreeScreen(ti);
5039
5040     return;
5041   }
5042   else if (button == MB_MENU_LEAVE)
5043   {
5044     if (game_status != GAME_MODE_SCORES)
5045       FadeSetLeaveMenu();
5046
5047     PlaySound(SND_MENU_ITEM_SELECTING);
5048
5049     if (ti->node_parent)
5050     {
5051       *ti_ptr = ti->node_parent;
5052       DrawChooseTree(ti_ptr);
5053     }
5054     else if (game_status == GAME_MODE_SETUP)
5055     {
5056       if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE ||
5057           setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
5058           setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
5059           setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
5060         execSetupGame();
5061       else if (setup_mode == SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE ||
5062                setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64 ||
5063                setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV ||
5064                setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_ATARI ||
5065                setup_mode == SETUP_MODE_CHOOSE_BD_COLOR_TYPE)
5066         execSetupEngines();
5067       else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
5068                setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
5069                setup_mode == SETUP_MODE_CHOOSE_RENDERING ||
5070                setup_mode == SETUP_MODE_CHOOSE_VSYNC)
5071         execSetupGraphics();
5072       else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
5073                setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
5074                setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
5075         execSetupSound();
5076       else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
5077                setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
5078                setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE ||
5079                setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY ||
5080                setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0 ||
5081                setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0 ||
5082                setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1 ||
5083                setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
5084         execSetupTouch();
5085       else
5086         execSetupArtwork();
5087     }
5088     else
5089     {
5090       if (game_status == GAME_MODE_LEVELNR)
5091       {
5092         int new_level_nr = atoi(level_number_current->identifier);
5093
5094         HandleMainMenu_SelectLevel(0, 0, new_level_nr);
5095       }
5096
5097       SetGameStatus(GAME_MODE_MAIN);
5098
5099       DrawMainMenu();
5100     }
5101
5102     return;
5103   }
5104
5105 #if defined(PLATFORM_ANDROID)
5106   // directly continue when touching the screen after playing
5107   if ((mx || my) && scores.continue_on_return)
5108   {
5109     // ignore touch events until released
5110     mx = my = 0;
5111   }
5112 #endif
5113
5114   // any mouse click or cursor key stops leaving scores by "Return" key
5115   if ((mx || my || dx || dy) && scores.continue_on_return)
5116   {
5117     scores.continue_on_return = FALSE;
5118     level_nr = scores.last_level_nr;
5119     LoadLevel(level_nr);
5120   }
5121
5122   if (mx || my)         // mouse input
5123   {
5124     x = (mx - amSX) / 32;
5125     y = (my - amSY) / 32 - MENU_SCREEN_START_YPOS;
5126
5127     if (game_status == GAME_MODE_NAMES)
5128       drawChooseTreeEdit(ti->cl_cursor, FALSE);
5129   }
5130   else if (dx || dy)    // keyboard or scrollbar/scrollbutton input
5131   {
5132     // move cursor instead of scrolling when already at start/end of list
5133     if (dy == -1 * SCROLL_LINE && ti->cl_first == 0)
5134       dy = -1;
5135     else if (dy == +1 * SCROLL_LINE &&
5136              ti->cl_first + num_page_entries == num_entries)
5137       dy = 1;
5138
5139     // handle scrolling screen one line or page
5140     if (ti->cl_cursor + dy < 0 ||
5141         ti->cl_cursor + dy > num_page_entries - 1)
5142     {
5143       boolean redraw = FALSE;
5144
5145       if (ABS(dy) == SCROLL_PAGE)
5146         step = num_page_entries - 1;
5147
5148       if (dy < 0 && ti->cl_first > 0)
5149       {
5150         // scroll page/line up
5151
5152         ti->cl_first -= step;
5153         if (ti->cl_first < 0)
5154           ti->cl_first = 0;
5155
5156         redraw = TRUE;
5157       }
5158       else if (dy > 0 && ti->cl_first + num_page_entries < num_entries)
5159       {
5160         // scroll page/line down
5161
5162         ti->cl_first += step;
5163         if (ti->cl_first + num_page_entries > num_entries)
5164           ti->cl_first = MAX(0, num_entries - num_page_entries);
5165
5166         redraw = TRUE;
5167       }
5168
5169       if (redraw)
5170         drawChooseTreeScreen(ti);
5171
5172       return;
5173     }
5174
5175     // handle moving cursor one line
5176     y = ti->cl_cursor + dy;
5177   }
5178
5179   if (game_status == GAME_MODE_SCORES && ABS(dx) == 1)
5180   {
5181     HandleHallOfFame_SelectLevel(1, dx);
5182
5183     return;
5184   }
5185   else if (game_status == GAME_MODE_NAMES && dx == 1)
5186   {
5187     SetGameStatus(GAME_MODE_PSEUDO_TYPENAMES);
5188
5189     DrawTypeName();
5190
5191     return;
5192   }
5193   else if (dx == 1)
5194   {
5195     TreeInfo *node_first, *node_cursor;
5196     int entry_pos = ti->cl_first + y;
5197
5198     node_first = getTreeInfoFirstGroupEntry(ti);
5199     node_cursor = getTreeInfoFromPos(node_first, entry_pos);
5200
5201     if (node_cursor->node_group)
5202     {
5203       FadeSetEnterMenu();
5204
5205       PlaySound(SND_MENU_ITEM_SELECTING);
5206
5207       node_cursor->cl_first = ti->cl_first;
5208       node_cursor->cl_cursor = ti->cl_cursor;
5209
5210       *ti_ptr = node_cursor->node_group;
5211       DrawChooseTree(ti_ptr);
5212
5213       return;
5214     }
5215   }
5216   else if ((dx == -1 || button == MB_MENU_CONTINUE) && ti->node_parent)
5217   {
5218     if (game_status != GAME_MODE_SCORES)
5219       FadeSetLeaveMenu();
5220
5221     PlaySound(SND_MENU_ITEM_SELECTING);
5222
5223     *ti_ptr = ti->node_parent;
5224     DrawChooseTree(ti_ptr);
5225
5226     return;
5227   }
5228
5229   if (!anyScrollbarGadgetActive() &&
5230       IN_VIS_MENU(x, y) &&
5231       mx < mx_right_border &&
5232       y >= 0 && y < num_page_entries)
5233   {
5234     if (button)
5235     {
5236       if (game_status == GAME_MODE_NAMES)
5237       {
5238         if (mx >= sx1_edit_name && mx <= sx2_edit_name)
5239           drawChooseTreeEdit(y, TRUE);
5240       }
5241
5242       if (y != ti->cl_cursor)
5243       {
5244         PlaySound(SND_MENU_ITEM_ACTIVATING);
5245
5246         drawChooseTreeCursorAndText(ti, FALSE);
5247
5248         ti->cl_cursor = y;
5249
5250         drawChooseTreeCursorAndText(ti, TRUE);
5251
5252         drawChooseTreeInfo(ti);
5253       }
5254       else if (dx < 0)
5255       {
5256         if (game_status == GAME_MODE_SETUP)
5257         {
5258           if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE ||
5259               setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
5260               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
5261               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
5262             execSetupGame();
5263           else if (setup_mode == SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE ||
5264                    setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64 ||
5265                    setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV ||
5266                    setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_ATARI ||
5267                    setup_mode == SETUP_MODE_CHOOSE_BD_COLOR_TYPE)
5268             execSetupEngines();
5269           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
5270                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
5271                    setup_mode == SETUP_MODE_CHOOSE_RENDERING ||
5272                    setup_mode == SETUP_MODE_CHOOSE_VSYNC)
5273             execSetupGraphics();
5274           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
5275                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
5276                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
5277             execSetupSound();
5278           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
5279                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
5280                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE ||
5281                    setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY ||
5282                    setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0 ||
5283                    setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0 ||
5284                    setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1 ||
5285                    setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
5286             execSetupTouch();
5287           else
5288             execSetupArtwork();
5289         }
5290       }
5291     }
5292     else
5293     {
5294       TreeInfo *node_first, *node_cursor;
5295       int entry_pos = ti->cl_first + y;
5296
5297       PlaySound(SND_MENU_ITEM_SELECTING);
5298
5299       node_first = getTreeInfoFirstGroupEntry(ti);
5300       node_cursor = getTreeInfoFromPos(node_first, entry_pos);
5301
5302       if (node_cursor->node_group)
5303       {
5304         FadeSetEnterMenu();
5305
5306         node_cursor->cl_first = ti->cl_first;
5307         node_cursor->cl_cursor = ti->cl_cursor;
5308
5309         *ti_ptr = node_cursor->node_group;
5310         DrawChooseTree(ti_ptr);
5311       }
5312       else if (node_cursor->parent_link)
5313       {
5314         if (game_status != GAME_MODE_SCORES)
5315           FadeSetLeaveMenu();
5316
5317         *ti_ptr = node_cursor->node_parent;
5318         DrawChooseTree(ti_ptr);
5319       }
5320       else
5321       {
5322         if (game_status != GAME_MODE_SCORES)
5323           FadeSetEnterMenu();
5324
5325         node_cursor->cl_first = ti->cl_first;
5326         node_cursor->cl_cursor = ti->cl_cursor;
5327
5328         *ti_ptr = node_cursor;
5329
5330         if (ti->type == TREE_TYPE_LEVEL_DIR)
5331         {
5332           LoadLevelSetup_SeriesInfo();
5333
5334           SaveLevelSetup_LastSeries();
5335           SaveLevelSetup_SeriesInfo();
5336           TapeErase();
5337         }
5338
5339         if (game_status == GAME_MODE_SETUP)
5340         {
5341           if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE ||
5342               setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
5343               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
5344               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
5345             execSetupGame();
5346           else if (setup_mode == SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE ||
5347                    setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64 ||
5348                    setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV ||
5349                    setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_ATARI ||
5350                    setup_mode == SETUP_MODE_CHOOSE_BD_COLOR_TYPE)
5351             execSetupEngines();
5352           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
5353                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
5354                    setup_mode == SETUP_MODE_CHOOSE_RENDERING ||
5355                    setup_mode == SETUP_MODE_CHOOSE_VSYNC)
5356             execSetupGraphics();
5357           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
5358                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
5359                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
5360             execSetupSound();
5361           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
5362                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
5363                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE ||
5364                    setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY ||
5365                    setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0 ||
5366                    setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0 ||
5367                    setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1 ||
5368                    setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
5369             execSetupTouch();
5370           else
5371             execSetupArtwork();
5372         }
5373         else
5374         {
5375           if (game_status == GAME_MODE_LEVELNR)
5376           {
5377             int new_level_nr = atoi(level_number_current->identifier);
5378
5379             HandleMainMenu_SelectLevel(0, 0, new_level_nr);
5380           }
5381           else if (game_status == GAME_MODE_LEVELS)
5382           {
5383             // store level set if chosen from "last played level set" menu
5384             StoreLastPlayedLevels(leveldir_current);
5385
5386             // store if level set chosen from "last played level set" menu
5387             SaveLevelSetup_LastSeries();
5388           }
5389           else if (game_status == GAME_MODE_NAMES)
5390           {
5391             if (mx >= sx1_edit_name && mx <= sx2_edit_name)
5392             {
5393               SetGameStatus(GAME_MODE_PSEUDO_TYPENAMES);
5394
5395               DrawTypeName();
5396
5397               return;
5398             }
5399
5400             // change active user to selected user
5401             user.nr = entry_pos;
5402
5403             // save number of new active user
5404             SaveUserSetup();
5405
5406             // load setup of new active user
5407             LoadSetup();
5408
5409             // load last level set of new active user
5410             LoadLevelSetup_LastSeries();
5411             LoadLevelSetup_SeriesInfo();
5412
5413             // update list of last played level sets
5414             UpdateLastPlayedLevels_TreeInfo();
5415
5416             TapeErase();
5417
5418             ToggleFullscreenIfNeeded();
5419             ChangeWindowScalingIfNeeded();
5420
5421             ChangeCurrentArtworkIfNeeded(ARTWORK_TYPE_GRAPHICS);
5422             ChangeCurrentArtworkIfNeeded(ARTWORK_TYPE_SOUNDS);
5423             ChangeCurrentArtworkIfNeeded(ARTWORK_TYPE_MUSIC);
5424           }
5425           else if (game_status == GAME_MODE_SCORES)
5426           {
5427             if (scores.continue_playing && scores.continue_on_return)
5428             {
5429               StartPlayingFromHallOfFame();
5430
5431               return;
5432             }
5433             else if (!scores.continue_on_return)
5434             {
5435               SetGameStatus(GAME_MODE_SCOREINFO);
5436
5437               DrawScoreInfo(node_cursor->pos);
5438
5439               return;
5440             }
5441           }
5442
5443           SetGameStatus(GAME_MODE_MAIN);
5444
5445           DrawMainMenu();
5446         }
5447       }
5448     }
5449   }
5450
5451   if (game_status == GAME_MODE_SCORES)
5452     PlayMenuSoundIfLoop();
5453 }
5454
5455 void DrawChoosePlayerName(void)
5456 {
5457   int i;
5458
5459   if (player_name != NULL)
5460   {
5461     freeTreeInfo(player_name);
5462
5463     player_name = NULL;
5464   }
5465
5466   for (i = 0; i < MAX_PLAYER_NAMES; i++)
5467   {
5468     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_PLAYER_NAME);
5469     char identifier[32], name[MAX_PLAYER_NAME_LEN + 1];
5470     int value = i;
5471
5472     ti->node_top = &player_name;
5473     ti->sort_priority = 10000 + value;
5474     ti->color = getPlayerNameColor(global.user_names[i]);
5475
5476     snprintf(identifier, sizeof(identifier), "%d", value);
5477     snprintf(name, sizeof(name), "%s", global.user_names[i]);
5478
5479     setString(&ti->identifier, identifier);
5480     setString(&ti->name, name);
5481     setString(&ti->name_sorting, name);
5482
5483     pushTreeInfo(&player_name, ti);
5484   }
5485
5486   // sort player entries by player number
5487   sortTreeInfo(&player_name);
5488
5489   // set current player entry to selected player entry
5490   player_name_current =
5491     getTreeInfoFromIdentifier(player_name, i_to_a(user.nr));
5492
5493   // if that fails, set current player name to first available name
5494   if (player_name_current == NULL)
5495     player_name_current = player_name;
5496
5497   // set text size for main name input (also used on name selection screen)
5498   InitializeMainControls();
5499
5500   DrawChooseTree(&player_name_current);
5501 }
5502
5503 void HandleChoosePlayerName(int mx, int my, int dx, int dy, int button)
5504 {
5505   HandleChooseTree(mx, my, dx, dy, button, &player_name_current);
5506 }
5507
5508 void DrawChooseLevelSet(void)
5509 {
5510   DrawChooseTree(&leveldir_current);
5511 }
5512
5513 void HandleChooseLevelSet(int mx, int my, int dx, int dy, int button)
5514 {
5515   HandleChooseTree(mx, my, dx, dy, button, &leveldir_current);
5516 }
5517
5518 void DrawChooseLevelNr(void)
5519 {
5520   int i;
5521
5522   if (level_number != NULL)
5523   {
5524     freeTreeInfo(level_number);
5525
5526     level_number = NULL;
5527   }
5528
5529   for (i = leveldir_current->first_level; i <= leveldir_current->last_level;i++)
5530   {
5531     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_LEVEL_NR);
5532     char identifier[32], name[64];
5533     int value = i;
5534
5535     // temporarily load level info to get level name
5536     LoadLevelInfoOnly(i);
5537
5538     ti->node_top = &level_number;
5539     ti->sort_priority = 10000 + value;
5540     ti->color = (level.no_level_file ? FC_BLUE :
5541                  LevelStats_getSolved(i) ? FC_GREEN :
5542                  LevelStats_getPlayed(i) ? FC_YELLOW : FC_RED);
5543
5544     snprintf(identifier, sizeof(identifier), "%d", value);
5545     snprintf(name, sizeof(name), "%03d: %s", value,
5546              (level.no_level_file ? "(no file)" : level.name));
5547
5548     setString(&ti->identifier, identifier);
5549     setString(&ti->name, name);
5550     setString(&ti->name_sorting, name);
5551
5552     pushTreeInfo(&level_number, ti);
5553   }
5554
5555   // sort level number values to start with lowest level number
5556   sortTreeInfo(&level_number);
5557
5558   // set current level number to current level number
5559   level_number_current =
5560     getTreeInfoFromIdentifier(level_number, i_to_a(level_nr));
5561
5562   // if that also fails, set current level number to first available level
5563   if (level_number_current == NULL)
5564     level_number_current = level_number;
5565
5566   DrawChooseTree(&level_number_current);
5567 }
5568
5569 void HandleChooseLevelNr(int mx, int my, int dx, int dy, int button)
5570 {
5571   HandleChooseTree(mx, my, dx, dy, button, &level_number_current);
5572 }
5573
5574 static void DrawHallOfFame_setScoreEntries(void)
5575 {
5576   int max_empty_entries = 10;   // at least show "top ten" list, if empty
5577   int max_visible_entries = NUM_MENU_ENTRIES_ON_SCREEN - 1;   // w/o back link
5578   int min_score_entries = MIN(max_empty_entries, max_visible_entries);
5579   int score_pos = (scores.last_added >= 0 ? scores.last_added : 0);
5580   int i;
5581
5582   if (score_entries != NULL)
5583   {
5584     freeTreeInfo(score_entries);
5585
5586     score_entries = NULL;
5587   }
5588
5589   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
5590   {
5591     // do not add empty score entries if off-screen
5592     if (scores.entry[i].score == 0 &&
5593         scores.entry[i].time == 0 &&
5594         i >= min_score_entries)
5595       break;
5596
5597     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_SCORE_ENTRY);
5598     char identifier[32], name[64];
5599     int value = i;
5600
5601     ti->node_top = &score_entries;
5602     ti->sort_priority = 10000 + value;
5603     ti->color = FC_YELLOW;
5604     ti->pos = i;
5605
5606     snprintf(identifier, sizeof(identifier), "%d", value);
5607     snprintf(name, sizeof(name), "%03d.", value + 1);
5608
5609     setString(&ti->identifier, identifier);
5610     setString(&ti->name, name);
5611     setString(&ti->name_sorting, name);
5612
5613     pushTreeInfo(&score_entries, ti);
5614   }
5615
5616   // sort score entries to start with highest score entry
5617   sortTreeInfo(&score_entries);
5618
5619   // add top tree node to create back link to main menu
5620   score_entries = addTopTreeInfoNode(score_entries);
5621
5622   // set current score entry to last added or highest score entry
5623   score_entry_current =
5624     getTreeInfoFromIdentifier(score_entries, i_to_a(score_pos));
5625
5626   // if that fails, set current score entry to first valid score entry
5627   if (score_entry_current == NULL)
5628     score_entry_current = getFirstValidTreeInfoEntry(score_entries);
5629
5630   if (score_entries != NULL && scores.continue_playing)
5631     setString(&score_entries->node_group->name, BACKLINK_TEXT_NEXT);
5632 }
5633
5634 void DrawHallOfFame(int nr)
5635 {
5636   scores.last_level_nr = nr;
5637
5638   // (this is needed when called from GameEnd() after winning a game)
5639   KeyboardAutoRepeatOn();
5640
5641   // (this is needed when called from GameEnd() after winning a game)
5642   SetDrawDeactivationMask(REDRAW_NONE);
5643   SetDrawBackgroundMask(REDRAW_FIELD);
5644
5645   LoadLocalAndServerScore(scores.last_level_nr, TRUE);
5646
5647   DrawHallOfFame_setScoreEntries();
5648
5649   if (scores.last_added >= 0)
5650     SetAnimStatus(GAME_MODE_PSEUDO_SCORESNEW);
5651
5652   FadeSetEnterScreen();
5653
5654   DrawChooseTree(&score_entry_current);
5655 }
5656
5657 static char *getHallOfFameRankText(int nr, int size)
5658 {
5659   static char rank_text[10];
5660   boolean forced = (scores.force_last_added && nr == scores.last_added);
5661   char *rank_text_raw = (forced ? "???" : int2str(nr + 1, size));
5662
5663   sprintf(rank_text, "%s%s", rank_text_raw, (size > 0 || !forced ? "." : ""));
5664
5665   return rank_text;
5666 }
5667
5668 static char *getHallOfFameTimeText(int nr)
5669 {
5670   static char score_text[10];
5671   int time_seconds = scores.entry[nr].time / FRAMES_PER_SECOND;
5672   int mm = (time_seconds / 60) % 60;
5673   int ss = (time_seconds % 60);
5674
5675   sprintf(score_text, "%02d:%02d", mm, ss);     // show playing time
5676
5677   return score_text;
5678 }
5679
5680 static char *getHallOfFameScoreText(int nr, int size)
5681 {
5682   if (!level.rate_time_over_score)
5683     return int2str(scores.entry[nr].score, size);       // show normal score
5684   else if (level.use_step_counter)
5685     return int2str(scores.entry[nr].time, size);        // show number of steps
5686   else
5687     return getHallOfFameTimeText(nr);                   // show playing time
5688 }
5689
5690 static char *getHallOfFameTapeDateText(struct ScoreEntry *entry)
5691 {
5692   static char tape_date[MAX_ISO_DATE_LEN + 1];
5693   int i, j;
5694
5695   if (!strEqual(entry->tape_date, UNKNOWN_NAME) ||
5696       strEqual(entry->tape_basename, UNDEFINED_FILENAME))
5697     return entry->tape_date;
5698
5699   for (i = 0, j = 0; i < 8; i++, j++)
5700   {
5701     tape_date[j] = entry->tape_basename[i];
5702
5703     if (i == 3 || i == 5)
5704       tape_date[++j] = '-';
5705   }
5706
5707   tape_date[MAX_ISO_DATE_LEN] = '\0';
5708
5709   return tape_date;
5710 }
5711
5712 static void HandleHallOfFame_SelectLevel(int step, int direction)
5713 {
5714   int old_level_nr = scores.last_level_nr;
5715   int new_level_nr = old_level_nr + step * direction;
5716
5717   if (new_level_nr < leveldir_current->first_level)
5718     new_level_nr = leveldir_current->first_level;
5719   if (new_level_nr > leveldir_current->last_level)
5720     new_level_nr = leveldir_current->last_level;
5721
5722   if (setup.handicap && new_level_nr > leveldir_current->handicap_level)
5723     new_level_nr = leveldir_current->handicap_level;
5724
5725   if (new_level_nr != old_level_nr)
5726   {
5727     PlaySound(SND_MENU_ITEM_SELECTING);
5728
5729     scores.last_level_nr = level_nr = new_level_nr;
5730     scores.last_entry_nr = 0;
5731
5732     LoadLevel(level_nr);
5733     LoadLocalAndServerScore(level_nr, TRUE);
5734
5735     DrawHallOfFame_setScoreEntries();
5736
5737     if (game_status == GAME_MODE_SCORES)
5738     {
5739       // force remapping optional gadgets (especially scroll bar)
5740       UnmapScreenTreeGadgets();
5741
5742       // redraw complete high score screen, as sub-title has changed
5743       ClearField();
5744
5745       // redraw level selection buttons (which have just been erased)
5746       RedrawScreenMenuGadgets(SCREEN_MASK_SCORES);
5747
5748       HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, &score_entry_current);
5749     }
5750     else
5751     {
5752       DrawScoreInfo_Content(scores.last_entry_nr);
5753     }
5754
5755     SaveLevelSetup_SeriesInfo();
5756   }
5757 }
5758
5759 void HandleHallOfFame(int mx, int my, int dx, int dy, int button)
5760 {
5761   HandleChooseTree(mx, my, dx, dy, button, &score_entry_current);
5762 }
5763
5764 static void DrawScoreInfo_Content(int entry_nr)
5765 {
5766   struct ScoreEntry *entry = &scores.entry[entry_nr];
5767   char *pos_text = getHallOfFameRankText(entry_nr, 0);
5768   char *tape_date = getHallOfFameTapeDateText(entry);
5769   int font_head = MENU_INFO_FONT_HEAD;
5770   int font_text = MENU_INFO_FONT_TEXT;
5771   int font_foot = MENU_INFO_FONT_FOOT;
5772   int spacing_para = menu.paragraph_spacing[GAME_MODE_SCOREINFO];
5773   int spacing_line = menu.line_spacing[GAME_MODE_SCOREINFO];
5774   int spacing_left = menu.left_spacing[GAME_MODE_SCOREINFO];
5775   int spacing_top  = menu.top_spacing[GAME_MODE_SCOREINFO];
5776   int xstep = getFontWidth(font_text);
5777   int ystep_para = getMenuTextStep(spacing_para,  font_text);
5778   int ystep_line = getMenuTextStep(spacing_line,  font_text);
5779   int xstart  = mSX - SX + spacing_left;
5780   int ystart  = mSY - SY + spacing_top + getHeadlineSpacing();
5781   int ybottom = mSY - SY + SYSIZE - menu.bottom_spacing[GAME_MODE_SCOREINFO];
5782   int xstart1 = xstart + xstep;
5783   int xstart2 = xstart + xstep * 12;
5784   int select_x = SX + xstart1;
5785   int select_y1, select_y2;
5786   int play_x, play_y;
5787   int play_height = screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE]->height;
5788   boolean play_visible = !strEqual(tape_date, UNKNOWN_NAME);
5789   int font_width = getFontWidth(font_text);
5790   int font_height = getFontHeight(font_text);
5791   int tape_date_width = getTextWidth(tape_date, font_text);
5792   int pad_left = xstart2;
5793   int pad_right = menu.right_spacing[GAME_MODE_SCOREINFO];
5794   int max_chars_per_line = (SXSIZE - pad_left - pad_right) / font_width;
5795   int max_lines_per_text = 5;
5796   int lines;
5797
5798   ClearField();
5799
5800   // redraw level selection buttons (which have just been erased)
5801   RedrawScreenMenuGadgets(SCREEN_MASK_SCORES);
5802
5803   drawChooseTreeHead(score_entries);
5804   drawChooseTreeInfo(score_entries);
5805
5806   DrawTextF(xstart1, ystart, font_head, "Level Set");
5807   lines = DrawTextBufferS(xstart2, ystart, leveldir_current->name, font_text,
5808                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5809                           TRUE, FALSE, FALSE);
5810   ystart += ystep_line + (lines > 0 ? lines - 1 : 0) * font_height;
5811
5812   DrawTextF(xstart1, ystart, font_head, "Level");
5813   lines = DrawTextBufferS(xstart2, ystart, level.name, font_text,
5814                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5815                           TRUE, FALSE, FALSE);
5816   ystart += ystep_para + (lines > 0 ? lines - 1 : 0) * font_height;
5817
5818   select_y1 = SY + ystart;
5819   ystart += graphic_info[IMG_MENU_BUTTON_PREV_SCORE].height;
5820
5821   DrawTextF(xstart1, ystart, font_head, "Rank");
5822   DrawTextF(xstart2, ystart, font_text, pos_text);
5823   ystart += ystep_line;
5824
5825   DrawTextF(xstart1, ystart, font_head, "Player");
5826   DrawTextF(xstart2, ystart, font_text, entry->name);
5827   ystart += ystep_line;
5828
5829   if (level.use_step_counter)
5830   {
5831     DrawTextF(xstart1, ystart, font_head, "Steps");
5832     DrawTextF(xstart2, ystart, font_text, int2str(entry->time, 5));
5833     ystart += ystep_line;
5834   }
5835   else
5836   {
5837     DrawTextF(xstart1, ystart, font_head, "Time");
5838     DrawTextF(xstart2, ystart, font_text, getHallOfFameTimeText(entry_nr));
5839     ystart += ystep_line;
5840   }
5841
5842   if (!level.rate_time_over_score || entry->score > 0)
5843   {
5844     DrawTextF(xstart1, ystart, font_head, "Score");
5845     DrawTextF(xstart2, ystart, font_text, int2str(entry->score, 5));
5846     ystart += ystep_line;
5847   }
5848
5849   ystart += ystep_line;
5850
5851   play_x = SX + xstart2 + tape_date_width + font_width;
5852   play_y = SY + ystart + (font_height - play_height) / 2;
5853
5854   DrawTextF(xstart1, ystart, font_head, "Tape Date");
5855   DrawTextF(xstart2, ystart, font_text, tape_date);
5856   ystart += ystep_line;
5857
5858   DrawTextF(xstart1, ystart, font_head, "Platform");
5859   DrawTextF(xstart2, ystart, font_text, entry->platform);
5860   ystart += ystep_line;
5861
5862   DrawTextF(xstart1, ystart, font_head, "Version");
5863   DrawTextF(xstart2, ystart, font_text, entry->version);
5864   ystart += ystep_line;
5865
5866   DrawTextF(xstart1, ystart, font_head, "Country");
5867   lines = DrawTextBufferS(xstart2, ystart, entry->country_name, font_text,
5868                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5869                           TRUE, FALSE, FALSE);
5870   ystart += ystep_line;
5871
5872   select_y2 = SY + ystart;
5873
5874   DrawTextSCentered(ybottom, font_foot, "Press any key or button to go back");
5875
5876   AdjustScoreInfoButtons_SelectScore(select_x, select_y1, select_y2);
5877   AdjustScoreInfoButtons_PlayTape(play_x, play_y, play_visible);
5878 }
5879
5880 static void DrawScoreInfo(int entry_nr)
5881 {
5882   scores.last_entry_nr = entry_nr;
5883   score_info_tape_play = FALSE;
5884
5885   UnmapAllGadgets();
5886
5887   FreeScreenGadgets();
5888   CreateScreenGadgets();
5889
5890   FadeOut(REDRAW_FIELD);
5891
5892   // needed if different viewport properties defined after playing score tape
5893   ChangeViewportPropertiesIfNeeded();
5894
5895   // set this after "ChangeViewportPropertiesIfNeeded()" (which may reset it)
5896   SetDrawDeactivationMask(REDRAW_NONE);
5897   SetDrawBackgroundMask(REDRAW_FIELD);
5898
5899   // needed if different background image defined after playing score tape
5900   SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
5901   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_SCOREINFO);
5902
5903   // special compatibility handling for "Snake Bite" graphics set
5904   if (strPrefix(leveldir_current->identifier, "snake_bite"))
5905     ClearRectangle(gfx.background_bitmap, gfx.real_sx, gfx.real_sy + 64,
5906                    gfx.full_sxsize, gfx.full_sysize - 64);
5907
5908   DrawScoreInfo_Content(entry_nr);
5909
5910   // map gadgets for score info screen
5911   MapScreenMenuGadgets(SCREEN_MASK_SCORES_INFO);
5912
5913   FadeIn(REDRAW_FIELD);
5914 }
5915
5916 static void HandleScoreInfo_SelectScore(int step, int direction)
5917 {
5918   int old_entry_nr = scores.last_entry_nr;
5919   int new_entry_nr = old_entry_nr + step * direction;
5920   int num_nodes = numTreeInfoInGroup(score_entry_current);
5921   int num_entries = num_nodes - 1;      // score nodes only, without back link
5922
5923   if (new_entry_nr < 0)
5924     new_entry_nr = 0;
5925   if (new_entry_nr > num_entries - 1)
5926     new_entry_nr = num_entries - 1;
5927
5928   if (new_entry_nr != old_entry_nr)
5929   {
5930     scores.last_entry_nr = new_entry_nr;
5931
5932     DrawScoreInfo_Content(new_entry_nr);
5933   }
5934 }
5935
5936 static void HandleScoreInfo_PlayTape(void)
5937 {
5938   if (!PlayScoreTape(scores.last_entry_nr))
5939   {
5940     DrawScoreInfo_Content(scores.last_entry_nr);
5941
5942     FadeIn(REDRAW_FIELD);
5943   }
5944 }
5945
5946 void HandleScoreInfo(int mx, int my, int dx, int dy, int button)
5947 {
5948   boolean button_action = (button == MB_MENU_LEAVE || button == MB_MENU_CHOICE);
5949   boolean button_is_valid = (mx >= 0 && my >= 0);
5950   boolean button_screen_clicked = (button_action && button_is_valid);
5951
5952   if (server_scores.updated)
5953   {
5954     // reload scores, using updated server score cache file
5955     LoadLocalAndServerScore(scores.last_level_nr, FALSE);
5956
5957     server_scores.updated = FALSE;
5958
5959     DrawHallOfFame_setScoreEntries();
5960
5961     DrawScoreInfo_Content(scores.last_entry_nr);
5962   }
5963
5964   if (button_screen_clicked)
5965   {
5966     PlaySound(SND_MENU_ITEM_SELECTING);
5967
5968     SetGameStatus(GAME_MODE_SCORES);
5969
5970     DrawHallOfFame(scores.last_level_nr);
5971   }
5972   else if (dx)
5973   {
5974     HandleHallOfFame_SelectLevel(1, SIGN(dx) * (ABS(dx) > 1 ? 10 : 1));
5975   }
5976   else if (dy)
5977   {
5978     HandleScoreInfo_SelectScore(1, SIGN(dy) * (ABS(dy) > 1 ? 10 : 1));
5979   }
5980 }
5981
5982
5983 // ============================================================================
5984 // setup screen functions
5985 // ============================================================================
5986
5987 static struct TokenInfo *setup_info;
5988 static int num_setup_info;      // number of setup entries shown on screen
5989 static int max_setup_info;      // total number of setup entries in list
5990
5991 static char *window_size_text;
5992 static char *scaling_type_text;
5993 static char *rendering_mode_text;
5994 static char *vsync_mode_text;
5995 static char *scroll_delay_text;
5996 static char *snapshot_mode_text;
5997 static char *game_engine_type_text;
5998 static char *bd_palette_c64_text;
5999 static char *bd_palette_c64dtv_text;
6000 static char *bd_palette_atari_text;
6001 static char *bd_color_type_text;
6002 static char *game_speed_text;
6003 static char *scores_type_text;
6004 static char *network_server_text;
6005 static char *graphics_set_name;
6006 static char *sounds_set_name;
6007 static char *music_set_name;
6008 static char *volume_simple_text;
6009 static char *volume_loops_text;
6010 static char *volume_music_text;
6011 static char *touch_controls_text;
6012 static char *move_distance_text;
6013 static char *drop_distance_text;
6014 static char *transparency_text;
6015 static char *grid_size_text[2][2];
6016
6017 static void execSetupMain(void)
6018 {
6019   setup_mode = SETUP_MODE_MAIN;
6020
6021   DrawSetupScreen();
6022 }
6023
6024 static void execSetupGame_setScoresType(void)
6025 {
6026   if (scores_types == NULL)
6027   {
6028     int i;
6029
6030     for (i = 0; scores_types_list[i].value != NULL; i++)
6031     {
6032       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6033       char identifier[32], name[32];
6034       char *value = scores_types_list[i].value;
6035       char *text = scores_types_list[i].text;
6036
6037       ti->node_top = &scores_types;
6038       ti->sort_priority = i;
6039
6040       sprintf(identifier, "%s", value);
6041       sprintf(name, "%s", text);
6042
6043       setString(&ti->identifier, identifier);
6044       setString(&ti->name, name);
6045       setString(&ti->name_sorting, name);
6046       setString(&ti->infotext, STR_SETUP_CHOOSE_SCORES_TYPE);
6047
6048       pushTreeInfo(&scores_types, ti);
6049     }
6050
6051     // sort scores type values to start with lowest scores type value
6052     sortTreeInfo(&scores_types);
6053
6054     // set current scores type value to configured scores type value
6055     scores_type_current =
6056       getTreeInfoFromIdentifier(scores_types, setup.scores_in_highscore_list);
6057
6058     // if that fails, set current scores type to reliable default value
6059     if (scores_type_current == NULL)
6060       scores_type_current =
6061         getTreeInfoFromIdentifier(scores_types, STR_SCORES_TYPE_DEFAULT);
6062
6063     // if that also fails, set current scores type to first available value
6064     if (scores_type_current == NULL)
6065       scores_type_current = scores_types;
6066   }
6067
6068   setup.scores_in_highscore_list = scores_type_current->identifier;
6069
6070   // needed for displaying scores type text instead of identifier
6071   scores_type_text = scores_type_current->name;
6072 }
6073
6074 static void execSetupGame_setGameSpeeds(boolean update_value)
6075 {
6076   if (setup.game_speed_extended)
6077   {
6078     game_speeds_list = game_speeds_list_extended;
6079     game_speeds      = game_speeds_extended;
6080   }
6081   else
6082   {
6083     game_speeds_list = game_speeds_list_normal;
6084     game_speeds      = game_speeds_normal;
6085   }
6086
6087   if (game_speeds == NULL)
6088   {
6089     int i;
6090
6091     for (i = 0; game_speeds_list[i].value != -1; i++)
6092     {
6093       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6094       char identifier[32], name[32];
6095       int value = game_speeds_list[i].value;
6096       char *text = game_speeds_list[i].text;
6097
6098       ti->node_top = &game_speeds;
6099       ti->sort_priority = 10000 - value;
6100
6101       sprintf(identifier, "%d", value);
6102       sprintf(name, "%s", text);
6103
6104       setString(&ti->identifier, identifier);
6105       setString(&ti->name, name);
6106       setString(&ti->name_sorting, name);
6107       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_SPEED);
6108
6109       pushTreeInfo(&game_speeds, ti);
6110     }
6111
6112     // sort game speed values to start with slowest game speed
6113     sortTreeInfo(&game_speeds);
6114
6115     update_value = TRUE;
6116   }
6117
6118   if (update_value)
6119   {
6120     // set current game speed to configured game speed value
6121     game_speed_current =
6122       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
6123
6124     // if that fails, set current game speed to reliable default value
6125     if (game_speed_current == NULL)
6126       game_speed_current =
6127         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
6128
6129     // if that also fails, set current game speed to first available speed
6130     if (game_speed_current == NULL)
6131       game_speed_current = game_speeds;
6132
6133     if (setup.game_speed_extended)
6134       game_speeds_extended = game_speeds;
6135     else
6136       game_speeds_normal = game_speeds;
6137   }
6138
6139   setup.game_frame_delay = atoi(game_speed_current->identifier);
6140
6141   // needed for displaying game speed text instead of identifier
6142   game_speed_text = game_speed_current->name;
6143 }
6144
6145 static void execSetupGame_setScrollDelays(void)
6146 {
6147   if (scroll_delays == NULL)
6148   {
6149     int i;
6150
6151     for (i = 0; scroll_delays_list[i].value != -1; i++)
6152     {
6153       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6154       char identifier[32], name[32];
6155       int value = scroll_delays_list[i].value;
6156       char *text = scroll_delays_list[i].text;
6157
6158       ti->node_top = &scroll_delays;
6159       ti->sort_priority = value;
6160
6161       sprintf(identifier, "%d", value);
6162       sprintf(name, "%s", text);
6163
6164       setString(&ti->identifier, identifier);
6165       setString(&ti->name, name);
6166       setString(&ti->name_sorting, name);
6167       setString(&ti->infotext, STR_SETUP_CHOOSE_SCROLL_DELAY);
6168
6169       pushTreeInfo(&scroll_delays, ti);
6170     }
6171
6172     // sort scroll delay values to start with lowest scroll delay value
6173     sortTreeInfo(&scroll_delays);
6174
6175     // set current scroll delay value to configured scroll delay value
6176     scroll_delay_current =
6177       getTreeInfoFromIdentifier(scroll_delays, i_to_a(setup.scroll_delay_value));
6178
6179     // if that fails, set current scroll delay to reliable default value
6180     if (scroll_delay_current == NULL)
6181       scroll_delay_current =
6182         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
6183
6184     // if that also fails, set current scroll delay to first available value
6185     if (scroll_delay_current == NULL)
6186       scroll_delay_current = scroll_delays;
6187   }
6188
6189   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
6190
6191   // needed for displaying scroll delay text instead of identifier
6192   scroll_delay_text = scroll_delay_current->name;
6193 }
6194
6195 static void execSetupGame_setSnapshotModes(void)
6196 {
6197   if (snapshot_modes == NULL)
6198   {
6199     int i;
6200
6201     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
6202     {
6203       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6204       char identifier[32], name[32];
6205       char *value = snapshot_modes_list[i].value;
6206       char *text = snapshot_modes_list[i].text;
6207
6208       ti->node_top = &snapshot_modes;
6209       ti->sort_priority = i;
6210
6211       sprintf(identifier, "%s", value);
6212       sprintf(name, "%s", text);
6213
6214       setString(&ti->identifier, identifier);
6215       setString(&ti->name, name);
6216       setString(&ti->name_sorting, name);
6217       setString(&ti->infotext, STR_SETUP_CHOOSE_SNAPSHOT_MODE);
6218
6219       pushTreeInfo(&snapshot_modes, ti);
6220     }
6221
6222     // sort snapshot mode values to start with lowest snapshot mode value
6223     sortTreeInfo(&snapshot_modes);
6224
6225     // set current snapshot mode value to configured snapshot mode value
6226     snapshot_mode_current =
6227       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
6228
6229     // if that fails, set current snapshot mode to reliable default value
6230     if (snapshot_mode_current == NULL)
6231       snapshot_mode_current =
6232         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
6233
6234     // if that also fails, set current snapshot mode to first available value
6235     if (snapshot_mode_current == NULL)
6236       snapshot_mode_current = snapshot_modes;
6237   }
6238
6239   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
6240
6241   // needed for displaying snapshot mode text instead of identifier
6242   snapshot_mode_text = snapshot_mode_current->name;
6243 }
6244
6245 static void execSetupGame_setNetworkServerText(void)
6246 {
6247   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
6248   {
6249     strcpy(network_server_hostname, STR_NETWORK_AUTO_DETECT_SETUP);
6250   }
6251   else
6252   {
6253     strncpy(network_server_hostname, setup.network_server_hostname,
6254             MAX_SETUP_TEXT_INPUT_LEN);
6255     network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN] = '\0';
6256   }
6257
6258   // needed for displaying network server text instead of identifier
6259   network_server_text = network_server_hostname;
6260 }
6261
6262 static void execSetupGame(void)
6263 {
6264   boolean check_vsync_mode = (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED);
6265
6266   execSetupGame_setGameSpeeds(FALSE);
6267   execSetupGame_setScoresType();
6268   execSetupGame_setScrollDelays();
6269   execSetupGame_setSnapshotModes();
6270
6271   execSetupGame_setNetworkServerText();
6272
6273   if (!setup.provide_uploading_tapes)
6274     setHideSetupEntry(execOfferUploadTapes);
6275
6276   setup_mode = SETUP_MODE_GAME;
6277
6278   DrawSetupScreen();
6279
6280   // check if vsync needs to be disabled for this game speed to work
6281   if (check_vsync_mode)
6282     DisableVsyncIfNeeded();
6283 }
6284
6285 static void execSetupChooseScoresType(void)
6286 {
6287   setup_mode = SETUP_MODE_CHOOSE_SCORES_TYPE;
6288
6289   DrawSetupScreen();
6290 }
6291
6292 static void execSetupChooseGameSpeed(void)
6293 {
6294   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
6295
6296   DrawSetupScreen();
6297 }
6298
6299 static void execSetupChooseScrollDelay(void)
6300 {
6301   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
6302
6303   DrawSetupScreen();
6304 }
6305
6306 static void execSetupChooseSnapshotMode(void)
6307 {
6308   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
6309
6310   DrawSetupScreen();
6311 }
6312
6313 static void execSetupEngines_setGameEngineType(void)
6314 {
6315   if (game_engine_types == NULL)
6316   {
6317     int i;
6318
6319     for (i = 0; game_engine_types_list[i].value != -1; i++)
6320     {
6321       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6322       char identifier[32], name[32];
6323       int value = game_engine_types_list[i].value;
6324       char *text = game_engine_types_list[i].text;
6325
6326       ti->node_top = &game_engine_types;
6327       ti->sort_priority = value;
6328
6329       sprintf(identifier, "%d", value);
6330       sprintf(name, "%s", text);
6331
6332       setString(&ti->identifier, identifier);
6333       setString(&ti->name, name);
6334       setString(&ti->name_sorting, name);
6335       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_ENGINE_TYPE);
6336
6337       pushTreeInfo(&game_engine_types, ti);
6338     }
6339
6340     // sort game engine type values to start with lowest game engine type value
6341     sortTreeInfo(&game_engine_types);
6342
6343     // set current game engine type value to configured game engine type value
6344     game_engine_type_current =
6345       getTreeInfoFromIdentifier(game_engine_types, i_to_a(setup.default_game_engine_type));
6346
6347     // if that fails, set current game engine type to reliable default value
6348     if (game_engine_type_current == NULL)
6349       game_engine_type_current =
6350         getTreeInfoFromIdentifier(game_engine_types, i_to_a(GAME_ENGINE_TYPE_RND));
6351
6352     // if that also fails, set current game engine type to first available value
6353     if (game_engine_type_current == NULL)
6354       game_engine_type_current = game_engine_types;
6355   }
6356
6357   setup.default_game_engine_type = atoi(game_engine_type_current->identifier);
6358
6359   // needed for displaying game engine type text instead of identifier
6360   game_engine_type_text = game_engine_type_current->name;
6361 }
6362
6363 static void execSetupEngines_setPalettesC64(void)
6364 {
6365   if (bd_palettes_c64 == NULL)
6366   {
6367     int i;
6368
6369     for (i = 0; bd_palettes_c64_list[i].value != -1; i++)
6370     {
6371       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6372       char identifier[32], name[32];
6373       int value = bd_palettes_c64_list[i].value;
6374       char *text = bd_palettes_c64_list[i].text;
6375
6376       ti->node_top = &bd_palettes_c64;
6377       ti->sort_priority = value;
6378
6379       sprintf(identifier, "%d", value);
6380       sprintf(name, "%s", text);
6381
6382       setString(&ti->identifier, identifier);
6383       setString(&ti->name, name);
6384       setString(&ti->name_sorting, name);
6385       setString(&ti->infotext, STR_SETUP_CHOOSE_BD_PALETTE_C64);
6386
6387       pushTreeInfo(&bd_palettes_c64, ti);
6388     }
6389
6390     // sort palette values to start with lowest palette value
6391     sortTreeInfo(&bd_palettes_c64);
6392
6393     // set current palette value to configured palette value
6394     bd_palette_c64_current =
6395       getTreeInfoFromIdentifier(bd_palettes_c64, i_to_a(setup.bd_palette_c64));
6396
6397     // if that fails, set current palette to reliable default value
6398     if (bd_palette_c64_current == NULL)
6399       bd_palette_c64_current =
6400         getTreeInfoFromIdentifier(bd_palettes_c64, i_to_a(GD_DEFAULT_PALETTE_C64));
6401
6402     // if that also fails, set current palette to first available value
6403     if (bd_palette_c64_current == NULL)
6404       bd_palette_c64_current = bd_palettes_c64;
6405   }
6406
6407   setup.bd_palette_c64 = atoi(bd_palette_c64_current->identifier);
6408
6409   // needed for displaying palette text instead of identifier
6410   bd_palette_c64_text = bd_palette_c64_current->name;
6411 }
6412
6413 static void execSetupEngines_setPalettesC64DTV(void)
6414 {
6415   if (bd_palettes_c64dtv == NULL)
6416   {
6417     int i;
6418
6419     for (i = 0; bd_palettes_c64dtv_list[i].value != -1; i++)
6420     {
6421       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6422       char identifier[32], name[32];
6423       int value = bd_palettes_c64dtv_list[i].value;
6424       char *text = bd_palettes_c64dtv_list[i].text;
6425
6426       ti->node_top = &bd_palettes_c64dtv;
6427       ti->sort_priority = value;
6428
6429       sprintf(identifier, "%d", value);
6430       sprintf(name, "%s", text);
6431
6432       setString(&ti->identifier, identifier);
6433       setString(&ti->name, name);
6434       setString(&ti->name_sorting, name);
6435       setString(&ti->infotext, STR_SETUP_CHOOSE_BD_PALETTE_C64DTV);
6436
6437       pushTreeInfo(&bd_palettes_c64dtv, ti);
6438     }
6439
6440     // sort palette values to start with lowest palette value
6441     sortTreeInfo(&bd_palettes_c64dtv);
6442
6443     // set current palette value to configured palette value
6444     bd_palette_c64dtv_current =
6445       getTreeInfoFromIdentifier(bd_palettes_c64dtv, i_to_a(setup.bd_palette_c64dtv));
6446
6447     // if that fails, set current palette to reliable default value
6448     if (bd_palette_c64dtv_current == NULL)
6449       bd_palette_c64dtv_current =
6450         getTreeInfoFromIdentifier(bd_palettes_c64dtv, i_to_a(GD_DEFAULT_PALETTE_C64DTV));
6451
6452     // if that also fails, set current palette to first available value
6453     if (bd_palette_c64dtv_current == NULL)
6454       bd_palette_c64dtv_current = bd_palettes_c64dtv;
6455   }
6456
6457   setup.bd_palette_c64dtv = atoi(bd_palette_c64dtv_current->identifier);
6458
6459   // needed for displaying palette text instead of identifier
6460   bd_palette_c64dtv_text = bd_palette_c64dtv_current->name;
6461 }
6462
6463 static void execSetupEngines_setPalettesAtari(void)
6464 {
6465   if (bd_palettes_atari == NULL)
6466   {
6467     int i;
6468
6469     for (i = 0; bd_palettes_atari_list[i].value != -1; i++)
6470     {
6471       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6472       char identifier[32], name[32];
6473       int value = bd_palettes_atari_list[i].value;
6474       char *text = bd_palettes_atari_list[i].text;
6475
6476       ti->node_top = &bd_palettes_atari;
6477       ti->sort_priority = value;
6478
6479       sprintf(identifier, "%d", value);
6480       sprintf(name, "%s", text);
6481
6482       setString(&ti->identifier, identifier);
6483       setString(&ti->name, name);
6484       setString(&ti->name_sorting, name);
6485       setString(&ti->infotext, STR_SETUP_CHOOSE_BD_PALETTE_ATARI);
6486
6487       pushTreeInfo(&bd_palettes_atari, ti);
6488     }
6489
6490     // sort palette values to start with lowest palette value
6491     sortTreeInfo(&bd_palettes_atari);
6492
6493     // set current palette value to configured palette value
6494     bd_palette_atari_current =
6495       getTreeInfoFromIdentifier(bd_palettes_atari, i_to_a(setup.bd_palette_atari));
6496
6497     // if that fails, set current palette to reliable default value
6498     if (bd_palette_atari_current == NULL)
6499       bd_palette_atari_current =
6500         getTreeInfoFromIdentifier(bd_palettes_atari, i_to_a(GD_DEFAULT_PALETTE_ATARI));
6501
6502     // if that also fails, set current palette to first available value
6503     if (bd_palette_atari_current == NULL)
6504       bd_palette_atari_current = bd_palettes_atari;
6505   }
6506
6507   setup.bd_palette_atari = atoi(bd_palette_atari_current->identifier);
6508
6509   // needed for displaying palette text instead of identifier
6510   bd_palette_atari_text = bd_palette_atari_current->name;
6511 }
6512
6513 static void execSetupEngines_setColorType(void)
6514 {
6515   if (bd_color_types == NULL)
6516   {
6517     int i;
6518
6519     for (i = 0; bd_color_types_list[i].value != -1; i++)
6520     {
6521       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6522       char identifier[32], name[32];
6523       int value = bd_color_types_list[i].value;
6524       char *text = bd_color_types_list[i].text;
6525
6526       ti->node_top = &bd_color_types;
6527       ti->sort_priority = value;
6528
6529       sprintf(identifier, "%d", value);
6530       sprintf(name, "%s", text);
6531
6532       setString(&ti->identifier, identifier);
6533       setString(&ti->name, name);
6534       setString(&ti->name_sorting, name);
6535       setString(&ti->infotext, STR_SETUP_CHOOSE_BD_COLOR_TYPE);
6536
6537       pushTreeInfo(&bd_color_types, ti);
6538     }
6539
6540     // sort color type values to start with lowest color type value
6541     sortTreeInfo(&bd_color_types);
6542
6543     // set current color type value to configured color type value
6544     bd_color_type_current =
6545       getTreeInfoFromIdentifier(bd_color_types, i_to_a(setup.bd_default_color_type));
6546
6547     // if that fails, set current color type to reliable default value
6548     if (bd_color_type_current == NULL)
6549       bd_color_type_current =
6550         getTreeInfoFromIdentifier(bd_color_types, i_to_a(GD_DEFAULT_COLOR_TYPE));
6551
6552     // if that also fails, set current color type to first available value
6553     if (bd_color_type_current == NULL)
6554       bd_color_type_current = bd_color_types;
6555   }
6556
6557   setup.bd_default_color_type = atoi(bd_color_type_current->identifier);
6558
6559   // needed for displaying color type text instead of identifier
6560   bd_color_type_text = bd_color_type_current->name;
6561 }
6562
6563 static void execSetupEngines(void)
6564 {
6565   setup_mode = SETUP_MODE_ENGINES;
6566
6567   execSetupEngines_setGameEngineType();
6568   execSetupEngines_setPalettesC64();
6569   execSetupEngines_setPalettesC64DTV();
6570   execSetupEngines_setPalettesAtari();
6571   execSetupEngines_setColorType();
6572
6573   DrawSetupScreen();
6574 }
6575
6576 static void execSetupChooseGameEngineType(void)
6577 {
6578   setup_mode = SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE;
6579
6580   DrawSetupScreen();
6581 }
6582
6583 static void execSetupChoosePaletteC64(void)
6584 {
6585   setup_mode = SETUP_MODE_CHOOSE_BD_PALETTE_C64;
6586
6587   DrawSetupScreen();
6588 }
6589
6590 static void execSetupChoosePaletteC64DTV(void)
6591 {
6592   setup_mode = SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV;
6593
6594   DrawSetupScreen();
6595 }
6596
6597 static void execSetupChoosePaletteAtari(void)
6598 {
6599   setup_mode = SETUP_MODE_CHOOSE_BD_PALETTE_ATARI;
6600
6601   DrawSetupScreen();
6602 }
6603
6604 static void execSetupChooseColorType(void)
6605 {
6606   setup_mode = SETUP_MODE_CHOOSE_BD_COLOR_TYPE;
6607
6608   DrawSetupScreen();
6609 }
6610
6611 static void execSetupEditor(void)
6612 {
6613   setup_mode = SETUP_MODE_EDITOR;
6614
6615   DrawSetupScreen();
6616 }
6617
6618 static void execSetupGraphics_setWindowSizes(boolean update_list)
6619 {
6620   if (window_sizes != NULL && update_list)
6621   {
6622     freeTreeInfo(window_sizes);
6623
6624     window_sizes = NULL;
6625   }
6626
6627   if (window_sizes == NULL)
6628   {
6629     boolean current_window_size_found = FALSE;
6630     int i;
6631
6632     for (i = 0; window_sizes_list[i].value != -1; i++)
6633     {
6634       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6635       char identifier[32], name[32];
6636       int value = window_sizes_list[i].value;
6637       char *text = window_sizes_list[i].text;
6638
6639       ti->node_top = &window_sizes;
6640       ti->sort_priority = value;
6641
6642       sprintf(identifier, "%d", value);
6643       sprintf(name, "%s", text);
6644
6645       setString(&ti->identifier, identifier);
6646       setString(&ti->name, name);
6647       setString(&ti->name_sorting, name);
6648       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6649
6650       pushTreeInfo(&window_sizes, ti);
6651
6652       if (value == setup.window_scaling_percent)
6653         current_window_size_found = TRUE;
6654     }
6655
6656     if (!current_window_size_found)
6657     {
6658       // add entry for non-preset window scaling value
6659
6660       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6661       char identifier[32], name[32];
6662       int value = setup.window_scaling_percent;
6663
6664       ti->node_top = &window_sizes;
6665       ti->sort_priority = value;
6666
6667       sprintf(identifier, "%d", value);
6668       sprintf(name, "%d %% (Current)", value);
6669
6670       setString(&ti->identifier, identifier);
6671       setString(&ti->name, name);
6672       setString(&ti->name_sorting, name);
6673       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6674
6675       pushTreeInfo(&window_sizes, ti);
6676     }
6677
6678     // sort window size values to start with lowest window size value
6679     sortTreeInfo(&window_sizes);
6680
6681     // set current window size value to configured window size value
6682     window_size_current =
6683       getTreeInfoFromIdentifier(window_sizes,
6684                                 i_to_a(setup.window_scaling_percent));
6685
6686     // if that fails, set current window size to reliable default value
6687     if (window_size_current == NULL)
6688       window_size_current =
6689         getTreeInfoFromIdentifier(window_sizes,
6690                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
6691
6692     // if that also fails, set current window size to first available value
6693     if (window_size_current == NULL)
6694       window_size_current = window_sizes;
6695   }
6696
6697   setup.window_scaling_percent = atoi(window_size_current->identifier);
6698
6699   // needed for displaying window size text instead of identifier
6700   window_size_text = window_size_current->name;
6701 }
6702
6703 static void execSetupGraphics_setScalingTypes(void)
6704 {
6705   if (scaling_types == NULL)
6706   {
6707     int i;
6708
6709     for (i = 0; scaling_types_list[i].value != NULL; i++)
6710     {
6711       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6712       char identifier[32], name[32];
6713       char *value = scaling_types_list[i].value;
6714       char *text = scaling_types_list[i].text;
6715
6716       ti->node_top = &scaling_types;
6717       ti->sort_priority = i;
6718
6719       sprintf(identifier, "%s", value);
6720       sprintf(name, "%s", text);
6721
6722       setString(&ti->identifier, identifier);
6723       setString(&ti->name, name);
6724       setString(&ti->name_sorting, name);
6725       setString(&ti->infotext, STR_SETUP_CHOOSE_SCALING_TYPE);
6726
6727       pushTreeInfo(&scaling_types, ti);
6728     }
6729
6730     // sort scaling type values to start with lowest scaling type value
6731     sortTreeInfo(&scaling_types);
6732
6733     // set current scaling type value to configured scaling type value
6734     scaling_type_current =
6735       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
6736
6737     // if that fails, set current scaling type to reliable default value
6738     if (scaling_type_current == NULL)
6739       scaling_type_current =
6740         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
6741
6742     // if that also fails, set current scaling type to first available value
6743     if (scaling_type_current == NULL)
6744       scaling_type_current = scaling_types;
6745   }
6746
6747   setup.window_scaling_quality = scaling_type_current->identifier;
6748
6749   // needed for displaying scaling type text instead of identifier
6750   scaling_type_text = scaling_type_current->name;
6751 }
6752
6753 static void execSetupGraphics_setRenderingModes(void)
6754 {
6755   if (rendering_modes == NULL)
6756   {
6757     int i;
6758
6759     for (i = 0; rendering_modes_list[i].value != NULL; i++)
6760     {
6761       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6762       char identifier[32], name[32];
6763       char *value = rendering_modes_list[i].value;
6764       char *text = rendering_modes_list[i].text;
6765
6766       ti->node_top = &rendering_modes;
6767       ti->sort_priority = i;
6768
6769       sprintf(identifier, "%s", value);
6770       sprintf(name, "%s", text);
6771
6772       setString(&ti->identifier, identifier);
6773       setString(&ti->name, name);
6774       setString(&ti->name_sorting, name);
6775       setString(&ti->infotext, STR_SETUP_CHOOSE_RENDERING);
6776
6777       pushTreeInfo(&rendering_modes, ti);
6778     }
6779
6780     // sort rendering mode values to start with lowest rendering mode value
6781     sortTreeInfo(&rendering_modes);
6782
6783     // set current rendering mode value to configured rendering mode value
6784     rendering_mode_current =
6785       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
6786
6787     // if that fails, set current rendering mode to reliable default value
6788     if (rendering_mode_current == NULL)
6789       rendering_mode_current =
6790         getTreeInfoFromIdentifier(rendering_modes,
6791                                   STR_SPECIAL_RENDERING_DEFAULT);
6792
6793     // if that also fails, set current rendering mode to first available one
6794     if (rendering_mode_current == NULL)
6795       rendering_mode_current = rendering_modes;
6796   }
6797
6798   setup.screen_rendering_mode = rendering_mode_current->identifier;
6799
6800   // needed for displaying rendering mode text instead of identifier
6801   rendering_mode_text = rendering_mode_current->name;
6802 }
6803
6804 static void execSetupGraphics_setVsyncModes(boolean update_value)
6805 {
6806   if (vsync_modes == NULL)
6807   {
6808     int i;
6809
6810     for (i = 0; vsync_modes_list[i].value != NULL; i++)
6811     {
6812       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6813       char identifier[32], name[32];
6814       char *value = vsync_modes_list[i].value;
6815       char *text = vsync_modes_list[i].text;
6816
6817       ti->node_top = &vsync_modes;
6818       ti->sort_priority = i;
6819
6820       sprintf(identifier, "%s", value);
6821       sprintf(name, "%s", text);
6822
6823       setString(&ti->identifier, identifier);
6824       setString(&ti->name, name);
6825       setString(&ti->name_sorting, name);
6826       setString(&ti->infotext, STR_SETUP_CHOOSE_VSYNC);
6827
6828       pushTreeInfo(&vsync_modes, ti);
6829     }
6830
6831     // sort vsync mode values to start with lowest vsync mode value
6832     sortTreeInfo(&vsync_modes);
6833
6834     update_value = TRUE;
6835   }
6836
6837   if (update_value)
6838   {
6839     // set current vsync mode value to configured vsync mode value
6840     vsync_mode_current =
6841       getTreeInfoFromIdentifier(vsync_modes, setup.vsync_mode);
6842
6843     // if that fails, set current vsync mode to reliable default value
6844     if (vsync_mode_current == NULL)
6845       vsync_mode_current =
6846         getTreeInfoFromIdentifier(vsync_modes, STR_VSYNC_MODE_DEFAULT);
6847
6848     // if that also fails, set current vsync mode to first available one
6849     if (vsync_mode_current == NULL)
6850       vsync_mode_current = vsync_modes;
6851   }
6852
6853   setup.vsync_mode = vsync_mode_current->identifier;
6854
6855   // needed for displaying vsync mode text instead of identifier
6856   vsync_mode_text = vsync_mode_current->name;
6857 }
6858
6859 static void execSetupGraphics(void)
6860 {
6861   boolean check_game_speed = (setup_mode == SETUP_MODE_CHOOSE_VSYNC);
6862
6863   // update "setup.window_scaling_percent" from list selection
6864   // (in this case, window scaling was changed on setup screen)
6865   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6866     execSetupGraphics_setWindowSizes(FALSE);
6867
6868   // update "setup.vsync_mode" from list selection
6869   // (in this case, vsync mode was changed on setup screen)
6870   if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
6871     execSetupGraphics_setVsyncModes(FALSE);
6872
6873   // update list selection from "setup.window_scaling_percent"
6874   // (window scaling may have changed by resizing the window)
6875   execSetupGraphics_setWindowSizes(TRUE);
6876
6877   // update list selection from "setup.vsync_mode"
6878   // (vsync_mode may have changed by re-creating the renderer)
6879   execSetupGraphics_setVsyncModes(TRUE);
6880
6881   execSetupGraphics_setScalingTypes();
6882   execSetupGraphics_setRenderingModes();
6883
6884   setup_mode = SETUP_MODE_GRAPHICS;
6885
6886   DrawSetupScreen();
6887
6888   // check if game speed is high enough for 60 Hz vsync to work
6889   if (check_game_speed)
6890     ModifyGameSpeedIfNeeded();
6891
6892   // window scaling may have changed at this point
6893   ChangeWindowScalingIfNeeded();
6894
6895   // window scaling quality may have changed at this point
6896   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
6897     SDLSetWindowScalingQuality(setup.window_scaling_quality);
6898
6899   // screen rendering mode may have changed at this point
6900   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
6901
6902   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
6903   int video_vsync_mode = video.vsync_mode;
6904
6905   // screen vsync mode may have changed at this point
6906   ChangeVsyncModeIfNeeded();
6907
6908   // check if setting vsync mode to selected value failed
6909   if (setup_vsync_mode != video_vsync_mode &&
6910       setup_vsync_mode != video.vsync_mode)
6911   {
6912     // changing vsync mode to selected value failed -- reset displayed value
6913     execSetupGraphics_setVsyncModes(TRUE);
6914
6915     Request("Setting VSync failed!", REQ_CONFIRM);
6916
6917     DrawSetupScreen();
6918   }
6919 }
6920
6921 static void execSetupChooseWindowSize(void)
6922 {
6923   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
6924
6925   DrawSetupScreen();
6926 }
6927
6928 static void execSetupChooseScalingType(void)
6929 {
6930   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
6931
6932   DrawSetupScreen();
6933 }
6934
6935 static void execSetupChooseRenderingMode(void)
6936 {
6937   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
6938
6939   DrawSetupScreen();
6940 }
6941
6942 static void execSetupChooseVsyncMode(void)
6943 {
6944   setup_mode = SETUP_MODE_CHOOSE_VSYNC;
6945
6946   DrawSetupScreen();
6947 }
6948
6949 static void execSetupChooseVolumeSimple(void)
6950 {
6951   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
6952
6953   DrawSetupScreen();
6954 }
6955
6956 static void execSetupChooseVolumeLoops(void)
6957 {
6958   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
6959
6960   DrawSetupScreen();
6961 }
6962
6963 static void execSetupChooseVolumeMusic(void)
6964 {
6965   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
6966
6967   DrawSetupScreen();
6968 }
6969
6970 static void execSetupSound(void)
6971 {
6972   if (volumes_simple == NULL)
6973   {
6974     boolean current_volume_simple_found = FALSE;
6975     int i;
6976
6977     for (i = 0; volumes_list[i].value != -1; i++)
6978     {
6979       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6980       char identifier[32], name[32];
6981       int value = volumes_list[i].value;
6982       char *text = volumes_list[i].text;
6983
6984       ti->node_top = &volumes_simple;
6985       ti->sort_priority = value;
6986
6987       sprintf(identifier, "%d", value);
6988       sprintf(name, "%s", text);
6989
6990       setString(&ti->identifier, identifier);
6991       setString(&ti->name, name);
6992       setString(&ti->name_sorting, name);
6993       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6994
6995       pushTreeInfo(&volumes_simple, ti);
6996
6997       if (value == setup.volume_simple)
6998         current_volume_simple_found = TRUE;
6999     }
7000
7001     if (!current_volume_simple_found)
7002     {
7003       // add entry for non-preset volume value
7004
7005       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7006       char identifier[32], name[32];
7007       int value = setup.volume_simple;
7008
7009       ti->node_top = &volumes_simple;
7010       ti->sort_priority = value;
7011
7012       sprintf(identifier, "%d", value);
7013       sprintf(name, "%d %% (Current)", value);
7014
7015       setString(&ti->identifier, identifier);
7016       setString(&ti->name, name);
7017       setString(&ti->name_sorting, name);
7018       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
7019
7020       pushTreeInfo(&volumes_simple, ti);
7021     }
7022
7023     // sort volume values to start with lowest volume value
7024     sortTreeInfo(&volumes_simple);
7025
7026     // set current volume value to configured volume value
7027     volume_simple_current =
7028       getTreeInfoFromIdentifier(volumes_simple, i_to_a(setup.volume_simple));
7029
7030     // if that fails, set current volume to reliable default value
7031     if (volume_simple_current == NULL)
7032       volume_simple_current =
7033         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
7034
7035     // if that also fails, set current volume to first available value
7036     if (volume_simple_current == NULL)
7037       volume_simple_current = volumes_simple;
7038   }
7039
7040   if (volumes_loops == NULL)
7041   {
7042     boolean current_volume_loops_found = FALSE;
7043     int i;
7044
7045     for (i = 0; volumes_list[i].value != -1; i++)
7046     {
7047       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7048       char identifier[32], name[32];
7049       int value = volumes_list[i].value;
7050       char *text = volumes_list[i].text;
7051
7052       ti->node_top = &volumes_loops;
7053       ti->sort_priority = value;
7054
7055       sprintf(identifier, "%d", value);
7056       sprintf(name, "%s", text);
7057
7058       setString(&ti->identifier, identifier);
7059       setString(&ti->name, name);
7060       setString(&ti->name_sorting, name);
7061       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
7062
7063       pushTreeInfo(&volumes_loops, ti);
7064
7065       if (value == setup.volume_loops)
7066         current_volume_loops_found = TRUE;
7067     }
7068
7069     if (!current_volume_loops_found)
7070     {
7071       // add entry for non-preset volume value
7072
7073       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7074       char identifier[32], name[32];
7075       int value = setup.volume_loops;
7076
7077       ti->node_top = &volumes_loops;
7078       ti->sort_priority = value;
7079
7080       sprintf(identifier, "%d", value);
7081       sprintf(name, "%d %% (Current)", value);
7082
7083       setString(&ti->identifier, identifier);
7084       setString(&ti->name, name);
7085       setString(&ti->name_sorting, name);
7086       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
7087
7088       pushTreeInfo(&volumes_loops, ti);
7089     }
7090
7091     // sort volume values to start with lowest volume value
7092     sortTreeInfo(&volumes_loops);
7093
7094     // set current volume value to configured volume value
7095     volume_loops_current =
7096       getTreeInfoFromIdentifier(volumes_loops, i_to_a(setup.volume_loops));
7097
7098     // if that fails, set current volume to reliable default value
7099     if (volume_loops_current == NULL)
7100       volume_loops_current =
7101         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
7102
7103     // if that also fails, set current volume to first available value
7104     if (volume_loops_current == NULL)
7105       volume_loops_current = volumes_loops;
7106   }
7107
7108   if (volumes_music == NULL)
7109   {
7110     boolean current_volume_music_found = FALSE;
7111     int i;
7112
7113     for (i = 0; volumes_list[i].value != -1; i++)
7114     {
7115       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7116       char identifier[32], name[32];
7117       int value = volumes_list[i].value;
7118       char *text = volumes_list[i].text;
7119
7120       ti->node_top = &volumes_music;
7121       ti->sort_priority = value;
7122
7123       sprintf(identifier, "%d", value);
7124       sprintf(name, "%s", text);
7125
7126       setString(&ti->identifier, identifier);
7127       setString(&ti->name, name);
7128       setString(&ti->name_sorting, name);
7129       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
7130
7131       pushTreeInfo(&volumes_music, ti);
7132
7133       if (value == setup.volume_music)
7134         current_volume_music_found = TRUE;
7135     }
7136
7137     if (!current_volume_music_found)
7138     {
7139       // add entry for non-preset volume value
7140
7141       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7142       char identifier[32], name[32];
7143       int value = setup.volume_music;
7144
7145       ti->node_top = &volumes_music;
7146       ti->sort_priority = value;
7147
7148       sprintf(identifier, "%d", value);
7149       sprintf(name, "%d %% (Current)", value);
7150
7151       setString(&ti->identifier, identifier);
7152       setString(&ti->name, name);
7153       setString(&ti->name_sorting, name);
7154       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
7155
7156       pushTreeInfo(&volumes_music, ti);
7157     }
7158
7159     // sort volume values to start with lowest volume value
7160     sortTreeInfo(&volumes_music);
7161
7162     // set current volume value to configured volume value
7163     volume_music_current =
7164       getTreeInfoFromIdentifier(volumes_music, i_to_a(setup.volume_music));
7165
7166     // if that fails, set current volume to reliable default value
7167     if (volume_music_current == NULL)
7168       volume_music_current =
7169         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
7170
7171     // if that also fails, set current volume to first available value
7172     if (volume_music_current == NULL)
7173       volume_music_current = volumes_music;
7174   }
7175
7176   setup.volume_simple = atoi(volume_simple_current->identifier);
7177   setup.volume_loops  = atoi(volume_loops_current->identifier);
7178   setup.volume_music  = atoi(volume_music_current->identifier);
7179
7180   // needed for displaying volume text instead of identifier
7181   volume_simple_text = volume_simple_current->name;
7182   volume_loops_text = volume_loops_current->name;
7183   volume_music_text = volume_music_current->name;
7184
7185   setup_mode = SETUP_MODE_SOUND;
7186
7187   DrawSetupScreen();
7188 }
7189
7190 static void execSetupChooseTouchControls(void)
7191 {
7192   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
7193
7194   DrawSetupScreen();
7195 }
7196
7197 static void execSetupChooseMoveDistance(void)
7198 {
7199   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
7200
7201   DrawSetupScreen();
7202 }
7203
7204 static void execSetupChooseDropDistance(void)
7205 {
7206   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
7207
7208   DrawSetupScreen();
7209 }
7210
7211 static void execSetupChooseTransparency(void)
7212 {
7213   setup_mode = SETUP_MODE_CHOOSE_TRANSPARENCY;
7214
7215   DrawSetupScreen();
7216 }
7217
7218 static void execSetupChooseGridXSize_0(void)
7219 {
7220   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_0;
7221
7222   DrawSetupScreen();
7223 }
7224
7225 static void execSetupChooseGridYSize_0(void)
7226 {
7227   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_0;
7228
7229   DrawSetupScreen();
7230 }
7231
7232 static void execSetupChooseGridXSize_1(void)
7233 {
7234   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_1;
7235
7236   DrawSetupScreen();
7237 }
7238
7239 static void execSetupChooseGridYSize_1(void)
7240 {
7241   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_1;
7242
7243   DrawSetupScreen();
7244 }
7245
7246 static void execSetupConfigureVirtualButtons(void)
7247 {
7248   setup_mode = SETUP_MODE_CONFIG_VIRT_BUTTONS;
7249
7250   ConfigureVirtualButtons();
7251
7252   setup_mode = SETUP_MODE_TOUCH;
7253
7254   DrawSetupScreen();
7255 }
7256
7257 static void execSetupTouch(void)
7258 {
7259   int i, j, k;
7260
7261   if (touch_controls == NULL)
7262   {
7263     for (i = 0; touch_controls_list[i].value != NULL; i++)
7264     {
7265       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7266       char identifier[32], name[32];
7267       char *value = touch_controls_list[i].value;
7268       char *text = touch_controls_list[i].text;
7269
7270       ti->node_top = &touch_controls;
7271       ti->sort_priority = i;
7272
7273       sprintf(identifier, "%s", value);
7274       sprintf(name, "%s", text);
7275
7276       setString(&ti->identifier, identifier);
7277       setString(&ti->name, name);
7278       setString(&ti->name_sorting, name);
7279       setString(&ti->infotext, STR_SETUP_CHOOSE_TOUCH_CONTROL);
7280
7281       pushTreeInfo(&touch_controls, ti);
7282     }
7283
7284     // sort touch control values to start with lowest touch control value
7285     sortTreeInfo(&touch_controls);
7286
7287     // set current touch control value to configured touch control value
7288     touch_control_current =
7289       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
7290
7291     // if that fails, set current touch control to reliable default value
7292     if (touch_control_current == NULL)
7293       touch_control_current =
7294         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
7295
7296     // if that also fails, set current touch control to first available value
7297     if (touch_control_current == NULL)
7298       touch_control_current = touch_controls;
7299   }
7300
7301   if (move_distances == NULL)
7302   {
7303     for (i = 0; distances_list[i].value != -1; i++)
7304     {
7305       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7306       char identifier[32], name[32];
7307       int value = distances_list[i].value;
7308       char *text = distances_list[i].text;
7309
7310       ti->node_top = &move_distances;
7311       ti->sort_priority = value;
7312
7313       sprintf(identifier, "%d", value);
7314       sprintf(name, "%s", text);
7315
7316       setString(&ti->identifier, identifier);
7317       setString(&ti->name, name);
7318       setString(&ti->name_sorting, name);
7319       setString(&ti->infotext, STR_SETUP_CHOOSE_MOVE_DISTANCE);
7320
7321       pushTreeInfo(&move_distances, ti);
7322     }
7323
7324     // sort distance values to start with lowest distance value
7325     sortTreeInfo(&move_distances);
7326
7327     // set current distance value to configured distance value
7328     move_distance_current =
7329       getTreeInfoFromIdentifier(move_distances,
7330                                 i_to_a(setup.touch.move_distance));
7331
7332     // if that fails, set current distance to reliable default value
7333     if (move_distance_current == NULL)
7334       move_distance_current =
7335         getTreeInfoFromIdentifier(move_distances,
7336                                   i_to_a(TOUCH_MOVE_DISTANCE_DEFAULT));
7337
7338     // if that also fails, set current distance to first available value
7339     if (move_distance_current == NULL)
7340       move_distance_current = move_distances;
7341   }
7342
7343   if (drop_distances == NULL)
7344   {
7345     for (i = 0; distances_list[i].value != -1; i++)
7346     {
7347       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7348       char identifier[32], name[32];
7349       int value = distances_list[i].value;
7350       char *text = distances_list[i].text;
7351
7352       ti->node_top = &drop_distances;
7353       ti->sort_priority = value;
7354
7355       sprintf(identifier, "%d", value);
7356       sprintf(name, "%s", text);
7357
7358       setString(&ti->identifier, identifier);
7359       setString(&ti->name, name);
7360       setString(&ti->name_sorting, name);
7361       setString(&ti->infotext, STR_SETUP_CHOOSE_DROP_DISTANCE);
7362
7363       pushTreeInfo(&drop_distances, ti);
7364     }
7365
7366     // sort distance values to start with lowest distance value
7367     sortTreeInfo(&drop_distances);
7368
7369     // set current distance value to configured distance value
7370     drop_distance_current =
7371       getTreeInfoFromIdentifier(drop_distances,
7372                                 i_to_a(setup.touch.drop_distance));
7373
7374     // if that fails, set current distance to reliable default value
7375     if (drop_distance_current == NULL)
7376       drop_distance_current =
7377         getTreeInfoFromIdentifier(drop_distances,
7378                                   i_to_a(TOUCH_DROP_DISTANCE_DEFAULT));
7379
7380     // if that also fails, set current distance to first available value
7381     if (drop_distance_current == NULL)
7382       drop_distance_current = drop_distances;
7383   }
7384
7385   if (transparencies == NULL)
7386   {
7387     for (i = 0; transparencies_list[i].value != -1; i++)
7388     {
7389       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7390       char identifier[32], name[32];
7391       int value = transparencies_list[i].value;
7392       char *text = transparencies_list[i].text;
7393
7394       ti->node_top = &transparencies;
7395       ti->sort_priority = value;
7396
7397       sprintf(identifier, "%d", value);
7398       sprintf(name, "%s", text);
7399
7400       setString(&ti->identifier, identifier);
7401       setString(&ti->name, name);
7402       setString(&ti->name_sorting, name);
7403       setString(&ti->infotext, STR_SETUP_CHOOSE_TRANSPARENCY);
7404
7405       pushTreeInfo(&transparencies, ti);
7406     }
7407
7408     // sort transparency values to start with lowest transparency value
7409     sortTreeInfo(&transparencies);
7410
7411     // set current transparency value to configured transparency value
7412     transparency_current =
7413       getTreeInfoFromIdentifier(transparencies,
7414                                 i_to_a(setup.touch.transparency));
7415
7416     // if that fails, set current transparency to reliable default value
7417     if (transparency_current == NULL)
7418       transparency_current =
7419         getTreeInfoFromIdentifier(transparencies,
7420                                   i_to_a(TOUCH_TRANSPARENCY_DEFAULT));
7421
7422     // if that also fails, set current transparency to first available value
7423     if (transparency_current == NULL)
7424       transparency_current = transparencies;
7425   }
7426
7427   for (i = 0; i < 2; i++)
7428   {
7429     for (j = 0; j < 2; j++)
7430     {
7431       if (grid_sizes[i][j] == NULL)
7432       {
7433         for (k = 0; grid_sizes_list[k].value != -1; k++)
7434         {
7435           TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7436           char identifier[32], name[32];
7437           int value = grid_sizes_list[k].value;
7438           char *text = grid_sizes_list[k].text;
7439
7440           ti->node_top = &grid_sizes[i][j];
7441           ti->sort_priority = value;
7442
7443           sprintf(identifier, "%d", value);
7444           sprintf(name, "%s", text);
7445
7446           setString(&ti->identifier, identifier);
7447           setString(&ti->name, name);
7448           setString(&ti->name_sorting, name);
7449           setString(&ti->infotext,
7450                     (i == 0 ?
7451                      (j == 0 ?
7452                       STR_SETUP_CHOOSE_GRID_XSIZE_0 :
7453                       STR_SETUP_CHOOSE_GRID_YSIZE_0) :
7454                      (j == 0 ?
7455                       STR_SETUP_CHOOSE_GRID_XSIZE_1 :
7456                       STR_SETUP_CHOOSE_GRID_YSIZE_1)));
7457
7458           pushTreeInfo(&grid_sizes[i][j], ti);
7459         }
7460
7461         // sort grid size values to start with lowest grid size value
7462         sortTreeInfo(&grid_sizes[i][j]);
7463
7464         // set current grid size value to configured grid size value
7465         grid_size_current[i][j] =
7466           getTreeInfoFromIdentifier(grid_sizes[i][j],
7467                                     i_to_a(j == 0 ?
7468                                            setup.touch.grid_xsize[i] :
7469                                            setup.touch.grid_ysize[i]));
7470
7471         // if that fails, set current grid size to reliable default value
7472         if (grid_size_current[i][j] == NULL)
7473           grid_size_current[i][j] =
7474             getTreeInfoFromIdentifier(grid_sizes[i][j],
7475                                       i_to_a(j == 0 ?
7476                                              DEFAULT_GRID_XSIZE(i) :
7477                                              DEFAULT_GRID_YSIZE(i)));
7478
7479         // if that also fails, set current grid size to first available value
7480         if (grid_size_current[i][j] == NULL)
7481           grid_size_current[i][j] = grid_sizes[i][j];
7482       }
7483     }
7484   }
7485
7486   setup.touch.control_type = touch_control_current->identifier;
7487   setup.touch.move_distance = atoi(move_distance_current->identifier);
7488   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
7489   setup.touch.transparency = atoi(transparency_current->identifier);
7490
7491   for (i = 0; i < 2; i++)
7492   {
7493     setup.touch.grid_xsize[i] = atoi(grid_size_current[i][0]->identifier);
7494     setup.touch.grid_ysize[i] = atoi(grid_size_current[i][1]->identifier);
7495
7496     if (i == GRID_ACTIVE_NR())
7497     {
7498       overlay.grid_xsize = setup.touch.grid_xsize[i];
7499       overlay.grid_ysize = setup.touch.grid_ysize[i];
7500     }
7501   }
7502
7503   // needed for displaying value text instead of identifier
7504   touch_controls_text = touch_control_current->name;
7505   move_distance_text = move_distance_current->name;
7506   drop_distance_text = drop_distance_current->name;
7507   transparency_text = transparency_current->name;
7508
7509   for (i = 0; i < 2; i++)
7510     for (j = 0; j < 2; j++)
7511       grid_size_text[i][j] = grid_size_current[i][j]->name;
7512
7513   setup_mode = SETUP_MODE_TOUCH;
7514
7515   DrawSetupScreen();
7516 }
7517
7518 static void execSetupArtwork(void)
7519 {
7520   static ArtworkDirTree *gfx_last_valid = NULL;
7521   static ArtworkDirTree *snd_last_valid = NULL;
7522   static ArtworkDirTree *mus_last_valid = NULL;
7523
7524   // current artwork directory may be invalid (level group, parent link)
7525   if (!validLevelSeries(artwork.gfx_current))
7526     artwork.gfx_current = getFirstValidTreeInfoEntry(gfx_last_valid);
7527   if (!validLevelSeries(artwork.snd_current))
7528     artwork.snd_current = getFirstValidTreeInfoEntry(snd_last_valid);
7529   if (!validLevelSeries(artwork.mus_current))
7530     artwork.mus_current = getFirstValidTreeInfoEntry(mus_last_valid);
7531
7532   // store valid artwork directory information
7533   gfx_last_valid = artwork.gfx_current;
7534   snd_last_valid = artwork.snd_current;
7535   mus_last_valid = artwork.mus_current;
7536
7537 #if 0
7538   Debug("screens:execSetupArtwork", "'%s', '%s', '%s'",
7539         artwork.gfx_current->subdir,
7540         artwork.gfx_current->fullpath,
7541         artwork.gfx_current->basepath);
7542 #endif
7543
7544   setup.graphics_set = artwork.gfx_current->identifier;
7545   setup.sounds_set = artwork.snd_current->identifier;
7546   setup.music_set = artwork.mus_current->identifier;
7547
7548   // needed if last screen (setup choice) changed graphics, sounds or music
7549   ReloadCustomArtwork(0);
7550
7551   // needed for displaying artwork name instead of artwork identifier
7552   graphics_set_name = artwork.gfx_current->name;
7553   sounds_set_name = artwork.snd_current->name;
7554   music_set_name = artwork.mus_current->name;
7555
7556   setup_mode = SETUP_MODE_ARTWORK;
7557
7558   DrawSetupScreen();
7559 }
7560
7561 static void execSetupChooseGraphics(void)
7562 {
7563   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
7564
7565   DrawSetupScreen();
7566 }
7567
7568 static void execSetupChooseSounds(void)
7569 {
7570   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
7571
7572   DrawSetupScreen();
7573 }
7574
7575 static void execSetupChooseMusic(void)
7576 {
7577   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
7578
7579   DrawSetupScreen();
7580 }
7581
7582 static void execSetupInput(void)
7583 {
7584   setup_mode = SETUP_MODE_INPUT;
7585
7586   DrawSetupScreen();
7587 }
7588
7589 static void execSetupShortcuts(void)
7590 {
7591   setup_mode = SETUP_MODE_SHORTCUTS;
7592
7593   DrawSetupScreen();
7594 }
7595
7596 static void execSetupShortcuts1(void)
7597 {
7598   setup_mode = SETUP_MODE_SHORTCUTS_1;
7599
7600   DrawSetupScreen();
7601 }
7602
7603 static void execSetupShortcuts2(void)
7604 {
7605   setup_mode = SETUP_MODE_SHORTCUTS_2;
7606
7607   DrawSetupScreen();
7608 }
7609
7610 static void execSetupShortcuts3(void)
7611 {
7612   setup_mode = SETUP_MODE_SHORTCUTS_3;
7613
7614   DrawSetupScreen();
7615 }
7616
7617 static void execSetupShortcuts4(void)
7618 {
7619   setup_mode = SETUP_MODE_SHORTCUTS_4;
7620
7621   DrawSetupScreen();
7622 }
7623
7624 static void execSetupShortcuts5(void)
7625 {
7626   setup_mode = SETUP_MODE_SHORTCUTS_5;
7627
7628   DrawSetupScreen();
7629 }
7630
7631 static void execSetupShortcuts6(void)
7632 {
7633   setup_mode = SETUP_MODE_SHORTCUTS_6;
7634
7635   DrawSetupScreen();
7636 }
7637
7638 static void execExitSetup(void)
7639 {
7640   SetGameStatus(GAME_MODE_MAIN);
7641
7642   DrawMainMenu();
7643 }
7644
7645 static void execSaveAndExitSetup(void)
7646 {
7647   SaveSetup();
7648   execExitSetup();
7649 }
7650
7651 static void execGadgetNetworkServer(void)
7652 {
7653   int gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
7654   struct GadgetInfo *gi = screen_gadget[gadget_id];
7655
7656   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
7657     network_server_hostname[0] = '\0';
7658
7659   ModifyGadget(gi, GDI_TEXT_VALUE, network_server_hostname, GDI_END);
7660
7661   MapGadget(gi);
7662
7663   ClickOnGadget(gi, MB_LEFTBUTTON);
7664 }
7665
7666 static void execOfferUploadTapes(void)
7667 {
7668   OfferUploadTapes();
7669 }
7670
7671 static void ToggleNetworkModeIfNeeded(void)
7672 {
7673   int font_title = FONT_TITLE_1;
7674   int font_foot = FC_BLUE;
7675   int ystart  = mSY - SY + 16;
7676   int ybottom = mSY - SY + SYSIZE - 20;
7677   char *text = (setup.network_mode ? "Start Network" : "Stop Network");
7678
7679   if (setup.network_mode == network.enabled)
7680     return;
7681
7682   network.enabled = setup.network_mode;
7683
7684   FadeOut(REDRAW_ALL);
7685
7686   ClearField();
7687
7688   DrawTextSCentered(ystart, font_title, text);
7689
7690   FadeIn(REDRAW_ALL);
7691
7692   if (network.enabled)
7693     InitNetworkServer();
7694   else
7695     DisconnectFromNetworkServer();
7696
7697   DrawTextSCentered(ybottom, font_foot,
7698                     "Press any key or button for setup menu");
7699
7700   WaitForEventToContinue();
7701
7702   DrawSetupScreen();
7703 }
7704
7705 static void ToggleGameSpeedsListIfNeeded(void)
7706 {
7707   boolean using_game_speeds_extended = (game_speeds == game_speeds_extended);
7708
7709   if (setup.game_speed_extended == using_game_speeds_extended)
7710     return;
7711
7712   // try to match similar values when changing game speeds list
7713   if (setup.game_speed_extended)
7714     setup.game_frame_delay = (setup.game_frame_delay == 15 ? 16 :
7715                               setup.game_frame_delay == 30 ? 29 :
7716                               setup.game_frame_delay);
7717   else
7718     setup.game_frame_delay = (setup.game_frame_delay == 14 ? 15 :
7719                               setup.game_frame_delay == 16 ? 15 :
7720                               setup.game_frame_delay >= 29 ? 30 :
7721                               setup.game_frame_delay <= 10 ? 10 :
7722                               setup.game_frame_delay);
7723
7724   execSetupGame_setGameSpeeds(TRUE);
7725
7726   DrawSetupScreen();
7727 }
7728
7729 static void ToggleUseApiServerIfNeeded(void)
7730 {
7731   if (runtime.use_api_server == setup.use_api_server)
7732     return;
7733
7734   runtime.use_api_server = setup.use_api_server;
7735
7736   if (runtime.use_api_server)
7737   {
7738     if (setup.has_remaining_tapes)
7739       setup.ask_for_uploading_tapes = TRUE;
7740
7741     CheckApiServerTasks();
7742   }
7743 }
7744
7745 static void ModifyGameSpeedIfNeeded(void)
7746 {
7747   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7748       setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY)
7749     return;
7750
7751   char message[100];
7752   char *game_speed_text = "Fast";
7753   int game_speed_value = 15;
7754
7755   if (setup.game_speed_extended)
7756   {
7757     game_speed_text = "60 fps";
7758     game_speed_value = 16;
7759   }
7760
7761   sprintf(message, "Game speed set to %s for VSync to work!", game_speed_text);
7762
7763   // set game speed to existing list value that is fast enough for vsync
7764   setup.game_frame_delay = game_speed_value;
7765
7766   execSetupGame_setGameSpeeds(TRUE);
7767
7768   Request(message, REQ_CONFIRM);
7769 }
7770
7771 static void DisableVsyncIfNeeded(void)
7772 {
7773   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7774       (setup.game_frame_delay >= MIN_VSYNC_FRAME_DELAY &&
7775        setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY))
7776     return;
7777
7778   // disable vsync for the selected game speed to work
7779   setup.vsync_mode = STR_VSYNC_MODE_OFF;
7780
7781   execSetupGraphics_setVsyncModes(TRUE);
7782
7783   Request("VSync disabled for this game speed to work!", REQ_CONFIRM);
7784 }
7785
7786 static struct
7787 {
7788   void *value;
7789   void *related_value;
7790 } hide_related_entry_list[] =
7791 {
7792   { &setup.network_server_hostname,             execGadgetNetworkServer         },
7793   { &setup.network_server_hostname,             &network_server_text            },
7794
7795   { &setup.scores_in_highscore_list,            execSetupChooseScoresType       },
7796   { &setup.scores_in_highscore_list,            &scores_type_text               },
7797
7798   { &setup.game_frame_delay,                    execSetupChooseGameSpeed        },
7799   { &setup.game_frame_delay,                    &game_speed_text                },
7800
7801   { &setup.scroll_delay_value,                  execSetupChooseScrollDelay      },
7802   { &setup.scroll_delay_value,                  &scroll_delay_text              },
7803
7804   { &setup.engine_snapshot_mode,                execSetupChooseSnapshotMode     },
7805   { &setup.engine_snapshot_mode,                &snapshot_mode_text             },
7806
7807   { &setup.default_game_engine_type,            execSetupChooseGameEngineType   },
7808   { &setup.default_game_engine_type,            &game_engine_type_text          },
7809
7810   { &setup.bd_palette_c64,                      execSetupChoosePaletteC64       },
7811   { &setup.bd_palette_c64,                      &bd_palette_c64_text            },
7812
7813   { &setup.bd_palette_c64dtv,                   execSetupChoosePaletteC64DTV    },
7814   { &setup.bd_palette_c64dtv,                   &bd_palette_c64dtv_text         },
7815
7816   { &setup.bd_palette_atari,                    execSetupChoosePaletteAtari     },
7817   { &setup.bd_palette_atari,                    &bd_palette_atari_text          },
7818
7819   { &setup.bd_default_color_type,               execSetupChooseColorType        },
7820   { &setup.bd_default_color_type,               &bd_color_type_text             },
7821
7822   { &setup.window_scaling_percent,              execSetupChooseWindowSize       },
7823   { &setup.window_scaling_percent,              &window_size_text               },
7824
7825   { &setup.window_scaling_quality,              execSetupChooseScalingType      },
7826   { &setup.window_scaling_quality,              &scaling_type_text              },
7827
7828   { &setup.screen_rendering_mode,               execSetupChooseRenderingMode    },
7829   { &setup.screen_rendering_mode,               &rendering_mode_text            },
7830
7831   { &setup.vsync_mode,                          execSetupChooseVsyncMode        },
7832   { &setup.vsync_mode,                          &vsync_mode_text                },
7833
7834   { &setup.graphics_set,                        execSetupChooseGraphics         },
7835   { &setup.graphics_set,                        &graphics_set_name              },
7836
7837   { &setup.sounds_set,                          execSetupChooseSounds           },
7838   { &setup.sounds_set,                          &sounds_set_name                },
7839
7840   { &setup.music_set,                           execSetupChooseMusic            },
7841   { &setup.music_set,                           &music_set_name                 },
7842
7843   { &setup.volume_simple,                       execSetupChooseVolumeSimple     },
7844   { &setup.volume_simple,                       &volume_simple_text             },
7845
7846   { &setup.volume_loops,                        execSetupChooseVolumeLoops      },
7847   { &setup.volume_loops,                        &volume_loops_text              },
7848
7849   { &setup.volume_music,                        execSetupChooseVolumeMusic      },
7850   { &setup.volume_music,                        &volume_music_text              },
7851
7852   { &setup.touch.control_type,                  execSetupChooseTouchControls    },
7853   { &setup.touch.control_type,                  &touch_controls_text            },
7854
7855   { &setup.touch.move_distance,                 execSetupChooseMoveDistance     },
7856   { &setup.touch.move_distance,                 &move_distance_text             },
7857
7858   { &setup.touch.drop_distance,                 execSetupChooseDropDistance     },
7859   { &setup.touch.drop_distance,                 &drop_distance_text             },
7860
7861   { &setup.touch.transparency,                  execSetupChooseTransparency     },
7862   { &setup.touch.transparency,                  &transparency_text              },
7863
7864   { &setup.touch.grid_xsize[0],                 execSetupChooseGridXSize_0      },
7865   { &setup.touch.grid_xsize[0],                 &grid_size_text[0][0]           },
7866
7867   { &setup.touch.grid_ysize[0],                 execSetupChooseGridYSize_0      },
7868   { &setup.touch.grid_ysize[0],                 &grid_size_text[0][1]           },
7869
7870   { &setup.touch.grid_xsize[1],                 execSetupChooseGridXSize_1      },
7871   { &setup.touch.grid_xsize[1],                 &grid_size_text[1][0]           },
7872
7873   { &setup.touch.grid_ysize[1],                 execSetupChooseGridYSize_1      },
7874   { &setup.touch.grid_ysize[1],                 &grid_size_text[1][1]           },
7875
7876   { &setup.internal.menu_game,                  execSetupGame                   },
7877   { &setup.internal.menu_engines,               execSetupEngines                },
7878   { &setup.internal.menu_editor,                execSetupEditor                 },
7879   { &setup.internal.menu_graphics,              execSetupGraphics               },
7880   { &setup.internal.menu_sound,                 execSetupSound                  },
7881   { &setup.internal.menu_artwork,               execSetupArtwork                },
7882   { &setup.internal.menu_input,                 execSetupInput                  },
7883   { &setup.internal.menu_touch,                 execSetupTouch                  },
7884   { &setup.internal.menu_shortcuts,             execSetupShortcuts              },
7885   { &setup.internal.menu_exit,                  execExitSetup                   },
7886   { &setup.internal.menu_save_and_exit,         execSaveAndExitSetup            },
7887
7888   { &setup.internal.menu_shortcuts_various,     execSetupShortcuts1             },
7889   { &setup.internal.menu_shortcuts_focus,       execSetupShortcuts2             },
7890   { &setup.internal.menu_shortcuts_tape,        execSetupShortcuts3             },
7891   { &setup.internal.menu_shortcuts_sound,       execSetupShortcuts4             },
7892   { &setup.internal.menu_shortcuts_snap,        execSetupShortcuts5             },
7893   { &setup.internal.menu_shortcuts_speed,       execSetupShortcuts6             },
7894
7895   { &setup.internal.info_title,                 execInfoTitleScreen             },
7896   { &setup.internal.info_elements,              execInfoElements                },
7897   { &setup.internal.info_music,                 execInfoMusic                   },
7898   { &setup.internal.info_credits,               execInfoCredits                 },
7899   { &setup.internal.info_program,               execInfoProgram                 },
7900   { &setup.internal.info_version,               execInfoVersion                 },
7901   { &setup.internal.info_levelset,              execInfoLevelSet                },
7902   { &setup.internal.info_exit,                  execExitInfo                    },
7903
7904   { NULL,                                       NULL                            }
7905 };
7906
7907 void setHideRelatedSetupEntries(void)
7908 {
7909   int i;
7910
7911   for (i = 0; hide_related_entry_list[i].value != NULL; i++)
7912     if (hideSetupEntry(hide_related_entry_list[i].value))
7913       setHideSetupEntry(hide_related_entry_list[i].related_value);
7914 }
7915
7916 static struct TokenInfo setup_info_main[] =
7917 {
7918   { TYPE_ENTER_MENU,    execSetupGame,                  STR_SETUP_GAME                  },
7919   { TYPE_ENTER_MENU,    execSetupEngines,               STR_SETUP_ENGINES               },
7920   { TYPE_ENTER_MENU,    execSetupEditor,                STR_SETUP_EDITOR                },
7921   { TYPE_ENTER_MENU,    execSetupGraphics,              STR_SETUP_GRAPHICS              },
7922   { TYPE_ENTER_MENU,    execSetupSound,                 STR_SETUP_SOUND                 },
7923   { TYPE_ENTER_MENU,    execSetupArtwork,               STR_SETUP_ARTWORK               },
7924   { TYPE_ENTER_MENU,    execSetupInput,                 STR_SETUP_INPUT                 },
7925   { TYPE_ENTER_MENU,    execSetupTouch,                 STR_SETUP_TOUCH                 },
7926   { TYPE_ENTER_MENU,    execSetupShortcuts,             STR_SETUP_SHORTCUTS             },
7927   { TYPE_EMPTY,         NULL,                           ""                              },
7928   { TYPE_LEAVE_MENU,    execExitSetup,                  STR_SETUP_EXIT                  },
7929   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,           STR_SETUP_SAVE_AND_EXIT         },
7930
7931   { 0,                  NULL,                           NULL                            }
7932 };
7933
7934 static struct TokenInfo setup_info_game[] =
7935 {
7936   { TYPE_SWITCH,        &setup.team_mode,               "Team-Mode (Multi-Player):"     },
7937   { TYPE_SWITCH,        &setup.network_mode,            "Network Multi-Player Mode:"    },
7938   { TYPE_PLAYER,        &setup.network_player_nr,       "Preferred Network Player:"     },
7939   { TYPE_TEXT_INPUT,    execGadgetNetworkServer,        "Network Server Hostname:"      },
7940   { TYPE_STRING,        &network_server_text,           ""                              },
7941   { TYPE_SWITCH,        &setup.use_api_server,          "Use Highscore Server:"         },
7942   { TYPE_ENTER_LIST,    execSetupChooseScoresType,      "Scores in Highscore List:"     },
7943   { TYPE_STRING,        &scores_type_text,              ""                              },
7944   { TYPE_ENTER_LIST,    execOfferUploadTapes,           "Upload Tapes to Server"        },
7945   { TYPE_SWITCH,        &setup.multiple_users,          "Multiple Users/Teams:"         },
7946   { TYPE_YES_NO,        &setup.input_on_focus,          "Only Move Focussed Player:"    },
7947   { TYPE_SWITCH,        &setup.time_limit,              "Time Limit:"                   },
7948   { TYPE_SWITCH,        &setup.handicap,                "Force Solving Levels:"         },
7949   { TYPE_SWITCH,        &setup.skip_levels,             "Allow Skipping Levels:"        },
7950   { TYPE_SWITCH,        &setup.increment_levels,        "Increment Solved Levels:"      },
7951   { TYPE_SWITCH,        &setup.auto_play_next_level,    "Auto-play Next Level:"         },
7952   { TYPE_SWITCH,        &setup.count_score_after_game,  "Count Score After Game:"       },
7953   { TYPE_SWITCH,        &setup.show_scores_after_game,  "Show Scores After Game:"       },
7954   { TYPE_YES_NO,        &setup.ask_on_game_over,        "Ask on Game Over:"             },
7955   { TYPE_YES_NO,        &setup.ask_on_quit_game,        "Ask on Quit Game:"             },
7956   { TYPE_YES_NO,        &setup.ask_on_quit_program,     "Ask on Quit Program:"          },
7957   { TYPE_SWITCH,        &setup.autorecord,              "Auto-Record When Playing:"     },
7958   { TYPE_SWITCH,        &setup.autorecord_after_replay, "Auto-Record After Replay:"     },
7959   { TYPE_SWITCH,        &setup.auto_pause_on_start,     "Start Game in Pause Mode:"     },
7960   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed,       "Game Speed:"                   },
7961   { TYPE_STRING,        &game_speed_text,               ""                              },
7962   { TYPE_SWITCH,        &setup.game_speed_extended,     "Game Speed Extended List:"     },
7963 #if 1
7964   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay,     "Scroll Delay:"                 },
7965   { TYPE_STRING,        &scroll_delay_text,             ""                              },
7966 #endif
7967   { TYPE_ENTER_LIST,    execSetupChooseSnapshotMode,    "Game Engine Snapshot Mode:"    },
7968   { TYPE_STRING,        &snapshot_mode_text,            ""                              },
7969   { TYPE_SWITCH,        &setup.show_load_save_buttons,  "Show Load/Save Buttons:"       },
7970   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,  "Show Undo/Redo Buttons:"       },
7971   { TYPE_EMPTY,         NULL,                           ""                              },
7972   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
7973
7974   { 0,                  NULL,                           NULL                            }
7975 };
7976
7977 static struct TokenInfo setup_info_engines[] =
7978 {
7979   { TYPE_ENTER_LIST,    &execSetupChooseGameEngineType, "Default Game Engine:"          },
7980   { TYPE_STRING,        &game_engine_type_text,         ""                              },
7981   { TYPE_EMPTY,         NULL,                           ""                              },
7982   { TYPE_HEADLINE,      NULL,                           "Boulder Dash"                  },
7983   { TYPE_SWITCH,        &setup.bd_skip_uncovering,      "Skip (un)covering screen:"     },
7984   { TYPE_SWITCH,        &setup.bd_skip_hatching,        "Skip hatching player:"         },
7985   { TYPE_SWITCH,        &setup.bd_scroll_delay,         "Scroll Delay:"                 },
7986   { TYPE_YES_NO_AUTO,   &setup.bd_smooth_movements,     "Smooth Element Movement:"      },
7987   { TYPE_YES_NO_AUTO,   &setup.bd_pushing_graphics,     "Use Player Pushing Graphics:"  },
7988   { TYPE_YES_NO_AUTO,   &setup.bd_up_down_graphics,     "Use Player Up/Down Graphics:"  },
7989   { TYPE_YES_NO_AUTO,   &setup.bd_skip_falling_sounds,  "Mute Double Falling Sounds:"   },
7990   { TYPE_SWITCH,        &setup.bd_show_invisible_outbox,"Show invisible outbox:"        },
7991   { TYPE_ENTER_LIST,    &execSetupChoosePaletteC64,     "Color Palette (C64):"          },
7992   { TYPE_STRING,        &bd_palette_c64_text,           ""                              },
7993   { TYPE_ENTER_LIST,    &execSetupChoosePaletteC64DTV,  "Color Palette (C64DTV):"       },
7994   { TYPE_STRING,        &bd_palette_c64dtv_text,        ""                              },
7995   { TYPE_ENTER_LIST,    &execSetupChoosePaletteAtari,   "Color Palette (Atari):"        },
7996   { TYPE_STRING,        &bd_palette_atari_text,         ""                              },
7997   { TYPE_ENTER_LIST,    &execSetupChooseColorType,      "Preferred Color Type:"         },
7998   { TYPE_STRING,        &bd_color_type_text,            ""                              },
7999   { TYPE_SWITCH,        &setup.bd_random_colors,        "Random Colors:"                },
8000   { TYPE_EMPTY,         NULL,                           ""                              },
8001   { TYPE_HEADLINE,      NULL,                           "Emerald Mine"                  },
8002   { TYPE_SWITCH,        &setup.forced_scroll_delay,     "Scroll Delay:"                 },
8003   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics,     "Amiga Graphics Chipset:"       },
8004   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,   "Low-Pass Filter Sounds:"       },
8005   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:"       },
8006   { TYPE_EMPTY,         NULL,                           ""                              },
8007   { TYPE_HEADLINE,      NULL,                           "Supaplex"                      },
8008   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:"              },
8009   { TYPE_EMPTY,         NULL,                           ""                              },
8010   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8011
8012   { 0,                  NULL,                           NULL                            }
8013 };
8014
8015 static struct TokenInfo setup_info_editor[] =
8016 {
8017 #if 0
8018   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:"                 },
8019   { TYPE_SWITCH,        &setup.editor.el_boulderdash_native, "Boulder Dash Native:"     },
8020   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:"                 },
8021   { TYPE_SWITCH,        &setup.editor.el_emerald_mine_club, "Emerald Mine Club:"        },
8022   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:"             },
8023   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"                      },
8024   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"                     },
8025   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:"             },
8026   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:"               },
8027   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:"              },
8028   { TYPE_SWITCH,        &setup.editor.el_steel_chars,   "Text Characters (Steel):"      },
8029 #endif
8030   { TYPE_SWITCH,        &setup.editor.el_classic,       "Classic Elements:"             },
8031   { TYPE_SWITCH,        &setup.editor.el_custom,        "Custom & Group Elements:"      },
8032 #if 0
8033   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"                    },
8034 #endif
8035   { TYPE_SWITCH, &setup.editor.el_user_defined,         "User defined element list:"    },
8036   { TYPE_SWITCH,        &setup.editor.el_dynamic,       "Dynamic level elements:"       },
8037   { TYPE_EMPTY,         NULL,                           ""                              },
8038 #if 0
8039   { TYPE_SWITCH,        &setup.editor.el_by_game,       "Show elements by game:"        },
8040   { TYPE_SWITCH,        &setup.editor.el_by_type,       "Show elements by type:"        },
8041   { TYPE_EMPTY,         NULL,                           ""                              },
8042 #endif
8043   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:"           },
8044   { TYPE_EMPTY,         NULL,                           ""                              },
8045   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:"       },
8046   { TYPE_EMPTY,         NULL,                           ""                              },
8047   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8048
8049   { 0,                  NULL,                           NULL                            }
8050 };
8051
8052 static struct TokenInfo setup_info_graphics[] =
8053 {
8054 #if !defined(PLATFORM_ANDROID) && !defined(PLATFORM_EMSCRIPTEN)
8055   { TYPE_SWITCH,        &setup.fullscreen,              "Fullscreen:"                   },
8056   { TYPE_ENTER_LIST,    execSetupChooseWindowSize,      "Window Scaling:"               },
8057   { TYPE_STRING,        &window_size_text,              ""                              },
8058   { TYPE_ENTER_LIST,    execSetupChooseScalingType,     "Anti-Aliasing:"                },
8059   { TYPE_STRING,        &scaling_type_text,             ""                              },
8060   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode,   "Special Rendering:"            },
8061   { TYPE_STRING,        &rendering_mode_text,           ""                              },
8062 #endif
8063 #if 0
8064   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay,     "Scroll Delay:"                 },
8065   { TYPE_STRING,        &scroll_delay_text,             ""                              },
8066 #endif
8067 #if !defined(PLATFORM_EMSCRIPTEN)
8068   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode,       "Vertical Sync (VSync):"        },
8069   { TYPE_STRING,        &vsync_mode_text,               ""                              },
8070 #endif
8071   { TYPE_SWITCH,        &setup.fade_screens,            "Fade Screens:"                 },
8072   { TYPE_SWITCH,        &setup.quick_switch,            "Quick Player Focus Switch:"    },
8073   { TYPE_SWITCH,        &setup.quick_doors,             "Quick Menu Doors:"             },
8074   { TYPE_SWITCH,        &setup.show_titlescreen,        "Show Title Screens:"           },
8075   { TYPE_SWITCH,        &setup.toons,                   "Show Toons:"                   },
8076   { TYPE_SWITCH,        &setup.small_game_graphics,     "Small Game Graphics:"          },
8077   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,          debug_xsn_mode                  },
8078   { TYPE_EMPTY,         NULL,                           ""                              },
8079   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8080
8081   { 0,                  NULL,                           NULL                            }
8082 };
8083
8084 static struct TokenInfo setup_info_sound[] =
8085 {
8086   { TYPE_SWITCH,        &setup.sound_simple,            "Sound Effects (Normal):"       },
8087   { TYPE_SWITCH,        &setup.sound_loops,             "Sound Effects (Looping):"      },
8088   { TYPE_SWITCH,        &setup.sound_music,             "Music:"                        },
8089   { TYPE_EMPTY,         NULL,                           ""                              },
8090   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple,    "Sound Volume (Normal):"        },
8091   { TYPE_STRING,        &volume_simple_text,            ""                              },
8092   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops,     "Sound Volume (Looping):"       },
8093   { TYPE_STRING,        &volume_loops_text,             ""                              },
8094   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic,     "Music Volume:"                 },
8095   { TYPE_STRING,        &volume_music_text,             ""                              },
8096   { TYPE_EMPTY,         NULL,                           ""                              },
8097   { TYPE_SWITCH,        &setup.audio_sample_rate_44100, "44100 Hz audio mixing:"        },
8098   { TYPE_EMPTY,         NULL,                           ""                              },
8099   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8100
8101   { 0,                  NULL,                           NULL                            }
8102 };
8103
8104 static struct TokenInfo setup_info_artwork[] =
8105 {
8106   { TYPE_ENTER_LIST,    execSetupChooseGraphics,        "Custom Graphics:"              },
8107   { TYPE_STRING,        &graphics_set_name,             ""                              },
8108   { TYPE_ENTER_LIST,    execSetupChooseSounds,          "Custom Sounds:"                },
8109   { TYPE_STRING,        &sounds_set_name,               ""                              },
8110   { TYPE_ENTER_LIST,    execSetupChooseMusic,           "Custom Music:"                 },
8111   { TYPE_STRING,        &music_set_name,                ""                              },
8112   { TYPE_EMPTY,         NULL,                           ""                              },
8113   { TYPE_YES_NO_AUTO,   &setup.override_level_graphics,"Override Level Graphics:"       },
8114   { TYPE_YES_NO_AUTO,   &setup.override_level_sounds,   "Override Level Sounds:"        },
8115   { TYPE_YES_NO_AUTO,   &setup.override_level_music,    "Override Level Music:"         },
8116   { TYPE_EMPTY,         NULL,                           ""                              },
8117   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8118
8119   { 0,                  NULL,                           NULL                            }
8120 };
8121
8122 static struct TokenInfo setup_info_input[] =
8123 {
8124   { TYPE_SWITCH,        NULL,                           "Player:"                       },
8125   { TYPE_SWITCH,        NULL,                           "Device:"                       },
8126   { TYPE_SWITCH,        NULL,                           ""                              },
8127   { TYPE_SKIPPABLE,     NULL,                           ""                              },
8128   { TYPE_EMPTY,         NULL,                           ""                              },
8129   { TYPE_EMPTY,         NULL,                           ""                              },
8130   { TYPE_EMPTY,         NULL,                           ""                              },
8131   { TYPE_EMPTY,         NULL,                           ""                              },
8132   { TYPE_EMPTY,         NULL,                           ""                              },
8133   { TYPE_EMPTY,         NULL,                           ""                              },
8134   { TYPE_EMPTY,         NULL,                           ""                              },
8135   { TYPE_EMPTY,         NULL,                           ""                              },
8136   { TYPE_SKIPPABLE,     NULL,                           ""                              },
8137   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8138
8139   { 0,                  NULL,                           NULL                            }
8140 };
8141
8142 static struct TokenInfo setup_info_touch[] =
8143 {
8144   { TYPE_ENTER_LIST,    execSetupChooseTouchControls,   "Touch Control Type:"           },
8145   { TYPE_STRING,        &touch_controls_text,           ""                              },
8146   { TYPE_EMPTY,         NULL,                           ""                              },
8147   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8148
8149   { 0,                  NULL,                           NULL                            }
8150 };
8151
8152 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
8153 {
8154   { TYPE_ENTER_LIST,    execSetupChooseTouchControls,   "Touch Control Type:"           },
8155   { TYPE_STRING,        &touch_controls_text,           ""                              },
8156   { TYPE_EMPTY,         NULL,                           ""                              },
8157   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0,     "Horizontal Buttons (Landscape):" },
8158   { TYPE_STRING,        &grid_size_text[0][0],          ""                              },
8159   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0,     "Vertical Buttons (Landscape):" },
8160   { TYPE_STRING,        &grid_size_text[0][1],          ""                              },
8161   { TYPE_ENTER_LIST,    execSetupChooseTransparency,    "Button Transparency:"          },
8162   { TYPE_STRING,        &transparency_text,             ""                              },
8163   { TYPE_SWITCH,        &setup.touch.draw_outlined,     "Draw Buttons Outlined:"        },
8164   { TYPE_SWITCH,        &setup.touch.draw_pressed,      "Highlight Pressed Buttons:"    },
8165   { TYPE_EMPTY,         NULL,                           ""                              },
8166   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons"   },
8167   { TYPE_EMPTY,         NULL,                           ""                              },
8168   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8169
8170   { 0,                  NULL,                           NULL                            }
8171 };
8172
8173 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
8174 {
8175   { TYPE_ENTER_LIST,    execSetupChooseTouchControls,   "Touch Control Type:"           },
8176   { TYPE_STRING,        &touch_controls_text,           ""                              },
8177   { TYPE_EMPTY,         NULL,                           ""                              },
8178   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1,     "Horizontal Buttons (Portrait):" },
8179   { TYPE_STRING,        &grid_size_text[1][0],          ""                              },
8180   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1,     "Vertical Buttons (Portrait):"  },
8181   { TYPE_STRING,        &grid_size_text[1][1],          ""                              },
8182   { TYPE_ENTER_LIST,    execSetupChooseTransparency,    "Button Transparency:"          },
8183   { TYPE_STRING,        &transparency_text,             ""                              },
8184   { TYPE_SWITCH,        &setup.touch.draw_outlined,     "Draw Buttons Outlined:"        },
8185   { TYPE_SWITCH,        &setup.touch.draw_pressed,      "Highlight Pressed Buttons:"    },
8186   { TYPE_EMPTY,         NULL,                           ""                              },
8187   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons"   },
8188   { TYPE_EMPTY,         NULL,                           ""                              },
8189   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8190
8191   { 0,                  NULL,                           NULL                            }
8192 };
8193
8194 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
8195 {
8196   setup_info_touch_virtual_buttons_0,
8197   setup_info_touch_virtual_buttons_1
8198 };
8199
8200 static struct TokenInfo setup_info_touch_wipe_gestures[] =
8201 {
8202   { TYPE_ENTER_LIST,    execSetupChooseTouchControls,   "Touch Control Type:"           },
8203   { TYPE_STRING,        &touch_controls_text,           ""                              },
8204   { TYPE_EMPTY,         NULL,                           ""                              },
8205   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance,    "Move Trigger Distance:"        },
8206   { TYPE_STRING,        &move_distance_text,            ""                              },
8207   { TYPE_ENTER_LIST,    execSetupChooseDropDistance,    "Drop Trigger Distance:"        },
8208   { TYPE_STRING,        &drop_distance_text,            ""                              },
8209   { TYPE_EMPTY,         NULL,                           ""                              },
8210   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8211
8212   { 0,                  NULL,                           NULL                            }
8213 };
8214
8215 static struct TokenInfo setup_info_shortcuts[] =
8216 {
8217   { TYPE_ENTER_MENU,    execSetupShortcuts1,            "Various Keys"                  },
8218   { TYPE_ENTER_MENU,    execSetupShortcuts2,            "Player Focus"                  },
8219   { TYPE_ENTER_MENU,    execSetupShortcuts3,            "Tape Buttons"                  },
8220   { TYPE_ENTER_MENU,    execSetupShortcuts4,            "Sound & Music"                 },
8221   { TYPE_ENTER_MENU,    execSetupShortcuts5,            "TAS Snap Keys"                 },
8222   { TYPE_ENTER_MENU,    execSetupShortcuts6,            "Speed Keys"                    },
8223   { TYPE_EMPTY,         NULL,                           ""                              },
8224   { TYPE_LEAVE_MENU,    execSetupMain,                  "Back"                          },
8225
8226   { 0,                  NULL,                           NULL                            }
8227 };
8228
8229 static struct TokenInfo setup_info_shortcuts_1[] =
8230 {
8231   { TYPE_KEYTEXT,       NULL,                           "Quick Save Game to Tape:"      },
8232   { TYPE_KEY,           &setup.shortcut.save_game,      ""                              },
8233   { TYPE_KEYTEXT,       NULL,                           "Quick Load Game from Tape:"    },
8234   { TYPE_KEY,           &setup.shortcut.load_game,      ""                              },
8235   { TYPE_KEYTEXT,       NULL,                           "Restart Game:"                 },
8236   { TYPE_KEY,           &setup.shortcut.restart_game,   ""                              },
8237   { TYPE_KEYTEXT,       NULL,                           "Replay & Pause Before End:"    },
8238   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""                            },
8239   { TYPE_KEYTEXT,       NULL,                           "Start Game & Toggle Pause:"    },
8240   { TYPE_KEY,           &setup.shortcut.toggle_pause,   ""                              },
8241   { TYPE_EMPTY,         NULL,                           ""                              },
8242   { TYPE_YES_NO,        &setup.ask_on_escape,           "Ask on 'Esc' Key:"             },
8243   { TYPE_YES_NO, &setup.ask_on_escape_editor,           "Ask on 'Esc' Key (Editor):"    },
8244   { TYPE_EMPTY,         NULL,                           ""                              },
8245   { TYPE_LEAVE_MENU,    execSetupShortcuts,             "Back"                          },
8246
8247   { 0,                  NULL,                           NULL                            }
8248 };
8249
8250 static struct TokenInfo setup_info_shortcuts_2[] =
8251 {
8252   { TYPE_KEYTEXT,       NULL,                           "Set Focus to Player 1:"        },
8253   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""                             },
8254   { TYPE_KEYTEXT,       NULL,                           "Set Focus to Player 2:"        },
8255   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""                             },
8256   { TYPE_KEYTEXT,       NULL,                           "Set Focus to Player 3:"        },
8257   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""                             },
8258   { TYPE_KEYTEXT,       NULL,                           "Set Focus to Player 4:"        },
8259   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""                             },
8260   { TYPE_KEYTEXT,       NULL,                           "Set Focus to All Players:"     },
8261   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""                            },
8262   { TYPE_EMPTY,         NULL,                           ""                              },
8263   { TYPE_LEAVE_MENU,    execSetupShortcuts,             "Back"                          },
8264
8265   { 0,                  NULL,                           NULL                            }
8266 };
8267
8268 static struct TokenInfo setup_info_shortcuts_3[] =
8269 {
8270   { TYPE_KEYTEXT,       NULL,                           "Eject Tape:"                   },
8271   { TYPE_KEY,           &setup.shortcut.tape_eject,     ""                              },
8272   { TYPE_KEYTEXT,       NULL,                           "Warp / Single Step:"           },
8273   { TYPE_KEY,           &setup.shortcut.tape_extra,     ""                              },
8274   { TYPE_KEYTEXT,       NULL,                           "Stop Tape:"                    },
8275   { TYPE_KEY,           &setup.shortcut.tape_stop,      ""                              },
8276   { TYPE_KEYTEXT,       NULL,                           "Pause / Unpause Tape:"         },
8277   { TYPE_KEY,           &setup.shortcut.tape_pause,     ""                              },
8278   { TYPE_KEYTEXT,       NULL,                           "Record Tape:"                  },
8279   { TYPE_KEY,           &setup.shortcut.tape_record,    ""                              },
8280   { TYPE_KEYTEXT,       NULL,                           "Play Tape:"                    },
8281   { TYPE_KEY,           &setup.shortcut.tape_play,      ""                              },
8282   { TYPE_EMPTY,         NULL,                           ""                              },
8283   { TYPE_LEAVE_MENU,    execSetupShortcuts,             "Back"                          },
8284
8285   { 0,                  NULL,                           NULL                            }
8286 };
8287
8288 static struct TokenInfo setup_info_shortcuts_4[] =
8289 {
8290   { TYPE_KEYTEXT,       NULL,                           "Toggle Sound Effects (Normal):" },
8291   { TYPE_KEY,           &setup.shortcut.sound_simple,   ""                              },
8292   { TYPE_KEYTEXT,       NULL,                           "Toggle Sound Effects (Looping):" },
8293   { TYPE_KEY,           &setup.shortcut.sound_loops,    ""                              },
8294   { TYPE_KEYTEXT,       NULL,                           "Toggle Music:"                 },
8295   { TYPE_KEY,           &setup.shortcut.sound_music,    ""                              },
8296   { TYPE_EMPTY,         NULL,                           ""                              },
8297   { TYPE_LEAVE_MENU,    execSetupShortcuts,             "Back"                          },
8298
8299   { 0,                  NULL,                           NULL                            }
8300 };
8301
8302 static struct TokenInfo setup_info_shortcuts_5[] =
8303 {
8304   { TYPE_KEYTEXT,       NULL,                           "Snap Left:"                    },
8305   { TYPE_KEY,           &setup.shortcut.snap_left,      ""                              },
8306   { TYPE_KEYTEXT,       NULL,                           "Snap Right:"                   },
8307   { TYPE_KEY,           &setup.shortcut.snap_right,     ""                              },
8308   { TYPE_KEYTEXT,       NULL,                           "Snap Up:"                      },
8309   { TYPE_KEY,           &setup.shortcut.snap_up,        ""                              },
8310   { TYPE_KEYTEXT,       NULL,                           "Snap Down:"                    },
8311   { TYPE_KEY,           &setup.shortcut.snap_down,      ""                              },
8312   { TYPE_EMPTY,         NULL,                           ""                              },
8313   { TYPE_LEAVE_MENU,    execSetupShortcuts,             "Back"                          },
8314
8315   { 0,                  NULL,                           NULL                            }
8316 };
8317
8318 static struct TokenInfo setup_info_shortcuts_6[] =
8319 {
8320   { TYPE_KEYTEXT,       NULL,                           "Fast Playing Speed:"           },
8321   { TYPE_KEY,           &setup.shortcut.speed_fast,     ""                              },
8322   { TYPE_KEYTEXT,       NULL,                           "Slow Playing Speed:"           },
8323   { TYPE_KEY,           &setup.shortcut.speed_slow,     ""                              },
8324   { TYPE_EMPTY,         NULL,                           ""                              },
8325   { TYPE_LEAVE_MENU,    execSetupShortcuts,             "Back"                          },
8326
8327   { 0,                  NULL,                           NULL                            }
8328 };
8329
8330 static Key getSetupKey(void)
8331 {
8332   Key key = KSYM_UNDEFINED;
8333   boolean got_key_event = FALSE;
8334
8335   while (!got_key_event)
8336   {
8337     Event event;
8338
8339     if (NextValidEvent(&event))
8340     {
8341       switch (event.type)
8342       {
8343         case EVENT_KEYPRESS:
8344           {
8345             key = GetEventKey((KeyEvent *)&event);
8346
8347             // press 'Escape' or 'Enter' to keep the existing key binding
8348             if (key == KSYM_Escape || key == KSYM_Return)
8349               key = KSYM_UNDEFINED;     // keep old value
8350
8351             got_key_event = TRUE;
8352           }
8353           break;
8354
8355         case EVENT_KEYRELEASE:
8356           key_joystick_mapping = 0;
8357           break;
8358
8359         default:
8360           HandleOtherEvents(&event);
8361           break;
8362       }
8363     }
8364
8365     BackToFront();
8366   }
8367
8368   return key;
8369 }
8370
8371 static int getSetupValueFont(int type, void *value)
8372 {
8373   if (type & TYPE_GHOSTED)
8374     return FONT_OPTION_OFF;
8375   else if (type & TYPE_KEY)
8376     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
8377   else if (type & TYPE_STRING)
8378     return FONT_VALUE_2;
8379   else if (type & TYPE_ECS_AGA)
8380     return FONT_VALUE_1;
8381   else if (type & TYPE_BOOLEAN_STYLE)
8382     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
8383   else if (type & TYPE_YES_NO_AUTO)
8384     return (*(int *)value == MODE_AUTO  ? FONT_OPTION_ON :
8385             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
8386   else if (type & TYPE_YES_NO_ASK)
8387     return (*(int *)value == MODE_ASK  ? FONT_OPTION_ON :
8388             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
8389   else if (type & TYPE_PLAYER)
8390     return FONT_VALUE_1;
8391   else
8392     return FONT_VALUE_1;
8393 }
8394
8395 static int getSetupValueFontNarrow(int type, int font_nr)
8396 {
8397   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
8398           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
8399           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
8400           font_nr);
8401 }
8402
8403 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
8404 {
8405   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
8406   struct TokenInfo *si = &setup_info[si_pos];
8407   boolean font_draw_xoffset_modified = FALSE;
8408   boolean scrollbar_needed = (num_setup_info < max_setup_info);
8409   int mx_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x;
8410   int mx_right_border = (scrollbar_needed ? mx_scrollbar : SX + SXSIZE);
8411   int font_draw_xoffset_old = -1;
8412   int xoffset = (scrollbar_needed ? 0 : 1);
8413   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
8414   int xpos = menu_screen_value_xpos;
8415   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
8416   int startx = mSX + xpos * 32;
8417   int starty = mSY + ypos * 32;
8418   int type = si->type;
8419   void *value = si->value;
8420   char *value_string = getSetupValue(type, value);
8421   int font_nr_default = getSetupValueFont(type, value);
8422   int font_width_default = getFontWidth(font_nr_default);
8423   int font_nr = font_nr_default;
8424
8425   if (value_string == NULL)
8426     return;
8427
8428   if (type & TYPE_KEY)
8429   {
8430     xpos = MENU_SCREEN_START_XPOS;
8431
8432     if (type & TYPE_QUERY)
8433       value_string = "<press key>";
8434   }
8435   else if (type & TYPE_STRING)
8436   {
8437     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
8438
8439     xpos = MENU_SCREEN_START_XPOS;
8440
8441     if (strlen(value_string) > max_value_len)
8442       value_string[max_value_len] = '\0';
8443   }
8444   else if (type & TYPE_PLAYER)
8445   {
8446     int displayed_player_nr = *(int *)value + 1;
8447
8448     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
8449   }
8450
8451   startx = mSX + xpos * 32;
8452   starty = mSY + ypos * 32;
8453
8454   // always use narrow font for setup values on right screen side
8455   if (xpos > MENU_SCREEN_START_XPOS)
8456     font_nr = getSetupValueFontNarrow(type, font_nr);
8457
8458   // downward compatibility correction for Juergen Bonhagen's menu settings
8459   if (setup_mode != SETUP_MODE_INPUT)
8460   {
8461     int max_menu_text_length_big = (menu_screen_value_xpos -
8462                                     MENU_SCREEN_START_XPOS);
8463     int max_menu_text_length_medium = max_menu_text_length_big * 2;
8464     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
8465     int font1_xoffset = getFontDrawOffsetX(font_nr);
8466     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
8467     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8468     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8469     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8470     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
8471     boolean correct_font_draw_xoffset = FALSE;
8472
8473     if (xpos == MENU_SCREEN_START_XPOS &&
8474         startx + font1_xoffset < text_startx + text_font_xoffset)
8475       correct_font_draw_xoffset = TRUE;
8476
8477     if (xpos == menu_screen_value_xpos &&
8478         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
8479       correct_font_draw_xoffset = TRUE;
8480
8481     // check if setup value would overlap with setup text when printed
8482     // (this can happen for extreme/wrong values for font draw offset)
8483     if (correct_font_draw_xoffset)
8484     {
8485       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
8486       font_draw_xoffset_modified = TRUE;
8487
8488       if (type & TYPE_KEY)
8489         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
8490       else if (!(type & TYPE_STRING))
8491         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
8492           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
8493     }
8494   }
8495
8496   DrawBackground(startx, starty, mx_right_border - startx, getFontHeight(font_nr));
8497   DrawText(startx, starty, value_string, font_nr);
8498
8499   if (type & TYPE_PLAYER)
8500   {
8501     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
8502     int player_nr = *(int *)value;
8503     int xoff = font->draw_xoffset + getFontWidth(font_nr);
8504     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
8505     int startx2 = startx + xoff;
8506     int starty2 = starty + yoff;
8507
8508     if (DrawingOnBackground(startx2, starty2))
8509       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
8510
8511     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
8512                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8513   }
8514
8515   if (font_draw_xoffset_modified)
8516     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
8517 }
8518
8519 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
8520 {
8521   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
8522   struct TokenInfo *si = &setup_info[si_pos];
8523
8524   if (si->type & TYPE_BOOLEAN_STYLE)
8525   {
8526     *(boolean *)si->value ^= TRUE;
8527   }
8528   else if (si->type & TYPE_YES_NO_AUTO)
8529   {
8530     *(int *)si->value =
8531       (dx == -1 ?
8532        (*(int *)si->value == MODE_AUTO ? TRUE :
8533         *(int *)si->value == TRUE ? FALSE : MODE_AUTO) :
8534        (*(int *)si->value == TRUE ? MODE_AUTO :
8535         *(int *)si->value == MODE_AUTO ? FALSE : TRUE));
8536   }
8537   else if (si->type & TYPE_YES_NO_ASK)
8538   {
8539     *(int *)si->value =
8540       (dx == -1 ?
8541        (*(int *)si->value == MODE_ASK ? TRUE :
8542         *(int *)si->value == TRUE ? FALSE : MODE_ASK) :
8543        (*(int *)si->value == TRUE ? MODE_ASK :
8544         *(int *)si->value == MODE_ASK ? FALSE : TRUE));
8545   }
8546   else if (si->type & TYPE_KEY)
8547   {
8548     Key key;
8549
8550     si->type |= TYPE_QUERY;
8551     drawSetupValue(screen_pos, setup_info_pos_raw);
8552     si->type &= ~TYPE_QUERY;
8553
8554     key = getSetupKey();
8555     if (key != KSYM_UNDEFINED)
8556       *(Key *)si->value = key;
8557   }
8558   else if (si->type & TYPE_PLAYER)
8559   {
8560     int player_nr = *(int *)si->value;
8561
8562     if (dx)
8563       player_nr += dx;
8564     else
8565       player_nr = Request("Choose player", REQ_PLAYER) - 1;
8566
8567     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
8568   }
8569
8570   drawSetupValue(screen_pos, setup_info_pos_raw);
8571
8572   // fullscreen state may have changed at this point
8573   if (si->value == &setup.fullscreen)
8574     ToggleFullscreenIfNeeded();
8575
8576   // audio sample rate may have changed at this point
8577   if (si->value == &setup.audio_sample_rate_44100)
8578     ToggleAudioSampleRateIfNeeded();
8579
8580   // network mode may have changed at this point
8581   if (si->value == &setup.network_mode)
8582     ToggleNetworkModeIfNeeded();
8583
8584   // API server mode may have changed at this point
8585   if (si->value == &setup.use_api_server)
8586     ToggleUseApiServerIfNeeded();
8587
8588   // game speed list may have changed at this point
8589   if (si->value == &setup.game_speed_extended)
8590     ToggleGameSpeedsListIfNeeded();
8591 }
8592
8593 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
8594 {
8595   static struct TokenInfo *setup_info_final = NULL;
8596   int list_size = 0;
8597   int list_pos = 0;
8598   int i;
8599
8600   // determine maximum list size of target list
8601   while (setup_info_orig[list_size++].type != 0);
8602
8603   // free, allocate and clear memory for target list
8604   checked_free(setup_info_final);
8605   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
8606
8607   // copy setup info list without setup entries marked as hidden
8608   for (i = 0; setup_info_orig[i].type != 0; i++)
8609   {
8610     // skip setup entries configured to be hidden
8611     if (hideSetupEntry(setup_info_orig[i].value))
8612       continue;
8613
8614     // skip skippable setup entries if screen is lower than usual
8615     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
8616         setup_info_orig[i].type == TYPE_SKIPPABLE)
8617       continue;
8618
8619     setup_info_final[list_pos++] = setup_info_orig[i];
8620   }
8621
8622   return setup_info_final;
8623 }
8624
8625 static void DrawSetupScreen_Generic(void)
8626 {
8627   int fade_mask = REDRAW_FIELD;
8628   boolean redraw_all = FALSE;
8629   char *title_string = NULL;
8630   int i;
8631
8632   if (CheckFadeAll())
8633     fade_mask = REDRAW_ALL;
8634
8635   UnmapAllGadgets();
8636   FadeMenuSoundsAndMusic();
8637
8638   FreeScreenGadgets();
8639   CreateScreenGadgets();
8640
8641   if (redraw_mask & REDRAW_ALL)
8642     redraw_all = TRUE;
8643
8644   FadeOut(fade_mask);
8645
8646   // needed if different viewport properties defined for setup screen
8647   ChangeViewportPropertiesIfNeeded();
8648
8649   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
8650
8651   ClearField();
8652
8653   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
8654
8655   if (setup_mode == SETUP_MODE_MAIN)
8656   {
8657     setup_info = setup_info_main;
8658     title_string = STR_SETUP_MAIN;
8659   }
8660   else if (setup_mode == SETUP_MODE_GAME)
8661   {
8662     setup_info = setup_info_game;
8663     title_string = STR_SETUP_GAME;
8664   }
8665   else if (setup_mode == SETUP_MODE_ENGINES)
8666   {
8667     setup_info = setup_info_engines;
8668     title_string = STR_SETUP_ENGINES;
8669   }
8670   else if (setup_mode == SETUP_MODE_EDITOR)
8671   {
8672     setup_info = setup_info_editor;
8673     title_string = STR_SETUP_EDITOR;
8674   }
8675   else if (setup_mode == SETUP_MODE_GRAPHICS)
8676   {
8677     setup_info = setup_info_graphics;
8678     title_string = STR_SETUP_GRAPHICS;
8679   }
8680   else if (setup_mode == SETUP_MODE_SOUND)
8681   {
8682     setup_info = setup_info_sound;
8683     title_string = STR_SETUP_SOUND;
8684   }
8685   else if (setup_mode == SETUP_MODE_ARTWORK)
8686   {
8687     setup_info = setup_info_artwork;
8688     title_string = STR_SETUP_ARTWORK;
8689   }
8690   else if (setup_mode == SETUP_MODE_TOUCH)
8691   {
8692     setup_info = setup_info_touch;
8693     title_string = STR_SETUP_TOUCH;
8694
8695     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
8696       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
8697     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
8698       setup_info = setup_info_touch_wipe_gestures;
8699   }
8700   else if (setup_mode == SETUP_MODE_SHORTCUTS)
8701   {
8702     setup_info = setup_info_shortcuts;
8703     title_string = STR_SETUP_SHORTCUTS;
8704   }
8705   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
8706   {
8707     setup_info = setup_info_shortcuts_1;
8708     title_string = STR_SETUP_SHORTCUTS;
8709   }
8710   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
8711   {
8712     setup_info = setup_info_shortcuts_2;
8713     title_string = STR_SETUP_SHORTCUTS;
8714   }
8715   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
8716   {
8717     setup_info = setup_info_shortcuts_3;
8718     title_string = STR_SETUP_SHORTCUTS;
8719   }
8720   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
8721   {
8722     setup_info = setup_info_shortcuts_4;
8723     title_string = STR_SETUP_SHORTCUTS;
8724   }
8725   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
8726   {
8727     setup_info = setup_info_shortcuts_5;
8728     title_string = STR_SETUP_SHORTCUTS;
8729   }
8730   else if (setup_mode == SETUP_MODE_SHORTCUTS_6)
8731   {
8732     setup_info = setup_info_shortcuts_6;
8733     title_string = STR_SETUP_SHORTCUTS;
8734   }
8735
8736   // use modified setup info without setup entries marked as hidden
8737   setup_info = getSetupInfoFinal(setup_info);
8738
8739   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
8740
8741   // determine maximal number of setup entries that can be displayed on screen
8742   num_setup_info = 0;
8743   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
8744     num_setup_info++;
8745
8746   // determine maximal number of setup entries available for this setup screen
8747   max_setup_info = 0;
8748   for (i = 0; setup_info[i].type != 0; i++)
8749     max_setup_info++;
8750
8751   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
8752
8753   MapScreenGadgets(max_setup_info);
8754
8755   if (redraw_all)
8756     redraw_mask = fade_mask = REDRAW_ALL;
8757
8758   DrawMaskedBorder(fade_mask);
8759
8760   FadeIn(fade_mask);
8761 }
8762
8763 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
8764 {
8765   menu_info = setup_info;
8766
8767   HandleMenuScreen(mx, my, dx, dy, button,
8768                    setup_mode, num_setup_info, max_setup_info);
8769 }
8770
8771 static void DrawSetupScreen_Input(void)
8772 {
8773   int i;
8774
8775   FadeOut(REDRAW_FIELD);
8776
8777   ClearField();
8778
8779   setup_info = getSetupInfoFinal(setup_info_input);
8780
8781   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
8782
8783   for (i = 0; setup_info[i].type != 0; i++)
8784   {
8785     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
8786       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
8787     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
8788       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
8789     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
8790       initCursor(i, IMG_MENU_BUTTON);
8791
8792     DrawCursorAndText_Setup(i, -1, FALSE);
8793   }
8794
8795   // create gadgets for setup input menu screen
8796   FreeScreenGadgets();
8797   CreateScreenGadgets();
8798
8799   // map gadgets for setup input menu screen
8800   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
8801
8802   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
8803
8804   FadeIn(REDRAW_FIELD);
8805 }
8806
8807 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8808 {
8809   if (device_name == NULL)
8810     return;
8811
8812   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8813     device_nr = 0;
8814
8815   if (strlen(device_name) > 1)
8816   {
8817     char c1 = device_name[strlen(device_name) - 1];
8818     char c2 = device_name[strlen(device_name) - 2];
8819
8820     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8821       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8822   }
8823   else
8824     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8825             strlen(device_name));
8826 }
8827
8828 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8829 {
8830   int i;
8831   static struct SetupKeyboardInfo custom_key;
8832   static struct
8833   {
8834     Key *key;
8835     char *text;
8836   } custom[] =
8837   {
8838     { &custom_key.left,  "Axis/Pad Left"  },
8839     { &custom_key.right, "Axis/Pad Right" },
8840     { &custom_key.up,    "Axis/Pad Up"    },
8841     { &custom_key.down,  "Axis/Pad Down"  },
8842     { &custom_key.snap,  "Button 1/A/X"   },
8843     { &custom_key.drop,  "Button 2/B/Y"   }
8844   };
8845   static char *joystick_name[MAX_PLAYERS] =
8846   {
8847     "Joystick1",
8848     "Joystick2",
8849     "Joystick3",
8850     "Joystick4"
8851   };
8852   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8853   int font_nr_info = FONT_MENU_1;
8854   int font_nr_name = FONT_VALUE_OLD;
8855   int font_nr_on   = FONT_VALUE_1;
8856   int font_nr_off  = FONT_VALUE_OLD;
8857   int pos = 4;
8858
8859   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8860   {
8861     font_nr_info = FONT_MENU_2;
8862     font_nr_on   = FONT_VALUE_NARROW;
8863     font_nr_off  = FONT_VALUE_OLD_NARROW;
8864   }
8865
8866   custom_key = setup.input[player_nr].key;
8867
8868   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8869            FONT_INPUT_1_ACTIVE);
8870
8871   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8872                              TILEX, TILEY);
8873   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8874                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8875
8876   if (setup.input[player_nr].use_joystick)
8877   {
8878     char *device_name = setup.input[player_nr].joy.device_name;
8879     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8880     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8881     char *text = joystick_name[joystick_nr];
8882     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8883
8884     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8885     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8886   }
8887   else
8888   {
8889     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8890     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8891   }
8892
8893   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8894     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8895   else
8896     pos = 3;
8897
8898   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8899   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8900   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8901   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8902
8903   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8904   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8905   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8906   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8907   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8908   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8909
8910   for (i = 0; i < 6; i++)
8911   {
8912     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8913
8914     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8915              "              ", font_nr_on);
8916     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8917              (setup.input[player_nr].use_joystick ?
8918               custom[i].text :
8919               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8920   }
8921 }
8922
8923 static int input_player_nr = 0;
8924
8925 static void HandleSetupScreen_Input_Player(int step, int direction)
8926 {
8927   int old_player_nr = input_player_nr;
8928   int new_player_nr;
8929
8930   new_player_nr = old_player_nr + step * direction;
8931   if (new_player_nr < 0)
8932     new_player_nr = 0;
8933   if (new_player_nr > MAX_PLAYERS - 1)
8934     new_player_nr = MAX_PLAYERS - 1;
8935
8936   if (new_player_nr != old_player_nr)
8937   {
8938     input_player_nr = new_player_nr;
8939
8940     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8941   }
8942 }
8943
8944 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8945 {
8946   static int choice = 0;
8947   int x = 0;
8948   int y = choice;
8949   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8950   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8951   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8952   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8953
8954   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8955   {
8956     int i;
8957
8958     for (i = 0; setup_info_input[i].type != 0; i++)
8959     {
8960       // adjust menu structure according to skipped setup entries
8961       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8962       {
8963         pos_empty2--;
8964         pos_end--;
8965       }
8966     }
8967   }
8968
8969   if (button == MB_MENU_INITIALIZE)
8970   {
8971     // input setup menu may have changed size due to graphics configuration
8972     if (choice >= pos_empty1)
8973       choice = pos_end;
8974
8975     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8976
8977     DrawCursorAndText_Setup(choice, -1, TRUE);
8978
8979     return;
8980   }
8981   else if (button == MB_MENU_LEAVE)
8982   {
8983     setup_mode = SETUP_MODE_MAIN;
8984     DrawSetupScreen();
8985     InitJoysticks();
8986
8987     return;
8988   }
8989
8990   if (mx || my)         // mouse input
8991   {
8992     x = (mx - mSX) / 32;
8993     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8994   }
8995   else if (dx || dy)    // keyboard input
8996   {
8997     if (dx && choice == 0)
8998       x = (dx < 0 ? 10 : 12);
8999     else if ((dx && choice == 1) ||
9000              (dx == -1 && choice == pos_end))
9001       button = MB_MENU_CHOICE;
9002     else if (dy)
9003       y = choice + dy;
9004
9005     if (y >= pos_empty1 && y <= pos_empty2)
9006       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
9007   }
9008
9009   if (y == 0 && dx != 0 && button)
9010   {
9011     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
9012   }
9013   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
9014            y >= pos_start && y <= pos_end &&
9015            !(y >= pos_empty1 && y <= pos_empty2))
9016   {
9017     if (button)
9018     {
9019       if (y != choice)
9020       {
9021         DrawCursorAndText_Setup(choice, -1, FALSE);
9022         DrawCursorAndText_Setup(y, -1, TRUE);
9023
9024         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
9025
9026         choice = y;
9027       }
9028     }
9029     else
9030     {
9031       if (y == 1)
9032       {
9033         char *device_name = setup.input[input_player_nr].joy.device_name;
9034
9035         if (!setup.input[input_player_nr].use_joystick)
9036         {
9037           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
9038
9039           setJoystickDeviceToNr(device_name, new_device_nr);
9040           setup.input[input_player_nr].use_joystick = TRUE;
9041         }
9042         else
9043         {
9044           int device_nr = getJoystickNrFromDeviceName(device_name);
9045           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
9046
9047           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
9048             setup.input[input_player_nr].use_joystick = FALSE;
9049           else
9050             setJoystickDeviceToNr(device_name, new_device_nr);
9051         }
9052
9053         drawPlayerSetupInputInfo(input_player_nr, FALSE);
9054       }
9055       else if (y == 2)
9056       {
9057         if (setup.input[input_player_nr].use_joystick)
9058           ConfigureJoystick(input_player_nr);
9059         else
9060           CustomizeKeyboard(input_player_nr);
9061       }
9062       else if (y == pos_end)
9063       {
9064         InitJoysticks();
9065
9066         FadeSetLeaveMenu();
9067
9068         setup_mode = SETUP_MODE_MAIN;
9069         DrawSetupScreen();
9070       }
9071     }
9072   }
9073 }
9074
9075 static boolean CustomizeKeyboardMain(int player_nr)
9076 {
9077   int i;
9078   int step_nr;
9079   boolean finished = FALSE;
9080   static struct SetupKeyboardInfo custom_key;
9081   static struct
9082   {
9083     Key *key;
9084     char *text;
9085   } customize_step[] =
9086   {
9087     { &custom_key.left,  "Move Left"    },
9088     { &custom_key.right, "Move Right"   },
9089     { &custom_key.up,    "Move Up"      },
9090     { &custom_key.down,  "Move Down"    },
9091     { &custom_key.snap,  "Snap Field"   },
9092     { &custom_key.drop,  "Drop Element" }
9093   };
9094   int font_nr_old = FONT_VALUE_OLD;
9095   int font_nr_new = FONT_VALUE_1;
9096   boolean success = FALSE;
9097
9098   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
9099   {
9100     font_nr_old = FONT_VALUE_OLD_NARROW;
9101     font_nr_new = FONT_VALUE_NARROW;
9102   }
9103
9104   // read existing key bindings from player setup
9105   custom_key = setup.input[player_nr].key;
9106
9107   FadeSetEnterMenu();
9108   FadeOut(REDRAW_FIELD);
9109
9110   ClearField();
9111
9112   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
9113
9114   step_nr = 0;
9115   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
9116            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
9117   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
9118            "Key:", FONT_INPUT_1_ACTIVE);
9119   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
9120            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
9121
9122   FadeIn(REDRAW_FIELD);
9123
9124   while (!finished)
9125   {
9126     Event event;
9127     DelayCounter event_frame_delay = { GAME_FRAME_DELAY };
9128
9129     // reset frame delay counter directly after updating screen
9130     ResetDelayCounter(&event_frame_delay);
9131
9132     while (NextValidEvent(&event))
9133     {
9134       switch (event.type)
9135       {
9136         case EVENT_KEYPRESS:
9137           {
9138             Key key = GetEventKey((KeyEvent *)&event);
9139
9140             // press 'Escape' to abort and keep the old key bindings
9141             if (key == KSYM_Escape)
9142             {
9143               FadeSkipNextFadeIn();
9144
9145               finished = TRUE;
9146
9147               break;
9148             }
9149
9150             // press 'Enter' to keep the existing key binding
9151             if (key == KSYM_Return)
9152               key = *customize_step[step_nr].key;
9153
9154             // check if key already used
9155             for (i = 0; i < step_nr; i++)
9156               if (*customize_step[i].key == key)
9157                 break;
9158             if (i < step_nr)
9159               break;
9160
9161             // got new key binding
9162             *customize_step[step_nr].key = key;
9163             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
9164                      "             ", font_nr_new);
9165             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
9166                      getKeyNameFromKey(key), font_nr_new);
9167             step_nr++;
9168
9169             // un-highlight last query
9170             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
9171                      customize_step[step_nr - 1].text, FONT_MENU_1);
9172             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
9173                      "Key:", FONT_MENU_1);
9174
9175             // all keys configured
9176             if (step_nr == 6)
9177             {
9178               finished = TRUE;
9179               success = TRUE;
9180
9181               break;
9182             }
9183
9184             // query next key binding
9185             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
9186                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
9187             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
9188                      "Key:", FONT_INPUT_1_ACTIVE);
9189             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
9190                      getKeyNameFromKey(*customize_step[step_nr].key),
9191                      font_nr_old);
9192           }
9193           break;
9194
9195         case EVENT_KEYRELEASE:
9196           key_joystick_mapping = 0;
9197           break;
9198
9199         default:
9200           HandleOtherEvents(&event);
9201           break;
9202       }
9203
9204       // do not handle events for longer than standard frame delay period
9205       if (DelayReached(&event_frame_delay))
9206         break;
9207     }
9208
9209     BackToFront();
9210   }
9211
9212   // write new key bindings back to player setup, if successfully finished
9213   if (success)
9214     setup.input[player_nr].key = custom_key;
9215
9216   return success;
9217 }
9218
9219 void CustomizeKeyboard(int player_nr)
9220 {
9221   boolean success = CustomizeKeyboardMain(player_nr);
9222
9223   if (success)
9224   {
9225     int font_nr = FONT_TITLE_1;
9226     int font_height = getFontHeight(font_nr);
9227     int ypos1 = SYSIZE / 2 - font_height * 2;
9228     int ypos2 = SYSIZE / 2 - font_height * 1;
9229     DelayCounter wait_frame_delay = { 2000 };
9230
9231     ResetDelayCounter(&wait_frame_delay);
9232
9233     ClearField();
9234
9235     DrawTextSCentered(ypos1, font_nr, "Keyboard");
9236     DrawTextSCentered(ypos2, font_nr, "configured!");
9237
9238     while (!DelayReached(&wait_frame_delay))
9239       BackToFront();
9240
9241     ClearEventQueue();
9242   }
9243
9244   DrawSetupScreen_Input();
9245 }
9246
9247 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
9248
9249 #define MARKER_BUTTON           1
9250 #define MARKER_AXIS_X           2
9251 #define MARKER_AXIS_Y           3
9252
9253 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
9254 {
9255   static boolean bitmaps_initialized = FALSE;
9256   boolean screen_initialized = FALSE;
9257   static Bitmap *controller, *button, *axis_x, *axis_y;
9258   char *name;
9259   boolean success = TRUE;
9260   boolean done = FALSE, next = FALSE;
9261   Event event;
9262   int alpha = 200, alpha_step = -1;
9263   int alpha_ticks = 0;
9264   char mapping[4096], temp[256];
9265   int font_name = MENU_SETUP_FONT_TITLE;
9266   int font_info = MENU_SETUP_FONT_TEXT;
9267   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
9268   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
9269   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
9270   int ystep_name = getMenuTextStep(spacing_name, font_name);
9271   int ystep_line = getMenuTextStep(spacing_line, font_info);
9272   int ystep_para = getMenuTextStep(spacing_para, font_info);
9273   int i, j;
9274
9275   struct
9276   {
9277     int x, y;
9278     int marker;
9279     char *field;
9280     int axis, button, hat, hat_value;
9281     char mapping[4096];
9282   }
9283   *step, *prev_step, steps[] =
9284   {
9285     { 356, 155, MARKER_BUTTON, "a",             },
9286     { 396, 122, MARKER_BUTTON, "b",             },
9287     { 320, 125, MARKER_BUTTON, "x",             },
9288     { 358,  95, MARKER_BUTTON, "y",             },
9289     { 162, 125, MARKER_BUTTON, "back",          },
9290     { 216, 125, MARKER_BUTTON, "guide",         },
9291     { 271, 125, MARKER_BUTTON, "start",         },
9292     { 110, 200, MARKER_BUTTON, "dpleft",        },
9293     { 146, 228, MARKER_BUTTON, "dpdown",        },
9294     { 178, 200, MARKER_BUTTON, "dpright",       },
9295     { 146, 172, MARKER_BUTTON, "dpup",          },
9296     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
9297     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
9298     { 382,  40, MARKER_BUTTON, "rightshoulder", },
9299     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
9300     {  73, 141, MARKER_BUTTON, "leftstick",     },
9301     { 282, 210, MARKER_BUTTON, "rightstick",    },
9302     {  73, 141, MARKER_AXIS_X, "leftx",         },
9303     {  73, 141, MARKER_AXIS_Y, "lefty",         },
9304     { 282, 210, MARKER_AXIS_X, "rightx",        },
9305     { 282, 210, MARKER_AXIS_Y, "righty",        },
9306   };
9307
9308   if (!bitmaps_initialized)
9309   {
9310     controller = LoadCustomImage("joystick/controller.png");
9311     button     = LoadCustomImage("joystick/button.png");
9312     axis_x     = LoadCustomImage("joystick/axis_x.png");
9313     axis_y     = LoadCustomImage("joystick/axis_y.png");
9314
9315     bitmaps_initialized = TRUE;
9316   }
9317
9318   name = getFormattedJoystickName(SDL_JoystickName(joystick));
9319
9320 #if DEBUG_JOYSTICKS
9321   // print info about the joystick we are watching
9322   Debug("joystick", "watching joystick %d: (%s)",
9323         SDL_JoystickInstanceID(joystick), name);
9324   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
9325         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
9326         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
9327 #endif
9328
9329   // initialize mapping with GUID and name
9330   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
9331
9332   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
9333            temp, name, SDL_GetPlatform());
9334
9335   // loop through all steps (buttons and axes), getting joystick events
9336   for (i = 0; i < SDL_arraysize(steps) && !done;)
9337   {
9338     Bitmap *marker = button;    // initialize with reliable default value
9339
9340     step = &steps[i];
9341     strcpy(step->mapping, mapping);
9342     step->axis = -1;
9343     step->button = -1;
9344     step->hat = -1;
9345     step->hat_value = -1;
9346
9347     marker = (step->marker == MARKER_BUTTON ? button :
9348               step->marker == MARKER_AXIS_X ? axis_x :
9349               step->marker == MARKER_AXIS_Y ? axis_y : marker);
9350
9351     next = FALSE;
9352
9353     while (!done && !next)
9354     {
9355       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
9356       alpha_ticks = SDL_GetTicks();
9357
9358       if (alpha >= 255)
9359       {
9360         alpha = 255;
9361         alpha_step = -1;
9362       }
9363       else if (alpha < 128)
9364       {
9365         alpha = 127;
9366         alpha_step = 1;
9367       }
9368
9369       int controller_x = SX + (SXSIZE - controller->width) / 2;
9370       int controller_y = SY + ystep_line;
9371
9372       int marker_x = controller_x + step->x;
9373       int marker_y = controller_y + step->y;
9374
9375       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
9376       int ystart2 = ystart1 + ystep_name + ystep_line;
9377
9378       ClearField();
9379
9380       DrawTextSCentered(ystart1, font_name, name);
9381
9382       DrawTextSCentered(ystart2, font_info,
9383                         "Press buttons and move axes on");
9384       ystart2 += ystep_line;
9385       DrawTextSCentered(ystart2, font_info,
9386                         "your controller when indicated.");
9387       ystart2 += ystep_line;
9388       DrawTextSCentered(ystart2, font_info,
9389                         "(Your controller may look different.)");
9390       ystart2 += ystep_para;
9391
9392 #if defined(PLATFORM_ANDROID)
9393       DrawTextSCentered(ystart2, font_info,
9394                         "To correct a mistake,");
9395       ystart2 += ystep_line;
9396       DrawTextSCentered(ystart2, font_info,
9397                         "press the 'back' button.");
9398       ystart2 += ystep_line;
9399       DrawTextSCentered(ystart2, font_info,
9400                         "To skip a button or axis,");
9401       ystart2 += ystep_line;
9402       DrawTextSCentered(ystart2, font_info,
9403                         "press the 'menu' button.");
9404 #else
9405       DrawTextSCentered(ystart2, font_info,
9406                         "To correct a mistake,");
9407       ystart2 += ystep_line;
9408       DrawTextSCentered(ystart2, font_info,
9409                         "press the 'backspace' key.");
9410       ystart2 += ystep_line;
9411       DrawTextSCentered(ystart2, font_info,
9412                         "To skip a button or axis,");
9413       ystart2 += ystep_line;
9414       DrawTextSCentered(ystart2, font_info,
9415                         "press the 'return' key.");
9416       ystart2 += ystep_line;
9417       DrawTextSCentered(ystart2, font_info,
9418                         "To exit, press the 'escape' key.");
9419 #endif
9420
9421       BlitBitmapMasked(controller, drawto, 0, 0,
9422                        controller->width, controller->height,
9423                        controller_x, controller_y);
9424
9425       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
9426       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
9427
9428       BlitBitmapMasked(marker, drawto, 0, 0,
9429                        marker->width, marker->height,
9430                        marker_x, marker_y);
9431
9432       if (!screen_initialized)
9433         FadeIn(REDRAW_FIELD);
9434       else
9435         BackToFront();
9436
9437       screen_initialized = TRUE;
9438
9439       DelayCounter event_frame_delay = { GAME_FRAME_DELAY };
9440
9441       // reset frame delay counter directly after updating screen
9442       ResetDelayCounter(&event_frame_delay);
9443
9444       while (NextValidEvent(&event))
9445       {
9446         switch (event.type)
9447         {
9448           case SDL_JOYAXISMOTION:
9449             if (event.jaxis.value > 20000 ||
9450                 event.jaxis.value < -20000)
9451             {
9452               for (j = 0; j < i; j++)
9453                 if (steps[j].axis == event.jaxis.axis)
9454                   break;
9455
9456               if (j == i)
9457               {
9458                 if (step->marker != MARKER_AXIS_X &&
9459                     step->marker != MARKER_AXIS_Y)
9460                   break;
9461
9462                 step->axis = event.jaxis.axis;
9463                 strcat(mapping, step->field);
9464                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
9465                 strcat(mapping, temp);
9466                 i++;
9467                 next = TRUE;
9468               }
9469             }
9470
9471             break;
9472
9473           case SDL_JOYHATMOTION:
9474             // ignore centering; we're probably just coming back
9475             // to the center from the previous item we set
9476             if (event.jhat.value == SDL_HAT_CENTERED)
9477               break;
9478
9479             for (j = 0; j < i; j++)
9480               if (steps[j].hat == event.jhat.hat &&
9481                   steps[j].hat_value == event.jhat.value)
9482                 break;
9483
9484             if (j == i)
9485             {
9486               step->hat = event.jhat.hat;
9487               step->hat_value = event.jhat.value;
9488               strcat(mapping, step->field);
9489               snprintf(temp, sizeof(temp), ":h%u.%u,",
9490                        event.jhat.hat, event.jhat.value );
9491               strcat(mapping, temp);
9492               i++;
9493               next = TRUE;
9494             }
9495
9496             break;
9497
9498           case SDL_JOYBALLMOTION:
9499             break;
9500
9501           case SDL_JOYBUTTONUP:
9502             for (j = 0; j < i; j++)
9503               if (steps[j].button == event.jbutton.button)
9504                 break;
9505
9506             if (j == i)
9507             {
9508               step->button = event.jbutton.button;
9509               strcat(mapping, step->field);
9510               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
9511               strcat(mapping, temp);
9512               i++;
9513               next = TRUE;
9514             }
9515
9516             break;
9517
9518           case SDL_FINGERDOWN:
9519           case SDL_MOUSEBUTTONDOWN:
9520             // skip this step
9521             i++;
9522             next = TRUE;
9523
9524             break;
9525
9526           case SDL_KEYDOWN:
9527             if (event.key.keysym.sym == KSYM_BackSpace ||
9528                 event.key.keysym.sym == KSYM_Back)
9529             {
9530               if (i == 0)
9531               {
9532                 // leave screen
9533                 success = FALSE;
9534                 done = TRUE;
9535
9536                 break;
9537               }
9538
9539               // undo this step
9540               prev_step = &steps[i - 1];
9541               strcpy(mapping, prev_step->mapping);
9542               i--;
9543               next = TRUE;
9544
9545               break;
9546             }
9547
9548             if (event.key.keysym.sym == KSYM_space ||
9549                 event.key.keysym.sym == KSYM_Return ||
9550                 event.key.keysym.sym == KSYM_Menu)
9551             {
9552               // skip this step
9553               i++;
9554               next = TRUE;
9555
9556               break;
9557             }
9558
9559             if (event.key.keysym.sym == KSYM_Escape)
9560             {
9561               // leave screen
9562               success = FALSE;
9563               done = TRUE;
9564             }
9565
9566             break;
9567
9568           case SDL_QUIT:
9569             program.exit_function(0);
9570             break;
9571
9572           default:
9573             break;
9574         }
9575
9576         // do not handle events for longer than standard frame delay period
9577         if (DelayReached(&event_frame_delay))
9578           break;
9579       }
9580     }
9581   }
9582
9583   if (success)
9584   {
9585 #if DEBUG_JOYSTICKS
9586     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
9587 #endif
9588
9589     // activate mapping for this game
9590     SDL_GameControllerAddMapping(mapping);
9591
9592     // save mapping to personal mappings
9593     SaveSetup_AddGameControllerMapping(mapping);
9594   }
9595
9596   // wait until the last pending event was removed from event queue
9597   while (NextValidEvent(&event));
9598
9599   return success;
9600 }
9601
9602 static int ConfigureJoystickMain(int player_nr)
9603 {
9604   char *device_name = setup.input[player_nr].joy.device_name;
9605   int joystick_nr = getJoystickNrFromDeviceName(device_name);
9606   boolean joystick_active = CheckJoystickOpened(joystick_nr);
9607   int success = FALSE;
9608   int i;
9609
9610   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
9611     return JOYSTICK_NOT_AVAILABLE;
9612
9613   if (!joystick_active || !setup.input[player_nr].use_joystick)
9614     return JOYSTICK_NOT_AVAILABLE;
9615
9616   FadeSetEnterMenu();
9617   FadeOut(REDRAW_FIELD);
9618
9619   // close all joystick devices (potentially opened as game controllers)
9620   for (i = 0; i < SDL_NumJoysticks(); i++)
9621     SDLCloseJoystick(i);
9622
9623   // open joystick device as plain joystick to configure as game controller
9624   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
9625
9626   // as the joystick was successfully opened before, this should not happen
9627   if (joystick == NULL)
9628     return FALSE;
9629
9630   // create new game controller mapping (buttons and axes) for joystick device
9631   success = ConfigureJoystickMapButtonsAndAxes(joystick);
9632
9633   // close joystick (and maybe re-open as configured game controller later)
9634   SDL_JoystickClose(joystick);
9635
9636   // re-open all joystick devices (potentially as game controllers)
9637   for (i = 0; i < SDL_NumJoysticks(); i++)
9638     SDLOpenJoystick(i);
9639
9640   // clear all joystick input actions for all joystick devices
9641   SDLClearJoystickState();
9642
9643   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
9644 }
9645
9646 void ConfigureJoystick(int player_nr)
9647 {
9648   boolean state = ConfigureJoystickMain(player_nr);
9649
9650   if (state != JOYSTICK_NOT_CONFIGURED)
9651   {
9652     boolean success = (state == JOYSTICK_CONFIGURED);
9653     char message1[MAX_OUTPUT_LINESIZE + 1];
9654     char *message2 = (success ? "configured!" : "not available!");
9655     char *device_name = setup.input[player_nr].joy.device_name;
9656     int nr = getJoystickNrFromDeviceName(device_name) + 1;
9657     int font_nr = FONT_TITLE_1;
9658     int font_height = getFontHeight(font_nr);
9659     int ypos1 = SYSIZE / 2 - font_height * 2;
9660     int ypos2 = SYSIZE / 2 - font_height * 1;
9661     DelayCounter wait_frame_delay = { 2000 };
9662
9663     ResetDelayCounter(&wait_frame_delay);
9664
9665     ClearField();
9666
9667     sprintf(message1, "Joystick %d", nr);
9668
9669     DrawTextSCentered(ypos1, font_nr, message1);
9670     DrawTextSCentered(ypos2, font_nr, message2);
9671
9672     while (!DelayReached(&wait_frame_delay))
9673       BackToFront();
9674
9675     ClearEventQueue();
9676   }
9677
9678   DrawSetupScreen_Input();
9679 }
9680
9681 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
9682 {
9683   if (y < video.screen_height / 3)
9684   {
9685     // remap touch gadgets to access upper part of the screen
9686     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9687     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9688   }
9689   else if (y > 2 * video.screen_height / 3)
9690   {
9691     // remap touch gadgets to access lower part of the screen
9692     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9693     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9694   }
9695 }
9696
9697 static boolean ConfigureVirtualButtonsMain(void)
9698 {
9699   static char *customize_step_text[] =
9700   {
9701     "Move Left",
9702     "Move Right",
9703     "Move Up",
9704     "Move Down",
9705     "Snap Field",
9706     "Drop Element"
9707   };
9708   char grid_button[] =
9709   {
9710     CHAR_GRID_BUTTON_LEFT,
9711     CHAR_GRID_BUTTON_RIGHT,
9712     CHAR_GRID_BUTTON_UP,
9713     CHAR_GRID_BUTTON_DOWN,
9714     CHAR_GRID_BUTTON_SNAP,
9715     CHAR_GRID_BUTTON_DROP
9716   };
9717   enum
9718   {
9719     ACTION_NONE,
9720     ACTION_ESCAPE,
9721     ACTION_BACK,
9722     ACTION_NEXT
9723   };
9724   int font_nr = FONT_INPUT_1_ACTIVE;
9725   int font_height = getFontHeight(font_nr);
9726   int ypos1 = SYSIZE / 2 - font_height * 2;
9727   int ypos2 = SYSIZE / 2 - font_height * 1;
9728   boolean success = FALSE;
9729   boolean finished = FALSE;
9730   int step_nr = 0;
9731   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
9732   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9733   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9734   boolean set_grid_button = FALSE;
9735   int nr = GRID_ACTIVE_NR();
9736   int x, y;
9737
9738   for (x = 0; x < MAX_GRID_XSIZE; x++)
9739     for (y = 0; y < MAX_GRID_YSIZE; y++)
9740       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
9741
9742   overlay.grid_button_highlight = grid_button[step_nr];
9743
9744   UnmapAllGadgets();
9745
9746   FadeSetEnterMenu();
9747   FadeOut(REDRAW_FIELD);
9748
9749   ClearField();
9750
9751   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9752   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9753   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9754
9755   FadeIn(REDRAW_FIELD);
9756
9757   SetOverlayShowGrid(TRUE);
9758
9759   // map gadgets for setup touch buttons menu screen
9760   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9761
9762   while (!finished)
9763   {
9764     Event event;
9765
9766     while (NextValidEvent(&event))
9767     {
9768       int action = ACTION_NONE;
9769
9770       // ---------- handle events and set the resulting action ----------
9771
9772       switch (event.type)
9773       {
9774         case EVENT_USER:
9775           {
9776             UserEvent *user = (UserEvent *)&event;
9777             int id = user->value1;
9778
9779             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
9780                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
9781                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
9782                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
9783                       ACTION_NONE);
9784           }
9785           break;
9786
9787         case EVENT_KEYPRESS:
9788           {
9789             Key key = GetEventKey((KeyEvent *)&event);
9790
9791             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
9792                       key == KSYM_BackSpace ||
9793                       key == KSYM_Back ?        ACTION_BACK :
9794                       key == KSYM_Return ||
9795                       key == KSYM_Menu ||
9796                       key == KSYM_space ?       ACTION_NEXT :
9797                       ACTION_NONE);
9798           }
9799           break;
9800
9801         case EVENT_KEYRELEASE:
9802           key_joystick_mapping = 0;
9803           break;
9804
9805         case EVENT_BUTTONPRESS:
9806         case EVENT_BUTTONRELEASE:
9807           {
9808             ButtonEvent *button = (ButtonEvent *)&event;
9809
9810             motion_status = FALSE;
9811
9812             if (button->type == EVENT_BUTTONPRESS)
9813               button_status = button->button;
9814             else
9815               button_status = MB_RELEASED;
9816
9817             if (HandleGadgets(button->x, button->y, button_status))
9818             {
9819               // do not handle this button event anymore
9820               break;
9821             }
9822
9823             button->x += video.screen_xoffset;
9824             button->y += video.screen_yoffset;
9825
9826             x = button->x * overlay.grid_xsize / video.screen_width;
9827             y = button->y * overlay.grid_ysize / video.screen_height;
9828
9829             if (button->type == EVENT_BUTTONPRESS)
9830             {
9831               grid_button_draw =
9832                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9833                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9834
9835               set_grid_button = TRUE;
9836             }
9837
9838             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9839           }
9840           break;
9841
9842         case EVENT_MOTIONNOTIFY:
9843           {
9844             MotionEvent *motion = (MotionEvent *)&event;
9845
9846             motion_status = TRUE;
9847
9848             if (HandleGadgets(motion->x, motion->y, button_status))
9849             {
9850               // do not handle this button event anymore
9851               break;
9852             }
9853
9854             motion->x += video.screen_xoffset;
9855             motion->y += video.screen_yoffset;
9856
9857             x = motion->x * overlay.grid_xsize / video.screen_width;
9858             y = motion->y * overlay.grid_ysize / video.screen_height;
9859
9860             set_grid_button = TRUE;
9861
9862             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9863           }
9864           break;
9865
9866         case SDL_WINDOWEVENT:
9867           HandleWindowEvent((WindowEvent *) &event);
9868
9869           // check if device has been rotated
9870           if (nr != GRID_ACTIVE_NR())
9871           {
9872             nr = GRID_ACTIVE_NR();
9873
9874             for (x = 0; x < MAX_GRID_XSIZE; x++)
9875               for (y = 0; y < MAX_GRID_YSIZE; y++)
9876                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9877                   overlay.grid_button[x][y];
9878           }
9879
9880           break;
9881
9882         case SDL_APP_WILLENTERBACKGROUND:
9883         case SDL_APP_DIDENTERBACKGROUND:
9884         case SDL_APP_WILLENTERFOREGROUND:
9885         case SDL_APP_DIDENTERFOREGROUND:
9886           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9887           break;
9888
9889         default:
9890           HandleOtherEvents(&event);
9891           break;
9892       }
9893
9894       // ---------- perform action set by handling events ----------
9895
9896       if (action == ACTION_ESCAPE)
9897       {
9898         // abort and restore the old key bindings
9899
9900         for (x = 0; x < MAX_GRID_XSIZE; x++)
9901           for (y = 0; y < MAX_GRID_YSIZE; y++)
9902             overlay.grid_button[x][y] = grid_button_old[x][y];
9903
9904         FadeSkipNextFadeIn();
9905
9906         finished = TRUE;
9907       }
9908       else if (action == ACTION_BACK)
9909       {
9910         // keep the configured key bindings and go to previous page
9911
9912         step_nr--;
9913
9914         if (step_nr < 0)
9915         {
9916           FadeSkipNextFadeIn();
9917
9918           finished = TRUE;
9919         }
9920       }
9921       else if (action == ACTION_NEXT)
9922       {
9923         // keep the configured key bindings and go to next page
9924
9925         step_nr++;
9926
9927         // all virtual buttons configured
9928         if (step_nr == 6)
9929         {
9930           finished = TRUE;
9931           success = TRUE;
9932         }
9933       }
9934
9935       if (action != ACTION_NONE && !finished)
9936       {
9937         for (x = 0; x < MAX_GRID_XSIZE; x++)
9938           for (y = 0; y < MAX_GRID_YSIZE; y++)
9939             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9940
9941         overlay.grid_button_highlight = grid_button[step_nr];
9942
9943         // configure next virtual button
9944
9945         ClearField();
9946
9947         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9948         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9949         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9950       }
9951
9952       if (set_grid_button)
9953       {
9954         overlay.grid_button[x][y] =
9955           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9956            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9957            grid_button_tmp[x][y]);
9958
9959         set_grid_button = FALSE;
9960       }
9961     }
9962
9963     BackToFront();
9964   }
9965
9966   for (x = 0; x < MAX_GRID_XSIZE; x++)
9967     for (y = 0; y < MAX_GRID_YSIZE; y++)
9968       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9969
9970   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9971
9972   SetOverlayShowGrid(FALSE);
9973
9974   return success;
9975 }
9976
9977 void ConfigureVirtualButtons(void)
9978 {
9979   boolean success = ConfigureVirtualButtonsMain();
9980
9981   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9982                          SCREEN_MASK_TOUCH2);
9983
9984   if (success)
9985   {
9986     int font_nr = FONT_TITLE_1;
9987     int font_height = getFontHeight(font_nr);
9988     int ypos1 = SYSIZE / 2 - font_height * 2;
9989     int ypos2 = SYSIZE / 2 - font_height * 1;
9990     DelayCounter wait_frame_delay = { 2000 };
9991
9992     ResetDelayCounter(&wait_frame_delay);
9993
9994     ClearField();
9995
9996     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9997     DrawTextSCentered(ypos2, font_nr, "configured!");
9998
9999     while (!DelayReached(&wait_frame_delay))
10000       BackToFront();
10001
10002     ClearEventQueue();
10003   }
10004 }
10005
10006 void DrawSetupScreen(void)
10007 {
10008   align_xoffset = 0;
10009   align_yoffset = 0;
10010
10011   if (setup_mode == SETUP_MODE_INPUT)
10012     DrawSetupScreen_Input();
10013   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
10014     DrawChooseTree(&scores_type_current);
10015   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
10016     DrawChooseTree(&game_speed_current);
10017   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
10018     DrawChooseTree(&scroll_delay_current);
10019   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
10020     DrawChooseTree(&snapshot_mode_current);
10021   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE)
10022     DrawChooseTree(&game_engine_type_current);
10023   else if (setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64)
10024     DrawChooseTree(&bd_palette_c64_current);
10025   else if (setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV)
10026     DrawChooseTree(&bd_palette_c64dtv_current);
10027   else if (setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_ATARI)
10028     DrawChooseTree(&bd_palette_atari_current);
10029   else if (setup_mode == SETUP_MODE_CHOOSE_BD_COLOR_TYPE)
10030     DrawChooseTree(&bd_color_type_current);
10031   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
10032     DrawChooseTree(&window_size_current);
10033   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
10034     DrawChooseTree(&scaling_type_current);
10035   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
10036     DrawChooseTree(&rendering_mode_current);
10037   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
10038     DrawChooseTree(&vsync_mode_current);
10039   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
10040     DrawChooseTree(&artwork.gfx_current);
10041   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
10042     DrawChooseTree(&artwork.snd_current);
10043   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
10044     DrawChooseTree(&artwork.mus_current);
10045   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
10046     DrawChooseTree(&volume_simple_current);
10047   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
10048     DrawChooseTree(&volume_loops_current);
10049   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
10050     DrawChooseTree(&volume_music_current);
10051   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
10052     DrawChooseTree(&touch_control_current);
10053   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
10054     DrawChooseTree(&move_distance_current);
10055   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
10056     DrawChooseTree(&drop_distance_current);
10057   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
10058     DrawChooseTree(&transparency_current);
10059   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
10060     DrawChooseTree(&grid_size_current[0][0]);
10061   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
10062     DrawChooseTree(&grid_size_current[0][1]);
10063   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
10064     DrawChooseTree(&grid_size_current[1][0]);
10065   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
10066     DrawChooseTree(&grid_size_current[1][1]);
10067   else
10068     DrawSetupScreen_Generic();
10069
10070   PlayMenuSoundsAndMusic();
10071 }
10072
10073 void RedrawSetupScreenAfterFullscreenToggle(void)
10074 {
10075   if (setup_mode == SETUP_MODE_GRAPHICS ||
10076       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
10077   {
10078     // update list selection from "setup.window_scaling_percent"
10079     execSetupGraphics_setWindowSizes(TRUE);
10080
10081     DrawSetupScreen();
10082   }
10083 }
10084
10085 void RedrawSetupScreenAfterScreenRotation(int nr)
10086 {
10087   int x, y;
10088
10089   if (setup_mode == SETUP_MODE_TOUCH)
10090   {
10091     // update virtual button settings (depending on screen orientation)
10092     DrawSetupScreen();
10093   }
10094   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
10095   {
10096     // save already configured virtual buttons
10097     for (x = 0; x < MAX_GRID_XSIZE; x++)
10098       for (y = 0; y < MAX_GRID_YSIZE; y++)
10099         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
10100   }
10101 }
10102
10103 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
10104 {
10105   if (setup_mode == SETUP_MODE_INPUT)
10106     HandleSetupScreen_Input(mx, my, dx, dy, button);
10107   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
10108     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
10109   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
10110     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
10111   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
10112     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
10113   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
10114     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
10115   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_ENGINE_TYPE)
10116     HandleChooseTree(mx, my, dx, dy, button, &game_engine_type_current);
10117   else if (setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64)
10118     HandleChooseTree(mx, my, dx, dy, button, &bd_palette_c64_current);
10119   else if (setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_C64DTV)
10120     HandleChooseTree(mx, my, dx, dy, button, &bd_palette_c64dtv_current);
10121   else if (setup_mode == SETUP_MODE_CHOOSE_BD_PALETTE_ATARI)
10122     HandleChooseTree(mx, my, dx, dy, button, &bd_palette_atari_current);
10123   else if (setup_mode == SETUP_MODE_CHOOSE_BD_COLOR_TYPE)
10124     HandleChooseTree(mx, my, dx, dy, button, &bd_color_type_current);
10125   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
10126     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
10127   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
10128     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
10129   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
10130     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
10131   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
10132     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
10133   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
10134     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
10135   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
10136     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
10137   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
10138     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
10139   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
10140     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
10141   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
10142     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
10143   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
10144     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
10145   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
10146     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
10147   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
10148     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
10149   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
10150     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
10151   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
10152     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
10153   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
10154     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
10155   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
10156     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
10157   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
10158     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
10159   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
10160     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
10161   else
10162     HandleSetupScreen_Generic(mx, my, dx, dy, button);
10163 }
10164
10165 void HandleGameActions(void)
10166 {
10167   if (CheckRestartGame())
10168     return;
10169
10170   if (game_status != GAME_MODE_PLAYING)
10171     return;
10172
10173   GameActions();                // main game loop
10174
10175   if (tape.auto_play && !tape.playing)
10176     AutoPlayTapesContinue();    // continue automatically playing next tape
10177 }
10178
10179
10180 // ---------- new screen button stuff --------------------------------------
10181
10182 static struct
10183 {
10184   int gfx_unpressed, gfx_pressed, gfx_active;
10185   struct MenuPosInfo *pos;
10186   boolean *check_value;
10187   int gadget_id;
10188   int screen_mask;
10189   unsigned int event_mask;
10190   boolean is_touch_button;
10191   char *infotext;
10192 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
10193 {
10194   {
10195     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE, -1,
10196     &menu.main.button.prev_level, NULL,
10197     SCREEN_CTRL_ID_PREV_LEVEL,
10198     SCREEN_MASK_MAIN,
10199     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10200     FALSE, "previous level"
10201   },
10202   {
10203     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE, -1,
10204     &menu.main.button.next_level, NULL,
10205     SCREEN_CTRL_ID_NEXT_LEVEL,
10206     SCREEN_MASK_MAIN,
10207     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10208     FALSE, "next level"
10209   },
10210   {
10211     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE, -1,
10212     &menu.scores.button.prev_level, NULL,
10213     SCREEN_CTRL_ID_PREV_LEVEL2,
10214     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
10215     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10216     FALSE, "previous level"
10217   },
10218   {
10219     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE, -1,
10220     &menu.scores.button.next_level, NULL,
10221     SCREEN_CTRL_ID_NEXT_LEVEL2,
10222     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
10223     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10224     FALSE, "next level"
10225   },
10226   {
10227     IMG_MENU_BUTTON_PREV_SCORE, IMG_MENU_BUTTON_PREV_SCORE_ACTIVE, -1,
10228     &menu.scores.button.prev_score, NULL,
10229     SCREEN_CTRL_ID_PREV_SCORE,
10230     SCREEN_MASK_SCORES_INFO,
10231     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10232     FALSE, "previous score"
10233   },
10234   {
10235     IMG_MENU_BUTTON_NEXT_SCORE, IMG_MENU_BUTTON_NEXT_SCORE_ACTIVE, -1,
10236     &menu.scores.button.next_score, NULL,
10237     SCREEN_CTRL_ID_NEXT_SCORE,
10238     SCREEN_MASK_SCORES_INFO,
10239     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10240     FALSE, "next score"
10241   },
10242   {
10243     IMG_MENU_BUTTON_PLAY_TAPE, IMG_MENU_BUTTON_PLAY_TAPE, -1,
10244     &menu.scores.button.play_tape, NULL,
10245     SCREEN_CTRL_ID_PLAY_TAPE,
10246     SCREEN_MASK_SCORES_INFO,
10247     GD_EVENT_RELEASED,
10248     FALSE, "play tape"
10249   },
10250   {
10251     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE, -1,
10252     &menu.main.button.first_level, NULL,
10253     SCREEN_CTRL_ID_FIRST_LEVEL,
10254     SCREEN_MASK_MAIN,
10255     GD_EVENT_RELEASED,
10256     FALSE, "first level"
10257   },
10258   {
10259     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE, -1,
10260     &menu.main.button.last_level, NULL,
10261     SCREEN_CTRL_ID_LAST_LEVEL,
10262     SCREEN_MASK_MAIN,
10263     GD_EVENT_RELEASED,
10264     FALSE, "last level"
10265   },
10266   {
10267     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE, -1,
10268     &menu.main.button.level_number, NULL,
10269     SCREEN_CTRL_ID_LEVEL_NUMBER,
10270     SCREEN_MASK_MAIN,
10271     GD_EVENT_RELEASED,
10272     FALSE, "level number"
10273   },
10274   {
10275     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE, -1,
10276     &menu.setup.button.prev_player, NULL,
10277     SCREEN_CTRL_ID_PREV_PLAYER,
10278     SCREEN_MASK_INPUT,
10279     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10280     FALSE, "previous player"
10281   },
10282   {
10283     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE, -1,
10284     &menu.setup.button.next_player, NULL,
10285     SCREEN_CTRL_ID_NEXT_PLAYER,
10286     SCREEN_MASK_INPUT,
10287     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
10288     FALSE, "next player"
10289   },
10290   {
10291     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE, -1,
10292     &menu.main.button.insert_solution, NULL,
10293     SCREEN_CTRL_ID_INSERT_SOLUTION,
10294     SCREEN_MASK_MAIN_HAS_SOLUTION,
10295     GD_EVENT_RELEASED,
10296     FALSE, "insert solution tape"
10297   },
10298   {
10299     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE, -1,
10300     &menu.main.button.play_solution, NULL,
10301     SCREEN_CTRL_ID_PLAY_SOLUTION,
10302     SCREEN_MASK_MAIN_HAS_SOLUTION,
10303     GD_EVENT_RELEASED,
10304     FALSE, "play solution tape"
10305   },
10306   {
10307     IMG_MENU_BUTTON_LEVELSET_INFO, IMG_MENU_BUTTON_LEVELSET_INFO_PRESSED,
10308     IMG_MENU_BUTTON_LEVELSET_INFO_ACTIVE,
10309     &menu.main.button.levelset_info, NULL,
10310     SCREEN_CTRL_ID_LEVELSET_INFO,
10311     SCREEN_MASK_MAIN_HAS_SET_INFO,
10312     GD_EVENT_RELEASED,
10313     FALSE, "show level set info"
10314   },
10315   {
10316     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE, -1,
10317     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
10318     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
10319     SCREEN_MASK_MAIN,
10320     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
10321     FALSE, "switch ECS/AGA chipset"
10322   },
10323   {
10324     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK, -1,
10325     &menu.setup.button.touch_back, NULL,
10326     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
10327     SCREEN_MASK_TOUCH,
10328     GD_EVENT_RELEASED,
10329     TRUE, "previous page"
10330   },
10331   {
10332     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT, -1,
10333     &menu.setup.button.touch_next, NULL,
10334     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
10335     SCREEN_MASK_TOUCH,
10336     GD_EVENT_RELEASED,
10337     TRUE, "next page"
10338   },
10339   {
10340     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2, -1,
10341     &menu.setup.button.touch_back2, NULL,
10342     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
10343     SCREEN_MASK_TOUCH2,
10344     GD_EVENT_RELEASED,
10345     TRUE, "previous page"
10346   },
10347   {
10348     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2, -1,
10349     &menu.setup.button.touch_next2, NULL,
10350     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
10351     SCREEN_MASK_TOUCH2,
10352     GD_EVENT_RELEASED,
10353     TRUE, "next page"
10354   },
10355 };
10356
10357 static struct
10358 {
10359   int gfx_unpressed, gfx_pressed;
10360   int x, y;
10361   int gadget_id;
10362   char *infotext;
10363 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
10364 {
10365   {
10366     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
10367     -1, -1,     // these values are not constant, but can change at runtime
10368     SCREEN_CTRL_ID_SCROLL_UP,
10369     "scroll up"
10370   },
10371   {
10372     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
10373     -1, -1,     // these values are not constant, but can change at runtime
10374     SCREEN_CTRL_ID_SCROLL_DOWN,
10375     "scroll down"
10376   }
10377 };
10378
10379 static struct
10380 {
10381   int gfx_unpressed, gfx_pressed;
10382   int x, y;
10383   int width, height;
10384   int type;
10385   int gadget_id;
10386   char *infotext;
10387 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
10388 {
10389   {
10390     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
10391     -1, -1,     // these values are not constant, but can change at runtime
10392     -1, -1,     // these values are not constant, but can change at runtime
10393     GD_TYPE_SCROLLBAR_VERTICAL,
10394     SCREEN_CTRL_ID_SCROLL_VERTICAL,
10395     "scroll level series vertically"
10396   }
10397 };
10398
10399 static struct
10400 {
10401   int graphic;
10402   int gadget_id;
10403   int x, y;
10404   int size;
10405   char *value;
10406   char *infotext;
10407 } textinput_info[NUM_SCREEN_TEXTINPUT] =
10408 {
10409   {
10410     IMG_SETUP_INPUT_TEXT,
10411     SCREEN_CTRL_ID_NETWORK_SERVER,
10412     -1, -1,     // these values are not constant, but can change at runtime
10413     MAX_SETUP_TEXT_INPUT_LEN,
10414     network_server_hostname,
10415     "Network Server Hostname / IP"
10416   },
10417 };
10418
10419 static void CreateScreenMenubuttons(void)
10420 {
10421   struct GadgetInfo *gi;
10422   unsigned int event_mask;
10423   int i;
10424
10425   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10426   {
10427     struct MenuPosInfo *pos = menubutton_info[i].pos;
10428     int screen_mask = menubutton_info[i].screen_mask;
10429     boolean is_touch_button = menubutton_info[i].is_touch_button;
10430     boolean is_check_button = menubutton_info[i].check_value != NULL;
10431     boolean is_score_button = (screen_mask & SCREEN_MASK_SCORES_INFO);
10432     boolean has_gfx_pressed = (menubutton_info[i].gfx_pressed ==
10433                                menubutton_info[i].gfx_unpressed);
10434     boolean has_gfx_active = (menubutton_info[i].gfx_active != -1);
10435     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10436     Bitmap *gd_bitmap_unpressed_alt, *gd_bitmap_pressed_alt;
10437     int gfx_unpressed, gfx_pressed;
10438     int gfx_unpressed_alt, gfx_pressed_alt;
10439     int x, y, width, height;
10440     int gd_x1, gd_x2, gd_y1, gd_y2;
10441     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
10442     int id = menubutton_info[i].gadget_id;
10443     int type = GD_TYPE_NORMAL_BUTTON;
10444     boolean checked = FALSE;
10445
10446     // do not use touch buttons if overlay touch buttons are disabled
10447     if (is_touch_button && !setup.touch.overlay_buttons)
10448       continue;
10449
10450     event_mask = menubutton_info[i].event_mask;
10451
10452     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
10453     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
10454
10455     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
10456     height = graphic_info[menubutton_info[i].gfx_pressed].height;
10457
10458     gfx_unpressed = menubutton_info[i].gfx_unpressed;
10459     gfx_pressed   = menubutton_info[i].gfx_pressed;
10460     gfx_unpressed_alt = gfx_unpressed;
10461     gfx_pressed_alt   = gfx_pressed;
10462
10463     if (has_gfx_active)
10464     {
10465       gfx_unpressed_alt = menubutton_info[i].gfx_active;
10466
10467       type = GD_TYPE_CHECK_BUTTON_2;
10468
10469       if (menubutton_info[i].check_value != NULL)
10470         checked = *menubutton_info[i].check_value;
10471     }
10472
10473     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10474     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10475     gd_bitmap_unpressed_alt = graphic_info[gfx_unpressed_alt].bitmap;
10476     gd_bitmap_pressed_alt   = graphic_info[gfx_pressed_alt].bitmap;
10477
10478     gd_x1 = graphic_info[gfx_unpressed].src_x;
10479     gd_y1 = graphic_info[gfx_unpressed].src_y;
10480     gd_x2 = graphic_info[gfx_pressed].src_x;
10481     gd_y2 = graphic_info[gfx_pressed].src_y;
10482
10483     gd_x1a = graphic_info[gfx_unpressed_alt].src_x;
10484     gd_y1a = graphic_info[gfx_unpressed_alt].src_y;
10485     gd_x2a = graphic_info[gfx_pressed_alt].src_x;
10486     gd_y2a = graphic_info[gfx_pressed_alt].src_y;
10487
10488     if (has_gfx_pressed)
10489     {
10490       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
10491       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
10492     }
10493
10494     if (is_check_button)
10495     {
10496       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
10497       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
10498       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
10499       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
10500
10501       type = GD_TYPE_CHECK_BUTTON;
10502
10503       if (menubutton_info[i].check_value != NULL)
10504         checked = *menubutton_info[i].check_value;
10505     }
10506
10507     if (is_score_button)
10508     {
10509       // if x/y set to -1, dynamically place buttons next to title text
10510       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
10511
10512       // special compatibility handling for "Snake Bite" graphics set
10513       if (strPrefix(leveldir_current->identifier, "snake_bite"))
10514         title_width = strlen(INFOTEXT_SCORE_ENTRY) * 32;
10515
10516       // use "SX" here to center buttons (ignore horizontal draw offset)
10517       if (pos->x == -1)
10518         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
10519              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
10520              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
10521              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
10522
10523       // use "mSY" here to place buttons (respect vertical draw offset)
10524       if (pos->y == -1)
10525         y = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ||
10526              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ? mSY + MENU_TITLE1_YPOS : 0);
10527     }
10528
10529     if (id == SCREEN_CTRL_ID_LEVELSET_INFO)
10530     {
10531       if (pos->x == -1 && pos->y == -1)
10532       {
10533         // use "SX" here to place button (ignore draw offsets)
10534         x = SX + SXSIZE - 2 * TILESIZE;
10535         y = SY + SYSIZE - 2 * TILESIZE;
10536
10537         // special compatibility handling for "BD2K3" graphics set
10538         if (strPrefix(leveldir_current->identifier, "BD2K3"))
10539           x = SX + TILESIZE + MINI_TILESIZE;
10540
10541         // special compatibility handling for "jue0" graphics set
10542         if (strPrefix(artwork.gfx_current_identifier, "jue0"))
10543         {
10544           x = SX + SXSIZE - 4 * TILESIZE;
10545           y = SY + SYSIZE - 3 * TILESIZE;
10546         }
10547       }
10548     }
10549
10550     gi = CreateGadget(GDI_CUSTOM_ID, id,
10551                       GDI_CUSTOM_TYPE_ID, i,
10552                       GDI_IMAGE_ID, gfx_unpressed,
10553                       GDI_INFO_TEXT, menubutton_info[i].infotext,
10554                       GDI_X, x,
10555                       GDI_Y, y,
10556                       GDI_WIDTH, width,
10557                       GDI_HEIGHT, height,
10558                       GDI_TYPE, type,
10559                       GDI_STATE, GD_BUTTON_UNPRESSED,
10560                       GDI_CHECKED, checked,
10561                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10562                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10563                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed_alt, gd_x1a, gd_y1a,
10564                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed_alt, gd_x2a, gd_y2a,
10565                       GDI_DIRECT_DRAW, FALSE,
10566                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
10567                       GDI_EVENT_MASK, event_mask,
10568                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10569                       GDI_END);
10570
10571     if (gi == NULL)
10572       Fail("cannot create gadget");
10573
10574     screen_gadget[id] = gi;
10575   }
10576 }
10577
10578 static void CreateScreenScrollbuttons(void)
10579 {
10580   struct GadgetInfo *gi;
10581   unsigned int event_mask;
10582   int i;
10583
10584   // these values are not constant, but can change at runtime
10585   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
10586   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
10587   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
10588   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
10589
10590   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10591   {
10592     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10593     int gfx_unpressed, gfx_pressed;
10594     int x, y, width, height;
10595     int gd_x1, gd_x2, gd_y1, gd_y2;
10596     int id = scrollbutton_info[i].gadget_id;
10597
10598     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
10599
10600     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
10601     y = mSY + scrollbutton_info[i].y;
10602     width = SC_SCROLLBUTTON_XSIZE;
10603     height = SC_SCROLLBUTTON_YSIZE;
10604
10605     // correct scrollbar position if placed outside menu (playfield) area
10606     if (x > SX + SC_SCROLL_UP_XPOS)
10607       x = SX + SC_SCROLL_UP_XPOS;
10608
10609     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
10610       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
10611                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
10612
10613     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
10614     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
10615     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10616     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10617     gd_x1 = graphic_info[gfx_unpressed].src_x;
10618     gd_y1 = graphic_info[gfx_unpressed].src_y;
10619     gd_x2 = graphic_info[gfx_pressed].src_x;
10620     gd_y2 = graphic_info[gfx_pressed].src_y;
10621
10622     gi = CreateGadget(GDI_CUSTOM_ID, id,
10623                       GDI_CUSTOM_TYPE_ID, i,
10624                       GDI_IMAGE_ID, gfx_unpressed,
10625                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
10626                       GDI_X, x,
10627                       GDI_Y, y,
10628                       GDI_WIDTH, width,
10629                       GDI_HEIGHT, height,
10630                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
10631                       GDI_STATE, GD_BUTTON_UNPRESSED,
10632                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10633                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10634                       GDI_DIRECT_DRAW, FALSE,
10635                       GDI_EVENT_MASK, event_mask,
10636                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10637                       GDI_END);
10638
10639     if (gi == NULL)
10640       Fail("cannot create gadget");
10641
10642     screen_gadget[id] = gi;
10643   }
10644 }
10645
10646 static void CreateScreenScrollbars(void)
10647 {
10648   int i;
10649
10650   // these values are not constant, but can change at runtime
10651   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
10652   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
10653   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
10654   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
10655
10656   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10657   {
10658     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10659     int gfx_unpressed, gfx_pressed;
10660     int x, y, width, height;
10661     int gd_x1, gd_x2, gd_y1, gd_y2;
10662     struct GadgetInfo *gi;
10663     int items_max, items_visible, item_position;
10664     unsigned int event_mask;
10665     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
10666     int id = scrollbar_info[i].gadget_id;
10667
10668     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
10669
10670     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
10671     y = mSY + scrollbar_info[i].y;
10672     width  = scrollbar_info[i].width;
10673     height = scrollbar_info[i].height;
10674
10675     // correct scrollbar position if placed outside menu (playfield) area
10676     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
10677       x = SX + SC_SCROLL_VERTICAL_XPOS;
10678
10679     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
10680       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
10681
10682     items_max = num_page_entries;
10683     items_visible = num_page_entries;
10684     item_position = 0;
10685
10686     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
10687     gfx_pressed   = scrollbar_info[i].gfx_pressed;
10688     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10689     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10690     gd_x1 = graphic_info[gfx_unpressed].src_x;
10691     gd_y1 = graphic_info[gfx_unpressed].src_y;
10692     gd_x2 = graphic_info[gfx_pressed].src_x;
10693     gd_y2 = graphic_info[gfx_pressed].src_y;
10694
10695     gi = CreateGadget(GDI_CUSTOM_ID, id,
10696                       GDI_CUSTOM_TYPE_ID, i,
10697                       GDI_IMAGE_ID, gfx_unpressed,
10698                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
10699                       GDI_X, x,
10700                       GDI_Y, y,
10701                       GDI_WIDTH, width,
10702                       GDI_HEIGHT, height,
10703                       GDI_TYPE, scrollbar_info[i].type,
10704                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
10705                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
10706                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
10707                       GDI_WHEEL_AREA_X, SX,
10708                       GDI_WHEEL_AREA_Y, SY,
10709                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
10710                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
10711                       GDI_STATE, GD_BUTTON_UNPRESSED,
10712                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10713                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10714                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
10715                       GDI_DIRECT_DRAW, FALSE,
10716                       GDI_EVENT_MASK, event_mask,
10717                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10718                       GDI_END);
10719
10720     if (gi == NULL)
10721       Fail("cannot create gadget");
10722
10723     screen_gadget[id] = gi;
10724   }
10725 }
10726
10727 static void CreateScreenTextInputGadgets(void)
10728 {
10729   int i;
10730
10731   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
10732   {
10733     int graphic = textinput_info[i].graphic;
10734     struct GraphicInfo *gd = &graphic_info[graphic];
10735     int gd_x1 = gd->src_x;
10736     int gd_y1 = gd->src_y;
10737     int gd_x2 = gd->src_x + gd->active_xoffset;
10738     int gd_y2 = gd->src_y + gd->active_yoffset;
10739     struct GadgetInfo *gi;
10740     unsigned int event_mask;
10741     int id = textinput_info[i].gadget_id;
10742     int x = textinput_info[i].x;
10743     int y = textinput_info[i].y;
10744
10745     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
10746
10747     gi = CreateGadget(GDI_CUSTOM_ID, id,
10748                       GDI_CUSTOM_TYPE_ID, i,
10749                       GDI_INFO_TEXT, textinput_info[i].infotext,
10750                       GDI_X, SX + x,
10751                       GDI_Y, SY + y,
10752                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
10753                       GDI_TEXT_VALUE, textinput_info[i].value,
10754                       GDI_TEXT_SIZE, textinput_info[i].size,
10755                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
10756                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
10757                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
10758                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
10759                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
10760                       GDI_DESIGN_WIDTH, gd->width,
10761                       GDI_EVENT_MASK, event_mask,
10762                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10763                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
10764                       GDI_END);
10765
10766     if (gi == NULL)
10767       Fail("cannot create gadget");
10768
10769     screen_gadget[id] = gi;
10770   }
10771 }
10772
10773 void CreateScreenGadgets(void)
10774 {
10775   CreateScreenMenubuttons();
10776
10777   CreateScreenScrollbuttons();
10778   CreateScreenScrollbars();
10779
10780   CreateScreenTextInputGadgets();
10781 }
10782
10783 void FreeScreenGadgets(void)
10784 {
10785   int i;
10786
10787   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
10788     FreeGadget(screen_gadget[i]);
10789 }
10790
10791 static void RedrawScreenMenuGadgets(int screen_mask)
10792 {
10793   int i;
10794
10795   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10796     if (screen_mask & menubutton_info[i].screen_mask)
10797       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
10798 }
10799
10800 static void MapScreenMenuGadgets(int screen_mask)
10801 {
10802   int i;
10803
10804   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10805     if (screen_mask & menubutton_info[i].screen_mask)
10806       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10807 }
10808
10809 static void UnmapScreenMenuGadgets(int screen_mask)
10810 {
10811   int i;
10812
10813   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10814   {
10815     if (screen_mask & menubutton_info[i].screen_mask)
10816     {
10817       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10818
10819       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
10820         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
10821                        screen_gadget[menubutton_info[i].gadget_id]->y,
10822                        screen_gadget[menubutton_info[i].gadget_id]->width,
10823                        screen_gadget[menubutton_info[i].gadget_id]->height);
10824     }
10825   }
10826 }
10827
10828 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
10829 {
10830   if (map_gadgets)
10831     MapScreenMenuGadgets(screen_mask);
10832   else
10833     UnmapScreenMenuGadgets(screen_mask);
10834 }
10835
10836 static void MapScreenGadgets(int num_entries)
10837 {
10838   int i;
10839
10840   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
10841     return;
10842
10843   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10844     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10845
10846   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10847     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10848 }
10849
10850 static void UnmapScreenGadgets(void)
10851 {
10852   int i;
10853
10854   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10855     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10856
10857   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10858     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10859 }
10860
10861 static void MapScreenTreeGadgets(TreeInfo *ti)
10862 {
10863   MapScreenGadgets(numTreeInfoInGroup(ti));
10864 }
10865
10866 static void UnmapScreenTreeGadgets(void)
10867 {
10868   UnmapScreenGadgets();
10869 }
10870
10871 static void AdjustScoreInfoButtons_SelectScore(int x, int y1, int y2)
10872 {
10873   struct GadgetInfo *gi_1 = screen_gadget[SCREEN_CTRL_ID_PREV_SCORE];
10874   struct GadgetInfo *gi_2 = screen_gadget[SCREEN_CTRL_ID_NEXT_SCORE];
10875   struct MenuPosInfo *pos_1 = menubutton_info[SCREEN_CTRL_ID_PREV_SCORE].pos;
10876   struct MenuPosInfo *pos_2 = menubutton_info[SCREEN_CTRL_ID_NEXT_SCORE].pos;
10877
10878   if (pos_1->x == -1 && pos_1->y == -1)
10879     ModifyGadget(gi_1, GDI_X, x, GDI_Y, y1, GDI_END);
10880
10881   if (pos_2->x == -1 && pos_2->y == -1)
10882     ModifyGadget(gi_2, GDI_X, x, GDI_Y, y2, GDI_END);
10883 }
10884
10885 static void AdjustScoreInfoButtons_PlayTape(int x, int y, boolean visible)
10886 {
10887   struct GadgetInfo *gi = screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE];
10888   struct MenuPosInfo *pos = menubutton_info[SCREEN_CTRL_ID_PLAY_TAPE].pos;
10889
10890   // set gadget position dynamically, pre-defined or off-screen
10891   int xx = (visible ? (pos->x == -1 ? x : pos->x) : POS_OFFSCREEN);
10892   int yy = (visible ? (pos->y == -1 ? y : pos->y) : POS_OFFSCREEN);
10893
10894   ModifyGadget(gi, GDI_X, xx, GDI_Y, yy, GDI_END);
10895   MapGadget(gi);        // (needed if deactivated on last score page)
10896 }
10897
10898 static void HandleScreenGadgets(struct GadgetInfo *gi)
10899 {
10900   int id = gi->custom_id;
10901   int button = gi->event.button;
10902   int step = (button == MB_LEFTBUTTON   ? 1 :
10903               button == MB_MIDDLEBUTTON ? 5 :
10904               button == MB_RIGHTBUTTON  ? 10 : 1);
10905
10906   switch (id)
10907   {
10908     case SCREEN_CTRL_ID_PREV_LEVEL:
10909       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10910       break;
10911
10912     case SCREEN_CTRL_ID_NEXT_LEVEL:
10913       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10914       break;
10915
10916     case SCREEN_CTRL_ID_PREV_LEVEL2:
10917       HandleHallOfFame_SelectLevel(step, -1);
10918       break;
10919
10920     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10921       HandleHallOfFame_SelectLevel(step, +1);
10922       break;
10923
10924     case SCREEN_CTRL_ID_PREV_SCORE:
10925       HandleScoreInfo_SelectScore(step, -1);
10926       break;
10927
10928     case SCREEN_CTRL_ID_NEXT_SCORE:
10929       HandleScoreInfo_SelectScore(step, +1);
10930       break;
10931
10932     case SCREEN_CTRL_ID_PLAY_TAPE:
10933       HandleScoreInfo_PlayTape();
10934       break;
10935
10936     case SCREEN_CTRL_ID_FIRST_LEVEL:
10937       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10938       break;
10939
10940     case SCREEN_CTRL_ID_LAST_LEVEL:
10941       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10942       break;
10943
10944     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10945       CloseDoor(DOOR_CLOSE_2);
10946       SetGameStatus(GAME_MODE_LEVELNR);
10947       DrawChooseLevelNr();
10948       break;
10949
10950     case SCREEN_CTRL_ID_PREV_PLAYER:
10951       HandleSetupScreen_Input_Player(step, -1);
10952       break;
10953
10954     case SCREEN_CTRL_ID_NEXT_PLAYER:
10955       HandleSetupScreen_Input_Player(step, +1);
10956       break;
10957
10958     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10959       InsertSolutionTape();
10960       break;
10961
10962     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10963       PlaySolutionTape();
10964       break;
10965
10966     case SCREEN_CTRL_ID_LEVELSET_INFO:
10967       DrawInfoScreen_FromMainMenu(INFO_MODE_LEVELSET);
10968       break;
10969
10970     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10971       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10972       DrawMainMenu();
10973       break;
10974
10975     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10976     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10977     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10978     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10979       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10980       break;
10981
10982     case SCREEN_CTRL_ID_SCROLL_UP:
10983       if (game_status == GAME_MODE_NAMES)
10984         HandleChoosePlayerName(0, 0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10985       else if (game_status == GAME_MODE_LEVELS)
10986         HandleChooseLevelSet(0, 0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10987       else if (game_status == GAME_MODE_LEVELNR)
10988         HandleChooseLevelNr(0, 0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10989       else if (game_status == GAME_MODE_SETUP)
10990         HandleSetupScreen(0, 0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10991       else if (game_status == GAME_MODE_INFO)
10992         HandleInfoScreen(0, 0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10993       else if (game_status == GAME_MODE_SCORES)
10994         HandleHallOfFame(0, 0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10995       break;
10996
10997     case SCREEN_CTRL_ID_SCROLL_DOWN:
10998       if (game_status == GAME_MODE_NAMES)
10999         HandleChoosePlayerName(0, 0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
11000       else if (game_status == GAME_MODE_LEVELS)
11001         HandleChooseLevelSet(0, 0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
11002       else if (game_status == GAME_MODE_LEVELNR)
11003         HandleChooseLevelNr(0, 0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
11004       else if (game_status == GAME_MODE_SETUP)
11005         HandleSetupScreen(0, 0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
11006       else if (game_status == GAME_MODE_INFO)
11007         HandleInfoScreen(0, 0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
11008       else if (game_status == GAME_MODE_SCORES)
11009         HandleHallOfFame(0, 0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
11010       break;
11011
11012     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
11013       if (game_status == GAME_MODE_NAMES)
11014         HandleChoosePlayerName(0, 0, 999, gi->event.item_position, MB_MENU_INITIALIZE);
11015       else if (game_status == GAME_MODE_LEVELS)
11016         HandleChooseLevelSet(0, 0, 999, gi->event.item_position, MB_MENU_INITIALIZE);
11017       else if (game_status == GAME_MODE_LEVELNR)
11018         HandleChooseLevelNr(0, 0, 999, gi->event.item_position, MB_MENU_INITIALIZE);
11019       else if (game_status == GAME_MODE_SETUP)
11020         HandleSetupScreen(0, 0, 999, gi->event.item_position, MB_MENU_INITIALIZE);
11021       else if (game_status == GAME_MODE_INFO)
11022         HandleInfoScreen(0, 0, 999, gi->event.item_position, MB_MENU_INITIALIZE);
11023       else if (game_status == GAME_MODE_SCORES)
11024         HandleHallOfFame(0, 0, 999, gi->event.item_position, MB_MENU_INITIALIZE);
11025       break;
11026
11027     case SCREEN_CTRL_ID_NETWORK_SERVER:
11028     {
11029       if (!strEqual(gi->textinput.value, ""))
11030       {
11031         setString(&setup.network_server_hostname, gi->textinput.value);
11032
11033         network.server_host = setup.network_server_hostname;
11034       }
11035       else
11036       {
11037         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
11038
11039         network.server_host = NULL;
11040       }
11041
11042       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
11043         network.server_host = NULL;
11044
11045       execSetupGame_setNetworkServerText();
11046
11047       DrawSetupScreen();
11048
11049       break;
11050     }
11051
11052     default:
11053       break;
11054   }
11055 }
11056
11057 void HandleScreenGadgetKeys(Key key)
11058 {
11059   if (key == setup.shortcut.tape_play || key == KSYM_Return)
11060     HandleScreenGadgets(screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE]);
11061 }
11062
11063 void DumpScreenIdentifiers(void)
11064 {
11065   int i;
11066
11067   Print("Active screen elements on current screen:\n");
11068
11069   for (i = 0; main_controls[i].nr != -1; i++)
11070   {
11071     struct MainControlInfo *mci = &main_controls[i];
11072
11073     if (mci->button_graphic != -1)
11074     {
11075       char *token = getTokenFromImageID(mci->button_graphic);
11076
11077       Print("- '%s'\n", token);
11078     }
11079   }
11080
11081   Print("Done.\n");
11082 }
11083
11084 boolean DoScreenAction(int image_id)
11085 {
11086   int i;
11087
11088   if (game_status != GAME_MODE_MAIN)
11089     return FALSE;
11090
11091   for (i = 0; main_controls[i].nr != -1; i++)
11092   {
11093     struct MainControlInfo *mci = &main_controls[i];
11094     struct MenuPosInfo *pos = mci->pos_button;
11095
11096     if (mci->button_graphic == image_id)
11097     {
11098       int x = mSX + pos->x;
11099       int y = mSY + pos->y;
11100
11101       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
11102
11103       return TRUE;
11104     }
11105   }
11106
11107   return FALSE;
11108 }
11109
11110 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
11111 {
11112   // get tree info node of newly added level or artwork set
11113   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
11114   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
11115                                                       tree_subdir_new);
11116   if (tree_node_new == NULL)    // should not happen
11117     return;
11118
11119   // if request dialog is active, do nothing
11120   if (game.request_active)
11121     return;
11122
11123   if (game_status == GAME_MODE_MAIN &&
11124       tree_type == TREE_TYPE_LEVEL_DIR)
11125   {
11126     // when adding new level set in main menu, select it as current level set
11127
11128     // change current level set to newly added level set from zip file
11129     leveldir_current = tree_node_new;
11130
11131     // change current level number to first level of newly added level set
11132     level_nr = leveldir_current->first_level;
11133
11134     // redraw screen to reflect changed level set
11135     DrawMainMenu();
11136
11137     // save this level set and level number as last selected level set
11138     SaveLevelSetup_LastSeries();
11139     SaveLevelSetup_SeriesInfo();
11140   }
11141   else if (game_status == GAME_MODE_LEVELS &&
11142            tree_type == TREE_TYPE_LEVEL_DIR)
11143   {
11144     // when adding new level set in level set menu, set cursor and update screen
11145
11146     leveldir_current = tree_node_new;
11147
11148     DrawChooseTree(&leveldir_current);
11149   }
11150   else if (game_status == GAME_MODE_SETUP)
11151   {
11152     // when adding new artwork set in setup menu, set cursor and update screen
11153
11154     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
11155         tree_type == TREE_TYPE_GRAPHICS_DIR)
11156     {
11157       artwork.gfx_current = tree_node_new;
11158
11159       DrawChooseTree(&artwork.gfx_current);
11160     }
11161     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
11162              tree_type == TREE_TYPE_SOUNDS_DIR)
11163     {
11164       artwork.snd_current = tree_node_new;
11165
11166       DrawChooseTree(&artwork.snd_current);
11167     }
11168     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
11169              tree_type == TREE_TYPE_MUSIC_DIR)
11170     {
11171       artwork.mus_current = tree_node_new;
11172
11173       DrawChooseTree(&artwork.mus_current);
11174     }
11175   }
11176 }
11177
11178 static int UploadTapes(void)
11179 {
11180   SetGameStatus(GAME_MODE_LOADING);
11181
11182   FadeSetEnterScreen();
11183   FadeOut(REDRAW_ALL);
11184
11185   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
11186
11187   FadeIn(REDRAW_ALL);
11188
11189   DrawInitTextHead("Uploading tapes");
11190
11191   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
11192   global.autoplay_leveldir = "ALL";
11193   global.autoplay_all = TRUE;
11194
11195   int num_tapes_uploaded = AutoPlayTapes();
11196
11197   global.autoplay_mode = AUTOPLAY_MODE_NONE;
11198   global.autoplay_leveldir = NULL;
11199   global.autoplay_all = FALSE;
11200
11201   SetGameStatus(GAME_MODE_MAIN);
11202
11203   DrawMainMenu();
11204
11205   return num_tapes_uploaded;
11206 }
11207
11208 static boolean OfferUploadTapes(void)
11209 {
11210   if (!Request(setup.has_remaining_tapes ?
11211                "Upload missing tapes to the high score server now?" :
11212                "Upload all your tapes to the high score server now?", REQ_ASK))
11213     return FALSE;
11214
11215   // when uploading tapes, make sure that high score server is enabled
11216   runtime.use_api_server = setup.use_api_server = TRUE;
11217
11218   int num_tapes_uploaded = UploadTapes();
11219   char message[100];
11220
11221   if (num_tapes_uploaded < 0)
11222   {
11223     num_tapes_uploaded = -num_tapes_uploaded - 1;
11224
11225     if (num_tapes_uploaded == 0)
11226       sprintf(message, "Upload failed! No tapes uploaded!");
11227     else if (num_tapes_uploaded == 1)
11228       sprintf(message, "Upload failed! Only 1 tape uploaded!");
11229     else
11230       sprintf(message, "Upload failed! Only %d tapes uploaded!",
11231               num_tapes_uploaded);
11232
11233     Request(message, REQ_CONFIRM);
11234
11235     // if uploading tapes failed, add tape upload entry to setup menu
11236     setup.provide_uploading_tapes = TRUE;
11237     setup.has_remaining_tapes = TRUE;
11238
11239     SaveSetup_ServerSetup();
11240
11241     return FALSE;
11242   }
11243
11244   if (num_tapes_uploaded == 0)
11245     sprintf(message, "No tapes uploaded!");
11246   else if (num_tapes_uploaded == 1)
11247     sprintf(message, "1 tape uploaded!");
11248   else
11249     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
11250
11251   Request(message, REQ_CONFIRM);
11252
11253   if (num_tapes_uploaded > 0)
11254     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
11255
11256   // after all tapes have been uploaded, remove entry from setup menu
11257   setup.provide_uploading_tapes = FALSE;
11258   setup.has_remaining_tapes = FALSE;
11259
11260   SaveSetup_ServerSetup();
11261
11262   return TRUE;
11263 }
11264
11265 static void CheckUploadTapes(void)
11266 {
11267   if (!setup.ask_for_uploading_tapes)
11268     return;
11269
11270   // after asking for uploading tapes, do not ask again
11271   setup.ask_for_uploading_tapes = FALSE;
11272   setup.ask_for_remaining_tapes = FALSE;
11273
11274   if (directoryExists(getTapeDir(NULL)))
11275   {
11276     boolean tapes_uploaded = OfferUploadTapes();
11277
11278     if (!tapes_uploaded)
11279     {
11280       Request(setup.has_remaining_tapes ?
11281               "You can upload missing tapes from the setup menu later!" :
11282               "You can upload your tapes from the setup menu later!",
11283               REQ_CONFIRM);
11284     }
11285   }
11286   else
11287   {
11288     // if tapes directory does not exist yet, never offer uploading all tapes
11289     setup.provide_uploading_tapes = FALSE;
11290   }
11291
11292   SaveSetup_ServerSetup();
11293 }
11294
11295 static void UpgradePlayerUUID(void)
11296 {
11297   ApiResetUUIDAsThread(getUUID());
11298 }
11299
11300 static void CheckUpgradePlayerUUID(void)
11301 {
11302   if (setup.player_version > 1)
11303     return;
11304
11305   UpgradePlayerUUID();
11306 }
11307
11308 void CheckApiServerTasks(void)
11309 {
11310   // check if the player's UUID has to be upgraded
11311   CheckUpgradePlayerUUID();
11312
11313   // check if there are any tapes to be uploaded
11314   CheckUploadTapes();
11315 }