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