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