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