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