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