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