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