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