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