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