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