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