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