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