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