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