2f2352cde7798033142a951dc9c2568d96352d8b
[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 score 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   FadeOut(REDRAW_FIELD);
5537
5538   // needed if different viewport properties defined after playing score tape
5539   ChangeViewportPropertiesIfNeeded();
5540
5541   // set this after "ChangeViewportPropertiesIfNeeded()" (which may reset it)
5542   SetDrawDeactivationMask(REDRAW_NONE);
5543   SetDrawBackgroundMask(REDRAW_FIELD);
5544
5545   // needed if different background image defined after playing score tape
5546   SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
5547   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_SCOREINFO);
5548
5549   // special compatibility handling for "Snake Bite" graphics set
5550   if (strPrefix(leveldir_current->identifier, "snake_bite"))
5551     ClearRectangle(gfx.background_bitmap, gfx.real_sx, gfx.real_sy + 64,
5552                    gfx.full_sxsize, gfx.full_sysize - 64);
5553
5554   DrawScoreInfo_Content(entry_nr);
5555
5556   // map gadgets for score info screen
5557   MapScreenMenuGadgets(SCREEN_MASK_SCORES_INFO);
5558
5559   FadeIn(REDRAW_FIELD);
5560 }
5561
5562 static void HandleScoreInfo_SelectScore(int step, int direction)
5563 {
5564   int old_entry_nr = scores.last_entry_nr;
5565   int new_entry_nr = old_entry_nr + step * direction;
5566   int num_nodes = numTreeInfoInGroup(score_entry_current);
5567   int num_entries = num_nodes - 1;      // score nodes only, without back link
5568
5569   if (new_entry_nr < 0)
5570     new_entry_nr = 0;
5571   if (new_entry_nr > num_entries - 1)
5572     new_entry_nr = num_entries - 1;
5573
5574   if (new_entry_nr != old_entry_nr)
5575   {
5576     scores.last_entry_nr = new_entry_nr;
5577
5578     DrawScoreInfo_Content(new_entry_nr);
5579   }
5580 }
5581
5582 static void HandleScoreInfo_PlayTape(void)
5583 {
5584   if (!PlayScoreTape(scores.last_entry_nr))
5585   {
5586     DrawScoreInfo_Content(scores.last_entry_nr);
5587
5588     FadeIn(REDRAW_FIELD);
5589   }
5590 }
5591
5592 void HandleScoreInfo(int mx, int my, int dx, int dy, int button)
5593 {
5594   boolean button_action = (button == MB_MENU_LEAVE || button == MB_MENU_CHOICE);
5595   boolean button_is_valid = (mx >= 0 && my >= 0);
5596   boolean button_screen_clicked = (button_action && button_is_valid);
5597
5598   if (server_scores.updated)
5599   {
5600     // reload scores, using updated server score cache file
5601     LoadLocalAndServerScore(scores.last_level_nr, FALSE);
5602
5603     server_scores.updated = FALSE;
5604
5605     DrawHallOfFame_setScoreEntries();
5606
5607     DrawScoreInfo_Content(scores.last_entry_nr);
5608   }
5609
5610   if (button_screen_clicked)
5611   {
5612     PlaySound(SND_MENU_ITEM_SELECTING);
5613
5614     SetGameStatus(GAME_MODE_SCORES);
5615
5616     DrawHallOfFame(scores.last_level_nr);
5617   }
5618   else if (dx)
5619   {
5620     HandleHallOfFame_SelectLevel(1, SIGN(dx) * (ABS(dx) > 1 ? 10 : 1));
5621   }
5622   else if (dy)
5623   {
5624     HandleScoreInfo_SelectScore(1, SIGN(dy) * (ABS(dy) > 1 ? 10 : 1));
5625   }
5626 }
5627
5628
5629 // ============================================================================
5630 // setup screen functions
5631 // ============================================================================
5632
5633 static struct TokenInfo *setup_info;
5634 static int num_setup_info;      // number of setup entries shown on screen
5635 static int max_setup_info;      // total number of setup entries in list
5636
5637 static char *window_size_text;
5638 static char *scaling_type_text;
5639 static char *rendering_mode_text;
5640 static char *vsync_mode_text;
5641 static char *scroll_delay_text;
5642 static char *snapshot_mode_text;
5643 static char *game_speed_text;
5644 static char *scores_type_text;
5645 static char *network_server_text;
5646 static char *graphics_set_name;
5647 static char *sounds_set_name;
5648 static char *music_set_name;
5649 static char *volume_simple_text;
5650 static char *volume_loops_text;
5651 static char *volume_music_text;
5652 static char *touch_controls_text;
5653 static char *move_distance_text;
5654 static char *drop_distance_text;
5655 static char *transparency_text;
5656 static char *grid_size_text[2][2];
5657
5658 static void execSetupMain(void)
5659 {
5660   setup_mode = SETUP_MODE_MAIN;
5661
5662   DrawSetupScreen();
5663 }
5664
5665 static void execSetupGame_setScoresType(void)
5666 {
5667   if (scores_types == NULL)
5668   {
5669     int i;
5670
5671     for (i = 0; scores_types_list[i].value != NULL; i++)
5672     {
5673       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5674       char identifier[32], name[32];
5675       char *value = scores_types_list[i].value;
5676       char *text = scores_types_list[i].text;
5677
5678       ti->node_top = &scores_types;
5679       ti->sort_priority = i;
5680
5681       sprintf(identifier, "%s", value);
5682       sprintf(name, "%s", text);
5683
5684       setString(&ti->identifier, identifier);
5685       setString(&ti->name, name);
5686       setString(&ti->name_sorting, name);
5687       setString(&ti->infotext, STR_SETUP_CHOOSE_SCORES_TYPE);
5688
5689       pushTreeInfo(&scores_types, ti);
5690     }
5691
5692     // sort scores type values to start with lowest scores type value
5693     sortTreeInfo(&scores_types);
5694
5695     // set current scores type value to configured scores type value
5696     scores_type_current =
5697       getTreeInfoFromIdentifier(scores_types, setup.scores_in_highscore_list);
5698
5699     // if that fails, set current scores type to reliable default value
5700     if (scores_type_current == NULL)
5701       scores_type_current =
5702         getTreeInfoFromIdentifier(scores_types, STR_SCORES_TYPE_DEFAULT);
5703
5704     // if that also fails, set current scores type to first available value
5705     if (scores_type_current == NULL)
5706       scores_type_current = scores_types;
5707   }
5708
5709   setup.scores_in_highscore_list = scores_type_current->identifier;
5710
5711   // needed for displaying scores type text instead of identifier
5712   scores_type_text = scores_type_current->name;
5713 }
5714
5715 static void execSetupGame_setGameSpeeds(boolean update_value)
5716 {
5717   if (setup.game_speed_extended)
5718   {
5719     game_speeds_list = game_speeds_list_extended;
5720     game_speeds      = game_speeds_extended;
5721   }
5722   else
5723   {
5724     game_speeds_list = game_speeds_list_normal;
5725     game_speeds      = game_speeds_normal;
5726   }
5727
5728   if (game_speeds == NULL)
5729   {
5730     int i;
5731
5732     for (i = 0; game_speeds_list[i].value != -1; i++)
5733     {
5734       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5735       char identifier[32], name[32];
5736       int value = game_speeds_list[i].value;
5737       char *text = game_speeds_list[i].text;
5738
5739       ti->node_top = &game_speeds;
5740       ti->sort_priority = 10000 - value;
5741
5742       sprintf(identifier, "%d", value);
5743       sprintf(name, "%s", text);
5744
5745       setString(&ti->identifier, identifier);
5746       setString(&ti->name, name);
5747       setString(&ti->name_sorting, name);
5748       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_SPEED);
5749
5750       pushTreeInfo(&game_speeds, ti);
5751     }
5752
5753     // sort game speed values to start with slowest game speed
5754     sortTreeInfo(&game_speeds);
5755
5756     update_value = TRUE;
5757   }
5758
5759   if (update_value)
5760   {
5761     // set current game speed to configured game speed value
5762     game_speed_current =
5763       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
5764
5765     // if that fails, set current game speed to reliable default value
5766     if (game_speed_current == NULL)
5767       game_speed_current =
5768         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
5769
5770     // if that also fails, set current game speed to first available speed
5771     if (game_speed_current == NULL)
5772       game_speed_current = game_speeds;
5773
5774     if (setup.game_speed_extended)
5775       game_speeds_extended = game_speeds;
5776     else
5777       game_speeds_normal = game_speeds;
5778   }
5779
5780   setup.game_frame_delay = atoi(game_speed_current->identifier);
5781
5782   // needed for displaying game speed text instead of identifier
5783   game_speed_text = game_speed_current->name;
5784 }
5785
5786 static void execSetupGame_setScrollDelays(void)
5787 {
5788   if (scroll_delays == NULL)
5789   {
5790     int i;
5791
5792     for (i = 0; scroll_delays_list[i].value != -1; i++)
5793     {
5794       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5795       char identifier[32], name[32];
5796       int value = scroll_delays_list[i].value;
5797       char *text = scroll_delays_list[i].text;
5798
5799       ti->node_top = &scroll_delays;
5800       ti->sort_priority = value;
5801
5802       sprintf(identifier, "%d", value);
5803       sprintf(name, "%s", text);
5804
5805       setString(&ti->identifier, identifier);
5806       setString(&ti->name, name);
5807       setString(&ti->name_sorting, name);
5808       setString(&ti->infotext, STR_SETUP_CHOOSE_SCROLL_DELAY);
5809
5810       pushTreeInfo(&scroll_delays, ti);
5811     }
5812
5813     // sort scroll delay values to start with lowest scroll delay value
5814     sortTreeInfo(&scroll_delays);
5815
5816     // set current scroll delay value to configured scroll delay value
5817     scroll_delay_current =
5818       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
5819
5820     // if that fails, set current scroll delay to reliable default value
5821     if (scroll_delay_current == NULL)
5822       scroll_delay_current =
5823         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
5824
5825     // if that also fails, set current scroll delay to first available value
5826     if (scroll_delay_current == NULL)
5827       scroll_delay_current = scroll_delays;
5828   }
5829
5830   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
5831
5832   // needed for displaying scroll delay text instead of identifier
5833   scroll_delay_text = scroll_delay_current->name;
5834 }
5835
5836 static void execSetupGame_setSnapshotModes(void)
5837 {
5838   if (snapshot_modes == NULL)
5839   {
5840     int i;
5841
5842     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
5843     {
5844       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5845       char identifier[32], name[32];
5846       char *value = snapshot_modes_list[i].value;
5847       char *text = snapshot_modes_list[i].text;
5848
5849       ti->node_top = &snapshot_modes;
5850       ti->sort_priority = i;
5851
5852       sprintf(identifier, "%s", value);
5853       sprintf(name, "%s", text);
5854
5855       setString(&ti->identifier, identifier);
5856       setString(&ti->name, name);
5857       setString(&ti->name_sorting, name);
5858       setString(&ti->infotext, STR_SETUP_CHOOSE_SNAPSHOT_MODE);
5859
5860       pushTreeInfo(&snapshot_modes, ti);
5861     }
5862
5863     // sort snapshot mode values to start with lowest snapshot mode value
5864     sortTreeInfo(&snapshot_modes);
5865
5866     // set current snapshot mode value to configured snapshot mode value
5867     snapshot_mode_current =
5868       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
5869
5870     // if that fails, set current snapshot mode to reliable default value
5871     if (snapshot_mode_current == NULL)
5872       snapshot_mode_current =
5873         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
5874
5875     // if that also fails, set current snapshot mode to first available value
5876     if (snapshot_mode_current == NULL)
5877       snapshot_mode_current = snapshot_modes;
5878   }
5879
5880   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
5881
5882   // needed for displaying snapshot mode text instead of identifier
5883   snapshot_mode_text = snapshot_mode_current->name;
5884 }
5885
5886 static void execSetupGame_setNetworkServerText(void)
5887 {
5888   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
5889   {
5890     strcpy(network_server_hostname, STR_NETWORK_AUTO_DETECT_SETUP);
5891   }
5892   else
5893   {
5894     strncpy(network_server_hostname, setup.network_server_hostname,
5895             MAX_SETUP_TEXT_INPUT_LEN);
5896     network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN] = '\0';
5897   }
5898
5899   // needed for displaying network server text instead of identifier
5900   network_server_text = network_server_hostname;
5901 }
5902
5903 static void execSetupGame(void)
5904 {
5905   boolean check_vsync_mode = (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED);
5906
5907   execSetupGame_setGameSpeeds(FALSE);
5908   execSetupGame_setScoresType();
5909   execSetupGame_setScrollDelays();
5910   execSetupGame_setSnapshotModes();
5911
5912   execSetupGame_setNetworkServerText();
5913
5914   if (!setup.provide_uploading_tapes)
5915     setHideSetupEntry(execOfferUploadTapes);
5916
5917   setup_mode = SETUP_MODE_GAME;
5918
5919   DrawSetupScreen();
5920
5921   // check if vsync needs to be disabled for this game speed to work
5922   if (check_vsync_mode)
5923     DisableVsyncIfNeeded();
5924 }
5925
5926 static void execSetupChooseScoresType(void)
5927 {
5928   setup_mode = SETUP_MODE_CHOOSE_SCORES_TYPE;
5929
5930   DrawSetupScreen();
5931 }
5932
5933 static void execSetupChooseGameSpeed(void)
5934 {
5935   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
5936
5937   DrawSetupScreen();
5938 }
5939
5940 static void execSetupChooseScrollDelay(void)
5941 {
5942   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
5943
5944   DrawSetupScreen();
5945 }
5946
5947 static void execSetupChooseSnapshotMode(void)
5948 {
5949   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
5950
5951   DrawSetupScreen();
5952 }
5953
5954 static void execSetupEngines(void)
5955 {
5956   setup_mode = SETUP_MODE_ENGINES;
5957
5958   DrawSetupScreen();
5959 }
5960
5961 static void execSetupEditor(void)
5962 {
5963   setup_mode = SETUP_MODE_EDITOR;
5964
5965   DrawSetupScreen();
5966 }
5967
5968 static void execSetupGraphics_setWindowSizes(boolean update_list)
5969 {
5970   if (window_sizes != NULL && update_list)
5971   {
5972     freeTreeInfo(window_sizes);
5973
5974     window_sizes = NULL;
5975   }
5976
5977   if (window_sizes == NULL)
5978   {
5979     boolean current_window_size_found = FALSE;
5980     int i;
5981
5982     for (i = 0; window_sizes_list[i].value != -1; i++)
5983     {
5984       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5985       char identifier[32], name[32];
5986       int value = window_sizes_list[i].value;
5987       char *text = window_sizes_list[i].text;
5988
5989       ti->node_top = &window_sizes;
5990       ti->sort_priority = value;
5991
5992       sprintf(identifier, "%d", value);
5993       sprintf(name, "%s", text);
5994
5995       setString(&ti->identifier, identifier);
5996       setString(&ti->name, name);
5997       setString(&ti->name_sorting, name);
5998       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
5999
6000       pushTreeInfo(&window_sizes, ti);
6001
6002       if (value == setup.window_scaling_percent)
6003         current_window_size_found = TRUE;
6004     }
6005
6006     if (!current_window_size_found)
6007     {
6008       // add entry for non-preset window scaling value
6009
6010       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6011       char identifier[32], name[32];
6012       int value = setup.window_scaling_percent;
6013
6014       ti->node_top = &window_sizes;
6015       ti->sort_priority = value;
6016
6017       sprintf(identifier, "%d", value);
6018       sprintf(name, "%d %% (Current)", value);
6019
6020       setString(&ti->identifier, identifier);
6021       setString(&ti->name, name);
6022       setString(&ti->name_sorting, name);
6023       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6024
6025       pushTreeInfo(&window_sizes, ti);
6026     }
6027
6028     // sort window size values to start with lowest window size value
6029     sortTreeInfo(&window_sizes);
6030
6031     // set current window size value to configured window size value
6032     window_size_current =
6033       getTreeInfoFromIdentifier(window_sizes,
6034                                 i_to_a(setup.window_scaling_percent));
6035
6036     // if that fails, set current window size to reliable default value
6037     if (window_size_current == NULL)
6038       window_size_current =
6039         getTreeInfoFromIdentifier(window_sizes,
6040                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
6041
6042     // if that also fails, set current window size to first available value
6043     if (window_size_current == NULL)
6044       window_size_current = window_sizes;
6045   }
6046
6047   setup.window_scaling_percent = atoi(window_size_current->identifier);
6048
6049   // needed for displaying window size text instead of identifier
6050   window_size_text = window_size_current->name;
6051 }
6052
6053 static void execSetupGraphics_setScalingTypes(void)
6054 {
6055   if (scaling_types == NULL)
6056   {
6057     int i;
6058
6059     for (i = 0; scaling_types_list[i].value != NULL; i++)
6060     {
6061       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6062       char identifier[32], name[32];
6063       char *value = scaling_types_list[i].value;
6064       char *text = scaling_types_list[i].text;
6065
6066       ti->node_top = &scaling_types;
6067       ti->sort_priority = i;
6068
6069       sprintf(identifier, "%s", value);
6070       sprintf(name, "%s", text);
6071
6072       setString(&ti->identifier, identifier);
6073       setString(&ti->name, name);
6074       setString(&ti->name_sorting, name);
6075       setString(&ti->infotext, STR_SETUP_CHOOSE_SCALING_TYPE);
6076
6077       pushTreeInfo(&scaling_types, ti);
6078     }
6079
6080     // sort scaling type values to start with lowest scaling type value
6081     sortTreeInfo(&scaling_types);
6082
6083     // set current scaling type value to configured scaling type value
6084     scaling_type_current =
6085       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
6086
6087     // if that fails, set current scaling type to reliable default value
6088     if (scaling_type_current == NULL)
6089       scaling_type_current =
6090         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
6091
6092     // if that also fails, set current scaling type to first available value
6093     if (scaling_type_current == NULL)
6094       scaling_type_current = scaling_types;
6095   }
6096
6097   setup.window_scaling_quality = scaling_type_current->identifier;
6098
6099   // needed for displaying scaling type text instead of identifier
6100   scaling_type_text = scaling_type_current->name;
6101 }
6102
6103 static void execSetupGraphics_setRenderingModes(void)
6104 {
6105   if (rendering_modes == NULL)
6106   {
6107     int i;
6108
6109     for (i = 0; rendering_modes_list[i].value != NULL; i++)
6110     {
6111       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6112       char identifier[32], name[32];
6113       char *value = rendering_modes_list[i].value;
6114       char *text = rendering_modes_list[i].text;
6115
6116       ti->node_top = &rendering_modes;
6117       ti->sort_priority = i;
6118
6119       sprintf(identifier, "%s", value);
6120       sprintf(name, "%s", text);
6121
6122       setString(&ti->identifier, identifier);
6123       setString(&ti->name, name);
6124       setString(&ti->name_sorting, name);
6125       setString(&ti->infotext, STR_SETUP_CHOOSE_RENDERING);
6126
6127       pushTreeInfo(&rendering_modes, ti);
6128     }
6129
6130     // sort rendering mode values to start with lowest rendering mode value
6131     sortTreeInfo(&rendering_modes);
6132
6133     // set current rendering mode value to configured rendering mode value
6134     rendering_mode_current =
6135       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
6136
6137     // if that fails, set current rendering mode to reliable default value
6138     if (rendering_mode_current == NULL)
6139       rendering_mode_current =
6140         getTreeInfoFromIdentifier(rendering_modes,
6141                                   STR_SPECIAL_RENDERING_DEFAULT);
6142
6143     // if that also fails, set current rendering mode to first available one
6144     if (rendering_mode_current == NULL)
6145       rendering_mode_current = rendering_modes;
6146   }
6147
6148   setup.screen_rendering_mode = rendering_mode_current->identifier;
6149
6150   // needed for displaying rendering mode text instead of identifier
6151   rendering_mode_text = rendering_mode_current->name;
6152 }
6153
6154 static void execSetupGraphics_setVsyncModes(boolean update_value)
6155 {
6156   if (vsync_modes == NULL)
6157   {
6158     int i;
6159
6160     for (i = 0; vsync_modes_list[i].value != NULL; i++)
6161     {
6162       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6163       char identifier[32], name[32];
6164       char *value = vsync_modes_list[i].value;
6165       char *text = vsync_modes_list[i].text;
6166
6167       ti->node_top = &vsync_modes;
6168       ti->sort_priority = i;
6169
6170       sprintf(identifier, "%s", value);
6171       sprintf(name, "%s", text);
6172
6173       setString(&ti->identifier, identifier);
6174       setString(&ti->name, name);
6175       setString(&ti->name_sorting, name);
6176       setString(&ti->infotext, STR_SETUP_CHOOSE_VSYNC);
6177
6178       pushTreeInfo(&vsync_modes, ti);
6179     }
6180
6181     // sort vsync mode values to start with lowest vsync mode value
6182     sortTreeInfo(&vsync_modes);
6183
6184     update_value = TRUE;
6185   }
6186
6187   if (update_value)
6188   {
6189     // set current vsync mode value to configured vsync mode value
6190     vsync_mode_current =
6191       getTreeInfoFromIdentifier(vsync_modes, setup.vsync_mode);
6192
6193     // if that fails, set current vsync mode to reliable default value
6194     if (vsync_mode_current == NULL)
6195       vsync_mode_current =
6196         getTreeInfoFromIdentifier(vsync_modes, STR_VSYNC_MODE_DEFAULT);
6197
6198     // if that also fails, set current vsync mode to first available one
6199     if (vsync_mode_current == NULL)
6200       vsync_mode_current = vsync_modes;
6201   }
6202
6203   setup.vsync_mode = vsync_mode_current->identifier;
6204
6205   // needed for displaying vsync mode text instead of identifier
6206   vsync_mode_text = vsync_mode_current->name;
6207 }
6208
6209 static void execSetupGraphics(void)
6210 {
6211   boolean check_game_speed = (setup_mode == SETUP_MODE_CHOOSE_VSYNC);
6212
6213   // update "setup.window_scaling_percent" from list selection
6214   // (in this case, window scaling was changed on setup screen)
6215   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6216     execSetupGraphics_setWindowSizes(FALSE);
6217
6218   // update "setup.vsync_mode" from list selection
6219   // (in this case, vsync mode was changed on setup screen)
6220   if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
6221     execSetupGraphics_setVsyncModes(FALSE);
6222
6223   // update list selection from "setup.window_scaling_percent"
6224   // (window scaling may have changed by resizing the window)
6225   execSetupGraphics_setWindowSizes(TRUE);
6226
6227   // update list selection from "setup.vsync_mode"
6228   // (vsync_mode may have changed by re-creating the renderer)
6229   execSetupGraphics_setVsyncModes(TRUE);
6230
6231   execSetupGraphics_setScalingTypes();
6232   execSetupGraphics_setRenderingModes();
6233
6234   setup_mode = SETUP_MODE_GRAPHICS;
6235
6236   DrawSetupScreen();
6237
6238   // check if game speed is high enough for 60 Hz vsync to work
6239   if (check_game_speed)
6240     ModifyGameSpeedIfNeeded();
6241
6242   // window scaling may have changed at this point
6243   ChangeWindowScalingIfNeeded();
6244
6245   // window scaling quality may have changed at this point
6246   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
6247     SDLSetWindowScalingQuality(setup.window_scaling_quality);
6248
6249   // screen rendering mode may have changed at this point
6250   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
6251
6252   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
6253   int video_vsync_mode = video.vsync_mode;
6254
6255   // screen vsync mode may have changed at this point
6256   ChangeVsyncModeIfNeeded();
6257
6258   // check if setting vsync mode to selected value failed
6259   if (setup_vsync_mode != video_vsync_mode &&
6260       setup_vsync_mode != video.vsync_mode)
6261   {
6262     // changing vsync mode to selected value failed -- reset displayed value
6263     execSetupGraphics_setVsyncModes(TRUE);
6264
6265     Request("Setting VSync failed!", REQ_CONFIRM);
6266
6267     DrawSetupScreen();
6268   }
6269 }
6270
6271 static void execSetupChooseWindowSize(void)
6272 {
6273   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
6274
6275   DrawSetupScreen();
6276 }
6277
6278 static void execSetupChooseScalingType(void)
6279 {
6280   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
6281
6282   DrawSetupScreen();
6283 }
6284
6285 static void execSetupChooseRenderingMode(void)
6286 {
6287   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
6288
6289   DrawSetupScreen();
6290 }
6291
6292 static void execSetupChooseVsyncMode(void)
6293 {
6294   setup_mode = SETUP_MODE_CHOOSE_VSYNC;
6295
6296   DrawSetupScreen();
6297 }
6298
6299 static void execSetupChooseVolumeSimple(void)
6300 {
6301   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
6302
6303   DrawSetupScreen();
6304 }
6305
6306 static void execSetupChooseVolumeLoops(void)
6307 {
6308   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
6309
6310   DrawSetupScreen();
6311 }
6312
6313 static void execSetupChooseVolumeMusic(void)
6314 {
6315   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
6316
6317   DrawSetupScreen();
6318 }
6319
6320 static void execSetupSound(void)
6321 {
6322   if (volumes_simple == NULL)
6323   {
6324     boolean current_volume_simple_found = FALSE;
6325     int i;
6326
6327     for (i = 0; volumes_list[i].value != -1; i++)
6328     {
6329       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6330       char identifier[32], name[32];
6331       int value = volumes_list[i].value;
6332       char *text = volumes_list[i].text;
6333
6334       ti->node_top = &volumes_simple;
6335       ti->sort_priority = value;
6336
6337       sprintf(identifier, "%d", value);
6338       sprintf(name, "%s", text);
6339
6340       setString(&ti->identifier, identifier);
6341       setString(&ti->name, name);
6342       setString(&ti->name_sorting, name);
6343       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6344
6345       pushTreeInfo(&volumes_simple, ti);
6346
6347       if (value == setup.volume_simple)
6348         current_volume_simple_found = TRUE;
6349     }
6350
6351     if (!current_volume_simple_found)
6352     {
6353       // add entry for non-preset volume value
6354
6355       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6356       char identifier[32], name[32];
6357       int value = setup.volume_simple;
6358
6359       ti->node_top = &volumes_simple;
6360       ti->sort_priority = value;
6361
6362       sprintf(identifier, "%d", value);
6363       sprintf(name, "%d %% (Current)", value);
6364
6365       setString(&ti->identifier, identifier);
6366       setString(&ti->name, name);
6367       setString(&ti->name_sorting, name);
6368       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6369
6370       pushTreeInfo(&volumes_simple, ti);
6371     }
6372
6373     // sort volume values to start with lowest volume value
6374     sortTreeInfo(&volumes_simple);
6375
6376     // set current volume value to configured volume value
6377     volume_simple_current =
6378       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
6379
6380     // if that fails, set current volume to reliable default value
6381     if (volume_simple_current == NULL)
6382       volume_simple_current =
6383         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
6384
6385     // if that also fails, set current volume to first available value
6386     if (volume_simple_current == NULL)
6387       volume_simple_current = volumes_simple;
6388   }
6389
6390   if (volumes_loops == NULL)
6391   {
6392     boolean current_volume_loops_found = FALSE;
6393     int i;
6394
6395     for (i = 0; volumes_list[i].value != -1; i++)
6396     {
6397       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6398       char identifier[32], name[32];
6399       int value = volumes_list[i].value;
6400       char *text = volumes_list[i].text;
6401
6402       ti->node_top = &volumes_loops;
6403       ti->sort_priority = value;
6404
6405       sprintf(identifier, "%d", value);
6406       sprintf(name, "%s", text);
6407
6408       setString(&ti->identifier, identifier);
6409       setString(&ti->name, name);
6410       setString(&ti->name_sorting, name);
6411       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6412
6413       pushTreeInfo(&volumes_loops, ti);
6414
6415       if (value == setup.volume_loops)
6416         current_volume_loops_found = TRUE;
6417     }
6418
6419     if (!current_volume_loops_found)
6420     {
6421       // add entry for non-preset volume value
6422
6423       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6424       char identifier[32], name[32];
6425       int value = setup.volume_loops;
6426
6427       ti->node_top = &volumes_loops;
6428       ti->sort_priority = value;
6429
6430       sprintf(identifier, "%d", value);
6431       sprintf(name, "%d %% (Current)", value);
6432
6433       setString(&ti->identifier, identifier);
6434       setString(&ti->name, name);
6435       setString(&ti->name_sorting, name);
6436       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6437
6438       pushTreeInfo(&volumes_loops, ti);
6439     }
6440
6441     // sort volume values to start with lowest volume value
6442     sortTreeInfo(&volumes_loops);
6443
6444     // set current volume value to configured volume value
6445     volume_loops_current =
6446       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
6447
6448     // if that fails, set current volume to reliable default value
6449     if (volume_loops_current == NULL)
6450       volume_loops_current =
6451         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
6452
6453     // if that also fails, set current volume to first available value
6454     if (volume_loops_current == NULL)
6455       volume_loops_current = volumes_loops;
6456   }
6457
6458   if (volumes_music == NULL)
6459   {
6460     boolean current_volume_music_found = FALSE;
6461     int i;
6462
6463     for (i = 0; volumes_list[i].value != -1; i++)
6464     {
6465       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6466       char identifier[32], name[32];
6467       int value = volumes_list[i].value;
6468       char *text = volumes_list[i].text;
6469
6470       ti->node_top = &volumes_music;
6471       ti->sort_priority = value;
6472
6473       sprintf(identifier, "%d", value);
6474       sprintf(name, "%s", text);
6475
6476       setString(&ti->identifier, identifier);
6477       setString(&ti->name, name);
6478       setString(&ti->name_sorting, name);
6479       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6480
6481       pushTreeInfo(&volumes_music, ti);
6482
6483       if (value == setup.volume_music)
6484         current_volume_music_found = TRUE;
6485     }
6486
6487     if (!current_volume_music_found)
6488     {
6489       // add entry for non-preset volume value
6490
6491       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6492       char identifier[32], name[32];
6493       int value = setup.volume_music;
6494
6495       ti->node_top = &volumes_music;
6496       ti->sort_priority = value;
6497
6498       sprintf(identifier, "%d", value);
6499       sprintf(name, "%d %% (Current)", value);
6500
6501       setString(&ti->identifier, identifier);
6502       setString(&ti->name, name);
6503       setString(&ti->name_sorting, name);
6504       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6505
6506       pushTreeInfo(&volumes_music, ti);
6507     }
6508
6509     // sort volume values to start with lowest volume value
6510     sortTreeInfo(&volumes_music);
6511
6512     // set current volume value to configured volume value
6513     volume_music_current =
6514       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
6515
6516     // if that fails, set current volume to reliable default value
6517     if (volume_music_current == NULL)
6518       volume_music_current =
6519         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
6520
6521     // if that also fails, set current volume to first available value
6522     if (volume_music_current == NULL)
6523       volume_music_current = volumes_music;
6524   }
6525
6526   setup.volume_simple = atoi(volume_simple_current->identifier);
6527   setup.volume_loops  = atoi(volume_loops_current->identifier);
6528   setup.volume_music  = atoi(volume_music_current->identifier);
6529
6530   // needed for displaying volume text instead of identifier
6531   volume_simple_text = volume_simple_current->name;
6532   volume_loops_text = volume_loops_current->name;
6533   volume_music_text = volume_music_current->name;
6534
6535   setup_mode = SETUP_MODE_SOUND;
6536
6537   DrawSetupScreen();
6538 }
6539
6540 static void execSetupChooseTouchControls(void)
6541 {
6542   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
6543
6544   DrawSetupScreen();
6545 }
6546
6547 static void execSetupChooseMoveDistance(void)
6548 {
6549   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
6550
6551   DrawSetupScreen();
6552 }
6553
6554 static void execSetupChooseDropDistance(void)
6555 {
6556   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
6557
6558   DrawSetupScreen();
6559 }
6560
6561 static void execSetupChooseTransparency(void)
6562 {
6563   setup_mode = SETUP_MODE_CHOOSE_TRANSPARENCY;
6564
6565   DrawSetupScreen();
6566 }
6567
6568 static void execSetupChooseGridXSize_0(void)
6569 {
6570   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_0;
6571
6572   DrawSetupScreen();
6573 }
6574
6575 static void execSetupChooseGridYSize_0(void)
6576 {
6577   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_0;
6578
6579   DrawSetupScreen();
6580 }
6581
6582 static void execSetupChooseGridXSize_1(void)
6583 {
6584   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_1;
6585
6586   DrawSetupScreen();
6587 }
6588
6589 static void execSetupChooseGridYSize_1(void)
6590 {
6591   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_1;
6592
6593   DrawSetupScreen();
6594 }
6595
6596 static void execSetupConfigureVirtualButtons(void)
6597 {
6598   setup_mode = SETUP_MODE_CONFIG_VIRT_BUTTONS;
6599
6600   ConfigureVirtualButtons();
6601
6602   setup_mode = SETUP_MODE_TOUCH;
6603
6604   DrawSetupScreen();
6605 }
6606
6607 static void execSetupTouch(void)
6608 {
6609   int i, j, k;
6610
6611   if (touch_controls == NULL)
6612   {
6613     for (i = 0; touch_controls_list[i].value != NULL; i++)
6614     {
6615       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6616       char identifier[32], name[32];
6617       char *value = touch_controls_list[i].value;
6618       char *text = touch_controls_list[i].text;
6619
6620       ti->node_top = &touch_controls;
6621       ti->sort_priority = i;
6622
6623       sprintf(identifier, "%s", value);
6624       sprintf(name, "%s", text);
6625
6626       setString(&ti->identifier, identifier);
6627       setString(&ti->name, name);
6628       setString(&ti->name_sorting, name);
6629       setString(&ti->infotext, STR_SETUP_CHOOSE_TOUCH_CONTROL);
6630
6631       pushTreeInfo(&touch_controls, ti);
6632     }
6633
6634     // sort touch control values to start with lowest touch control value
6635     sortTreeInfo(&touch_controls);
6636
6637     // set current touch control value to configured touch control value
6638     touch_control_current =
6639       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
6640
6641     // if that fails, set current touch control to reliable default value
6642     if (touch_control_current == NULL)
6643       touch_control_current =
6644         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
6645
6646     // if that also fails, set current touch control to first available value
6647     if (touch_control_current == NULL)
6648       touch_control_current = touch_controls;
6649   }
6650
6651   if (move_distances == NULL)
6652   {
6653     for (i = 0; distances_list[i].value != -1; i++)
6654     {
6655       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6656       char identifier[32], name[32];
6657       int value = distances_list[i].value;
6658       char *text = distances_list[i].text;
6659
6660       ti->node_top = &move_distances;
6661       ti->sort_priority = value;
6662
6663       sprintf(identifier, "%d", value);
6664       sprintf(name, "%s", text);
6665
6666       setString(&ti->identifier, identifier);
6667       setString(&ti->name, name);
6668       setString(&ti->name_sorting, name);
6669       setString(&ti->infotext, STR_SETUP_CHOOSE_MOVE_DISTANCE);
6670
6671       pushTreeInfo(&move_distances, ti);
6672     }
6673
6674     // sort distance values to start with lowest distance value
6675     sortTreeInfo(&move_distances);
6676
6677     // set current distance value to configured distance value
6678     move_distance_current =
6679       getTreeInfoFromIdentifier(move_distances,
6680                                 i_to_a(setup.touch.move_distance));
6681
6682     // if that fails, set current distance to reliable default value
6683     if (move_distance_current == NULL)
6684       move_distance_current =
6685         getTreeInfoFromIdentifier(move_distances,
6686                                   i_to_a(TOUCH_MOVE_DISTANCE_DEFAULT));
6687
6688     // if that also fails, set current distance to first available value
6689     if (move_distance_current == NULL)
6690       move_distance_current = move_distances;
6691   }
6692
6693   if (drop_distances == NULL)
6694   {
6695     for (i = 0; distances_list[i].value != -1; i++)
6696     {
6697       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6698       char identifier[32], name[32];
6699       int value = distances_list[i].value;
6700       char *text = distances_list[i].text;
6701
6702       ti->node_top = &drop_distances;
6703       ti->sort_priority = value;
6704
6705       sprintf(identifier, "%d", value);
6706       sprintf(name, "%s", text);
6707
6708       setString(&ti->identifier, identifier);
6709       setString(&ti->name, name);
6710       setString(&ti->name_sorting, name);
6711       setString(&ti->infotext, STR_SETUP_CHOOSE_DROP_DISTANCE);
6712
6713       pushTreeInfo(&drop_distances, ti);
6714     }
6715
6716     // sort distance values to start with lowest distance value
6717     sortTreeInfo(&drop_distances);
6718
6719     // set current distance value to configured distance value
6720     drop_distance_current =
6721       getTreeInfoFromIdentifier(drop_distances,
6722                                 i_to_a(setup.touch.drop_distance));
6723
6724     // if that fails, set current distance to reliable default value
6725     if (drop_distance_current == NULL)
6726       drop_distance_current =
6727         getTreeInfoFromIdentifier(drop_distances,
6728                                   i_to_a(TOUCH_DROP_DISTANCE_DEFAULT));
6729
6730     // if that also fails, set current distance to first available value
6731     if (drop_distance_current == NULL)
6732       drop_distance_current = drop_distances;
6733   }
6734
6735   if (transparencies == NULL)
6736   {
6737     for (i = 0; transparencies_list[i].value != -1; i++)
6738     {
6739       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6740       char identifier[32], name[32];
6741       int value = transparencies_list[i].value;
6742       char *text = transparencies_list[i].text;
6743
6744       ti->node_top = &transparencies;
6745       ti->sort_priority = value;
6746
6747       sprintf(identifier, "%d", value);
6748       sprintf(name, "%s", text);
6749
6750       setString(&ti->identifier, identifier);
6751       setString(&ti->name, name);
6752       setString(&ti->name_sorting, name);
6753       setString(&ti->infotext, STR_SETUP_CHOOSE_TRANSPARENCY);
6754
6755       pushTreeInfo(&transparencies, ti);
6756     }
6757
6758     // sort transparency values to start with lowest transparency value
6759     sortTreeInfo(&transparencies);
6760
6761     // set current transparency value to configured transparency value
6762     transparency_current =
6763       getTreeInfoFromIdentifier(transparencies,
6764                                 i_to_a(setup.touch.transparency));
6765
6766     // if that fails, set current transparency to reliable default value
6767     if (transparency_current == NULL)
6768       transparency_current =
6769         getTreeInfoFromIdentifier(transparencies,
6770                                   i_to_a(TOUCH_TRANSPARENCY_DEFAULT));
6771
6772     // if that also fails, set current transparency to first available value
6773     if (transparency_current == NULL)
6774       transparency_current = transparencies;
6775   }
6776
6777   for (i = 0; i < 2; i++)
6778   {
6779     for (j = 0; j < 2; j++)
6780     {
6781       if (grid_sizes[i][j] == NULL)
6782       {
6783         for (k = 0; grid_sizes_list[k].value != -1; k++)
6784         {
6785           TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6786           char identifier[32], name[32];
6787           int value = grid_sizes_list[k].value;
6788           char *text = grid_sizes_list[k].text;
6789
6790           ti->node_top = &grid_sizes[i][j];
6791           ti->sort_priority = value;
6792
6793           sprintf(identifier, "%d", value);
6794           sprintf(name, "%s", text);
6795
6796           setString(&ti->identifier, identifier);
6797           setString(&ti->name, name);
6798           setString(&ti->name_sorting, name);
6799           setString(&ti->infotext,
6800                     (i == 0 ?
6801                      (j == 0 ?
6802                       STR_SETUP_CHOOSE_GRID_XSIZE_0 :
6803                       STR_SETUP_CHOOSE_GRID_YSIZE_0) :
6804                      (j == 0 ?
6805                       STR_SETUP_CHOOSE_GRID_XSIZE_1 :
6806                       STR_SETUP_CHOOSE_GRID_YSIZE_1)));
6807
6808           pushTreeInfo(&grid_sizes[i][j], ti);
6809         }
6810
6811         // sort grid size values to start with lowest grid size value
6812         sortTreeInfo(&grid_sizes[i][j]);
6813
6814         // set current grid size value to configured grid size value
6815         grid_size_current[i][j] =
6816           getTreeInfoFromIdentifier(grid_sizes[i][j],
6817                                     i_to_a(j == 0 ?
6818                                            setup.touch.grid_xsize[i] :
6819                                            setup.touch.grid_ysize[i]));
6820
6821         // if that fails, set current grid size to reliable default value
6822         if (grid_size_current[i][j] == NULL)
6823           grid_size_current[i][j] =
6824             getTreeInfoFromIdentifier(grid_sizes[i][j],
6825                                       i_to_a(j == 0 ?
6826                                              DEFAULT_GRID_XSIZE(i) :
6827                                              DEFAULT_GRID_YSIZE(i)));
6828
6829         // if that also fails, set current grid size to first available value
6830         if (grid_size_current[i][j] == NULL)
6831           grid_size_current[i][j] = grid_sizes[i][j];
6832       }
6833     }
6834   }
6835
6836   setup.touch.control_type = touch_control_current->identifier;
6837   setup.touch.move_distance = atoi(move_distance_current->identifier);
6838   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
6839   setup.touch.transparency = atoi(transparency_current->identifier);
6840
6841   for (i = 0; i < 2; i++)
6842   {
6843     setup.touch.grid_xsize[i] = atoi(grid_size_current[i][0]->identifier);
6844     setup.touch.grid_ysize[i] = atoi(grid_size_current[i][1]->identifier);
6845
6846     if (i == GRID_ACTIVE_NR())
6847     {
6848       overlay.grid_xsize = setup.touch.grid_xsize[i];
6849       overlay.grid_ysize = setup.touch.grid_ysize[i];
6850     }
6851   }
6852
6853   // needed for displaying value text instead of identifier
6854   touch_controls_text = touch_control_current->name;
6855   move_distance_text = move_distance_current->name;
6856   drop_distance_text = drop_distance_current->name;
6857   transparency_text = transparency_current->name;
6858
6859   for (i = 0; i < 2; i++)
6860     for (j = 0; j < 2; j++)
6861       grid_size_text[i][j] = grid_size_current[i][j]->name;
6862
6863   setup_mode = SETUP_MODE_TOUCH;
6864
6865   DrawSetupScreen();
6866 }
6867
6868 static void execSetupArtwork(void)
6869 {
6870   static ArtworkDirTree *gfx_last_valid = NULL;
6871   static ArtworkDirTree *snd_last_valid = NULL;
6872   static ArtworkDirTree *mus_last_valid = NULL;
6873
6874   // current artwork directory may be invalid (level group, parent link)
6875   if (!validLevelSeries(artwork.gfx_current))
6876     artwork.gfx_current = getFirstValidTreeInfoEntry(gfx_last_valid);
6877   if (!validLevelSeries(artwork.snd_current))
6878     artwork.snd_current = getFirstValidTreeInfoEntry(snd_last_valid);
6879   if (!validLevelSeries(artwork.mus_current))
6880     artwork.mus_current = getFirstValidTreeInfoEntry(mus_last_valid);
6881
6882   // store valid artwork directory information
6883   gfx_last_valid = artwork.gfx_current;
6884   snd_last_valid = artwork.snd_current;
6885   mus_last_valid = artwork.mus_current;
6886
6887 #if 0
6888   Debug("screens:execSetupArtwork", "'%s', '%s', '%s'",
6889         artwork.gfx_current->subdir,
6890         artwork.gfx_current->fullpath,
6891         artwork.gfx_current->basepath);
6892 #endif
6893
6894   setup.graphics_set = artwork.gfx_current->identifier;
6895   setup.sounds_set = artwork.snd_current->identifier;
6896   setup.music_set = artwork.mus_current->identifier;
6897
6898   // needed if last screen (setup choice) changed graphics, sounds or music
6899   ReloadCustomArtwork(0);
6900
6901   // needed for displaying artwork name instead of artwork identifier
6902   graphics_set_name = artwork.gfx_current->name;
6903   sounds_set_name = artwork.snd_current->name;
6904   music_set_name = artwork.mus_current->name;
6905
6906   setup_mode = SETUP_MODE_ARTWORK;
6907
6908   DrawSetupScreen();
6909 }
6910
6911 static void execSetupChooseGraphics(void)
6912 {
6913   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
6914
6915   DrawSetupScreen();
6916 }
6917
6918 static void execSetupChooseSounds(void)
6919 {
6920   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
6921
6922   DrawSetupScreen();
6923 }
6924
6925 static void execSetupChooseMusic(void)
6926 {
6927   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
6928
6929   DrawSetupScreen();
6930 }
6931
6932 static void execSetupInput(void)
6933 {
6934   setup_mode = SETUP_MODE_INPUT;
6935
6936   DrawSetupScreen();
6937 }
6938
6939 static void execSetupShortcuts(void)
6940 {
6941   setup_mode = SETUP_MODE_SHORTCUTS;
6942
6943   DrawSetupScreen();
6944 }
6945
6946 static void execSetupShortcuts1(void)
6947 {
6948   setup_mode = SETUP_MODE_SHORTCUTS_1;
6949
6950   DrawSetupScreen();
6951 }
6952
6953 static void execSetupShortcuts2(void)
6954 {
6955   setup_mode = SETUP_MODE_SHORTCUTS_2;
6956
6957   DrawSetupScreen();
6958 }
6959
6960 static void execSetupShortcuts3(void)
6961 {
6962   setup_mode = SETUP_MODE_SHORTCUTS_3;
6963
6964   DrawSetupScreen();
6965 }
6966
6967 static void execSetupShortcuts4(void)
6968 {
6969   setup_mode = SETUP_MODE_SHORTCUTS_4;
6970
6971   DrawSetupScreen();
6972 }
6973
6974 static void execSetupShortcuts5(void)
6975 {
6976   setup_mode = SETUP_MODE_SHORTCUTS_5;
6977
6978   DrawSetupScreen();
6979 }
6980
6981 static void execExitSetup(void)
6982 {
6983   SetGameStatus(GAME_MODE_MAIN);
6984
6985   DrawMainMenu();
6986 }
6987
6988 static void execSaveAndExitSetup(void)
6989 {
6990   SaveSetup();
6991   execExitSetup();
6992 }
6993
6994 static void execGadgetNetworkServer(void)
6995 {
6996   int gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
6997   struct GadgetInfo *gi = screen_gadget[gadget_id];
6998
6999   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
7000     network_server_hostname[0] = '\0';
7001
7002   ModifyGadget(gi, GDI_TEXT_VALUE, network_server_hostname, GDI_END);
7003
7004   MapGadget(gi);
7005
7006   ClickOnGadget(gi, MB_LEFTBUTTON);
7007 }
7008
7009 static void execOfferUploadTapes(void)
7010 {
7011   OfferUploadTapes();
7012 }
7013
7014 static void ToggleNetworkModeIfNeeded(void)
7015 {
7016   int font_title = FONT_TITLE_1;
7017   int font_foot = FC_BLUE;
7018   int ystart  = mSY - SY + 16;
7019   int ybottom = mSY - SY + SYSIZE - 20;
7020   char *text = (setup.network_mode ? "Start Network" : "Stop Network");
7021
7022   if (setup.network_mode == network.enabled)
7023     return;
7024
7025   network.enabled = setup.network_mode;
7026
7027   FadeOut(REDRAW_ALL);
7028
7029   ClearField();
7030
7031   DrawTextSCentered(ystart, font_title, text);
7032
7033   FadeIn(REDRAW_ALL);
7034
7035   if (network.enabled)
7036     InitNetworkServer();
7037   else
7038     DisconnectFromNetworkServer();
7039
7040   DrawTextSCentered(ybottom, font_foot,
7041                     "Press any key or button for setup menu");
7042
7043   WaitForEventToContinue();
7044
7045   DrawSetupScreen();
7046 }
7047
7048 static void ToggleGameSpeedsListIfNeeded(void)
7049 {
7050   boolean using_game_speeds_extended = (game_speeds == game_speeds_extended);
7051
7052   if (setup.game_speed_extended == using_game_speeds_extended)
7053     return;
7054
7055   // try to match similar values when changing game speeds list
7056   if (setup.game_speed_extended)
7057     setup.game_frame_delay = (setup.game_frame_delay == 15 ? 16 :
7058                               setup.game_frame_delay == 30 ? 29 :
7059                               setup.game_frame_delay);
7060   else
7061     setup.game_frame_delay = (setup.game_frame_delay == 14 ? 15 :
7062                               setup.game_frame_delay == 16 ? 15 :
7063                               setup.game_frame_delay >= 29 ? 30 :
7064                               setup.game_frame_delay <= 10 ? 10 :
7065                               setup.game_frame_delay);
7066
7067   execSetupGame_setGameSpeeds(TRUE);
7068
7069   DrawSetupScreen();
7070 }
7071
7072 static void ToggleUseApiServerIfNeeded(void)
7073 {
7074   if (runtime.use_api_server == setup.use_api_server)
7075     return;
7076
7077   runtime.use_api_server = setup.use_api_server;
7078
7079   if (runtime.use_api_server)
7080     CheckApiServerTasks();
7081 }
7082
7083 static void ModifyGameSpeedIfNeeded(void)
7084 {
7085   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7086       setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY)
7087     return;
7088
7089   char message[100];
7090   char *game_speed_text = "Fast";
7091   int game_speed_value = 15;
7092
7093   if (setup.game_speed_extended)
7094   {
7095     game_speed_text = "60 fps";
7096     game_speed_value = 16;
7097   }
7098
7099   sprintf(message, "Game speed set to %s for VSync to work!", game_speed_text);
7100
7101   // set game speed to existing list value that is fast enough for vsync
7102   setup.game_frame_delay = game_speed_value;
7103
7104   execSetupGame_setGameSpeeds(TRUE);
7105
7106   Request(message, REQ_CONFIRM);
7107 }
7108
7109 static void DisableVsyncIfNeeded(void)
7110 {
7111   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7112       (setup.game_frame_delay >= MIN_VSYNC_FRAME_DELAY &&
7113        setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY))
7114     return;
7115
7116   // disable vsync for the selected game speed to work
7117   setup.vsync_mode = STR_VSYNC_MODE_OFF;
7118
7119   execSetupGraphics_setVsyncModes(TRUE);
7120
7121   Request("VSync disabled for this game speed to work!", REQ_CONFIRM);
7122 }
7123
7124 static struct
7125 {
7126   void *value;
7127   void *related_value;
7128 } hide_related_entry_list[] =
7129 {
7130   { &setup.scores_in_highscore_list,    execSetupChooseScoresType       },
7131   { &setup.scores_in_highscore_list,    &scores_type_text               },
7132
7133   { &setup.game_frame_delay,            execSetupChooseGameSpeed        },
7134   { &setup.game_frame_delay,            &game_speed_text                },
7135
7136   { &setup.scroll_delay_value,          execSetupChooseScrollDelay      },
7137   { &setup.scroll_delay_value,          &scroll_delay_text              },
7138
7139   { &setup.engine_snapshot_mode,        execSetupChooseSnapshotMode     },
7140   { &setup.engine_snapshot_mode,        &snapshot_mode_text             },
7141
7142   { &setup.window_scaling_percent,      execSetupChooseWindowSize       },
7143   { &setup.window_scaling_percent,      &window_size_text               },
7144
7145   { &setup.window_scaling_quality,      execSetupChooseScalingType      },
7146   { &setup.window_scaling_quality,      &scaling_type_text              },
7147
7148   { &setup.screen_rendering_mode,       execSetupChooseRenderingMode    },
7149   { &setup.screen_rendering_mode,       &rendering_mode_text            },
7150
7151   { &setup.vsync_mode,                  execSetupChooseVsyncMode        },
7152   { &setup.vsync_mode,                  &vsync_mode_text                },
7153
7154   { &setup.graphics_set,                execSetupChooseGraphics         },
7155   { &setup.graphics_set,                &graphics_set_name              },
7156
7157   { &setup.sounds_set,                  execSetupChooseSounds           },
7158   { &setup.sounds_set,                  &sounds_set_name                },
7159
7160   { &setup.music_set,                   execSetupChooseMusic            },
7161   { &setup.music_set,                   &music_set_name                 },
7162
7163   { &setup.volume_simple,               execSetupChooseVolumeSimple     },
7164   { &setup.volume_simple,               &volume_simple_text             },
7165
7166   { &setup.volume_loops,                execSetupChooseVolumeLoops      },
7167   { &setup.volume_loops,                &volume_loops_text              },
7168
7169   { &setup.volume_music,                execSetupChooseVolumeMusic      },
7170   { &setup.volume_music,                &volume_music_text              },
7171
7172   { &setup.touch.control_type,          execSetupChooseTouchControls    },
7173   { &setup.touch.control_type,          &touch_controls_text            },
7174
7175   { &setup.touch.move_distance,         execSetupChooseMoveDistance     },
7176   { &setup.touch.move_distance,         &move_distance_text             },
7177
7178   { &setup.touch.drop_distance,         execSetupChooseDropDistance     },
7179   { &setup.touch.drop_distance,         &drop_distance_text             },
7180
7181   { &setup.touch.transparency,          execSetupChooseTransparency     },
7182   { &setup.touch.transparency,          &transparency_text              },
7183
7184   { &setup.touch.grid_xsize[0],         execSetupChooseGridXSize_0      },
7185   { &setup.touch.grid_xsize[0],         &grid_size_text[0][0]           },
7186
7187   { &setup.touch.grid_ysize[0],         execSetupChooseGridYSize_0      },
7188   { &setup.touch.grid_ysize[0],         &grid_size_text[0][1]           },
7189
7190   { &setup.touch.grid_xsize[1],         execSetupChooseGridXSize_1      },
7191   { &setup.touch.grid_xsize[1],         &grid_size_text[1][0]           },
7192
7193   { &setup.touch.grid_ysize[1],         execSetupChooseGridYSize_1      },
7194   { &setup.touch.grid_ysize[1],         &grid_size_text[1][1]           },
7195
7196   { &setup.internal.menu_game,          execSetupGame                   },
7197   { &setup.internal.menu_engines,       execSetupEngines                },
7198   { &setup.internal.menu_editor,        execSetupEditor                 },
7199   { &setup.internal.menu_graphics,      execSetupGraphics               },
7200   { &setup.internal.menu_sound,         execSetupSound                  },
7201   { &setup.internal.menu_artwork,       execSetupArtwork                },
7202   { &setup.internal.menu_input,         execSetupInput                  },
7203   { &setup.internal.menu_touch,         execSetupTouch                  },
7204   { &setup.internal.menu_shortcuts,     execSetupShortcuts              },
7205   { &setup.internal.menu_exit,          execExitSetup                   },
7206   { &setup.internal.menu_save_and_exit, execSaveAndExitSetup            },
7207
7208   { &setup.internal.info_title,         execInfoTitleScreen             },
7209   { &setup.internal.info_elements,      execInfoElements                },
7210   { &setup.internal.info_music,         execInfoMusic                   },
7211   { &setup.internal.info_credits,       execInfoCredits                 },
7212   { &setup.internal.info_program,       execInfoProgram                 },
7213   { &setup.internal.info_version,       execInfoVersion                 },
7214   { &setup.internal.info_levelset,      execInfoLevelSet                },
7215   { &setup.internal.info_exit,          execExitInfo                    },
7216
7217   { NULL,                               NULL                            }
7218 };
7219
7220 void setHideRelatedSetupEntries(void)
7221 {
7222   int i;
7223
7224   for (i = 0; hide_related_entry_list[i].value != NULL; i++)
7225     if (hideSetupEntry(hide_related_entry_list[i].value))
7226       setHideSetupEntry(hide_related_entry_list[i].related_value);
7227 }
7228
7229 static struct TokenInfo setup_info_main[] =
7230 {
7231   { TYPE_ENTER_MENU,    execSetupGame,          STR_SETUP_GAME          },
7232   { TYPE_ENTER_MENU,    execSetupEngines,       STR_SETUP_ENGINES       },
7233   { TYPE_ENTER_MENU,    execSetupEditor,        STR_SETUP_EDITOR        },
7234   { TYPE_ENTER_MENU,    execSetupGraphics,      STR_SETUP_GRAPHICS      },
7235   { TYPE_ENTER_MENU,    execSetupSound,         STR_SETUP_SOUND         },
7236   { TYPE_ENTER_MENU,    execSetupArtwork,       STR_SETUP_ARTWORK       },
7237   { TYPE_ENTER_MENU,    execSetupInput,         STR_SETUP_INPUT         },
7238   { TYPE_ENTER_MENU,    execSetupTouch,         STR_SETUP_TOUCH         },
7239   { TYPE_ENTER_MENU,    execSetupShortcuts,     STR_SETUP_SHORTCUTS     },
7240   { TYPE_EMPTY,         NULL,                   ""                      },
7241   { TYPE_LEAVE_MENU,    execExitSetup,          STR_SETUP_EXIT          },
7242   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   STR_SETUP_SAVE_AND_EXIT },
7243
7244   { 0,                  NULL,                   NULL                    }
7245 };
7246
7247 static struct TokenInfo setup_info_game[] =
7248 {
7249   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
7250   { TYPE_SWITCH,        &setup.network_mode,    "Network Multi-Player Mode:" },
7251   { TYPE_PLAYER,        &setup.network_player_nr,"Preferred Network Player:" },
7252   { TYPE_TEXT_INPUT,    execGadgetNetworkServer, "Network Server Hostname:" },
7253   { TYPE_STRING,        &network_server_text,   ""                      },
7254   { TYPE_SWITCH,        &setup.use_api_server,  "Use Highscore Server:" },
7255   { TYPE_ENTER_LIST,    execSetupChooseScoresType,"Scores in Highscore List:" },
7256   { TYPE_STRING,        &scores_type_text,      ""                      },
7257   { TYPE_ENTER_LIST,    execOfferUploadTapes,   "Upload Tapes to Server" },
7258   { TYPE_SWITCH,        &setup.multiple_users,  "Multiple Users/Teams:" },
7259   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
7260   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
7261   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
7262   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
7263   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
7264   { TYPE_SWITCH,        &setup.auto_play_next_level,"Auto-play Next Level:" },
7265   { TYPE_SWITCH,        &setup.count_score_after_game,"Count Score After Game:" },
7266   { TYPE_SWITCH,        &setup.show_scores_after_game,"Show Scores After Game:" },
7267   { TYPE_YES_NO,        &setup.ask_on_game_over, "Ask on Game Over:"    },
7268   { TYPE_YES_NO,        &setup.ask_on_quit_game, "Ask on Quit Game:"    },
7269   { TYPE_YES_NO,        &setup.ask_on_quit_program, "Ask on Quit Program:" },
7270   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
7271   { TYPE_SWITCH,        &setup.auto_pause_on_start, "Start Game in Pause Mode:" },
7272   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
7273   { TYPE_STRING,        &game_speed_text,       ""                      },
7274   { TYPE_SWITCH,        &setup.game_speed_extended, "Game Speed Extended List:" },
7275 #if 1
7276   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7277   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7278 #endif
7279   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
7280   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
7281   { TYPE_SWITCH,        &setup.show_load_save_buttons,"Show Load/Save Buttons:" },
7282   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,"Show Undo/Redo Buttons:" },
7283   { TYPE_EMPTY,         NULL,                   ""                      },
7284   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7285
7286   { 0,                  NULL,                   NULL                    }
7287 };
7288
7289 static struct TokenInfo setup_info_engines[] =
7290 {
7291   { TYPE_HEADLINE,      NULL,                   "Emerald Mine"          },
7292   { TYPE_SWITCH,        &setup.forced_scroll_delay, "Scroll Delay:"     },
7293   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics, "Amiga Graphics Chipset:" },
7294   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,"Low-Pass Filter Sounds:" },
7295   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:" },
7296   { TYPE_EMPTY,         NULL,                   ""                      },
7297   { TYPE_HEADLINE,      NULL,                   "Supaplex"              },
7298   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:" },
7299   { TYPE_EMPTY,         NULL,                   ""                      },
7300   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7301
7302   { 0,                  NULL,                   NULL                    }
7303 };
7304
7305 static struct TokenInfo setup_info_editor[] =
7306 {
7307 #if 0
7308   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
7309   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
7310   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
7311   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
7312   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
7313   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
7314   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
7315   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
7316   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
7317   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
7318 #endif
7319   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
7320   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
7321 #if 0
7322   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
7323 #endif
7324   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
7325   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
7326   { TYPE_EMPTY,         NULL,                   ""                      },
7327 #if 0
7328   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
7329   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
7330   { TYPE_EMPTY,         NULL,                   ""                      },
7331 #endif
7332   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
7333   { TYPE_EMPTY,         NULL,                   ""                      },
7334   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:" },
7335   { TYPE_EMPTY,         NULL,                   ""                      },
7336   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7337
7338   { 0,                  NULL,                   NULL                    }
7339 };
7340
7341 static struct TokenInfo setup_info_graphics[] =
7342 {
7343 #if !defined(PLATFORM_ANDROID)
7344   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
7345   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
7346   { TYPE_STRING,        &window_size_text,      ""                      },
7347   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
7348   { TYPE_STRING,        &scaling_type_text,     ""                      },
7349   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
7350   { TYPE_STRING,        &rendering_mode_text,   ""                      },
7351 #endif
7352 #if 0
7353   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7354   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7355 #endif
7356   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode, "Vertical Sync (VSync):" },
7357   { TYPE_STRING,        &vsync_mode_text,       ""                      },
7358   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
7359   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
7360   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
7361   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
7362   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
7363   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
7364   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,  debug_xsn_mode          },
7365   { TYPE_EMPTY,         NULL,                   ""                      },
7366   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7367
7368   { 0,                  NULL,                   NULL                    }
7369 };
7370
7371 static struct TokenInfo setup_info_sound[] =
7372 {
7373   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
7374   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
7375   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
7376   { TYPE_EMPTY,         NULL,                   ""                      },
7377   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
7378   { TYPE_STRING,        &volume_simple_text,    ""                      },
7379   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
7380   { TYPE_STRING,        &volume_loops_text,     ""                      },
7381   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
7382   { TYPE_STRING,        &volume_music_text,     ""                      },
7383   { TYPE_EMPTY,         NULL,                   ""                      },
7384   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7385
7386   { 0,                  NULL,                   NULL                    }
7387 };
7388
7389 static struct TokenInfo setup_info_artwork[] =
7390 {
7391   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
7392   { TYPE_STRING,        &graphics_set_name,     ""                      },
7393   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
7394   { TYPE_STRING,        &sounds_set_name,       ""                      },
7395   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
7396   { TYPE_STRING,        &music_set_name,        ""                      },
7397   { TYPE_EMPTY,         NULL,                   ""                      },
7398   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
7399   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
7400   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
7401   { TYPE_EMPTY,         NULL,                   ""                      },
7402   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7403
7404   { 0,                  NULL,                   NULL                    }
7405 };
7406
7407 static struct TokenInfo setup_info_input[] =
7408 {
7409   { TYPE_SWITCH,        NULL,                   "Player:"               },
7410   { TYPE_SWITCH,        NULL,                   "Device:"               },
7411   { TYPE_SWITCH,        NULL,                   ""                      },
7412   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7413   { TYPE_EMPTY,         NULL,                   ""                      },
7414   { TYPE_EMPTY,         NULL,                   ""                      },
7415   { TYPE_EMPTY,         NULL,                   ""                      },
7416   { TYPE_EMPTY,         NULL,                   ""                      },
7417   { TYPE_EMPTY,         NULL,                   ""                      },
7418   { TYPE_EMPTY,         NULL,                   ""                      },
7419   { TYPE_EMPTY,         NULL,                   ""                      },
7420   { TYPE_EMPTY,         NULL,                   ""                      },
7421   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7422   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7423
7424   { 0,                  NULL,                   NULL                    }
7425 };
7426
7427 static struct TokenInfo setup_info_touch[] =
7428 {
7429   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7430   { TYPE_STRING,        &touch_controls_text,   ""                      },
7431   { TYPE_EMPTY,         NULL,                   ""                      },
7432   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7433
7434   { 0,                  NULL,                   NULL                    }
7435 };
7436
7437 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
7438 {
7439   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7440   { TYPE_STRING,        &touch_controls_text,   ""                      },
7441   { TYPE_EMPTY,         NULL,                   ""                      },
7442   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0, "Horizontal Buttons (Landscape):"   },
7443   { TYPE_STRING,        &grid_size_text[0][0],  ""                      },
7444   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0, "Vertical Buttons (Landscape):"     },
7445   { TYPE_STRING,        &grid_size_text[0][1],  ""                      },
7446   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7447   { TYPE_STRING,        &transparency_text,     ""                      },
7448   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7449   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7450   { TYPE_EMPTY,         NULL,                   ""                      },
7451   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7452   { TYPE_EMPTY,         NULL,                   ""                      },
7453   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7454
7455   { 0,                  NULL,                   NULL                    }
7456 };
7457
7458 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
7459 {
7460   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7461   { TYPE_STRING,        &touch_controls_text,   ""                      },
7462   { TYPE_EMPTY,         NULL,                   ""                      },
7463   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1, "Horizontal Buttons (Portrait):"    },
7464   { TYPE_STRING,        &grid_size_text[1][0],  ""                      },
7465   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1, "Vertical Buttons (Portrait):"      },
7466   { TYPE_STRING,        &grid_size_text[1][1],  ""                      },
7467   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7468   { TYPE_STRING,        &transparency_text,     ""                      },
7469   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7470   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7471   { TYPE_EMPTY,         NULL,                   ""                      },
7472   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7473   { TYPE_EMPTY,         NULL,                   ""                      },
7474   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7475
7476   { 0,                  NULL,                   NULL                    }
7477 };
7478
7479 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
7480 {
7481   setup_info_touch_virtual_buttons_0,
7482   setup_info_touch_virtual_buttons_1
7483 };
7484
7485 static struct TokenInfo setup_info_touch_wipe_gestures[] =
7486 {
7487   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7488   { TYPE_STRING,        &touch_controls_text,   ""                      },
7489   { TYPE_EMPTY,         NULL,                   ""                      },
7490   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
7491   { TYPE_STRING,        &move_distance_text,    ""                      },
7492   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
7493   { TYPE_STRING,        &drop_distance_text,    ""                      },
7494   { TYPE_EMPTY,         NULL,                   ""                      },
7495   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7496
7497   { 0,                  NULL,                   NULL                    }
7498 };
7499
7500 static struct TokenInfo setup_info_shortcuts[] =
7501 {
7502   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
7503   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
7504   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
7505   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
7506   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
7507   { TYPE_EMPTY,         NULL,                   ""                      },
7508   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7509
7510   { 0,                  NULL,                   NULL                    }
7511 };
7512
7513 static struct TokenInfo setup_info_shortcuts_1[] =
7514 {
7515   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
7516   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
7517   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
7518   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
7519   { TYPE_KEYTEXT,       NULL,           "Restart Game:",                },
7520   { TYPE_KEY,           &setup.shortcut.restart_game, ""                },
7521   { TYPE_KEYTEXT,       NULL,           "Replay & Pause Before End:",   },
7522   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""            },
7523   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
7524   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
7525   { TYPE_EMPTY,         NULL,                   ""                      },
7526   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
7527   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
7528   { TYPE_EMPTY,         NULL,                   ""                      },
7529   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7530
7531   { 0,                  NULL,                   NULL                    }
7532 };
7533
7534 static struct TokenInfo setup_info_shortcuts_2[] =
7535 {
7536   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
7537   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
7538   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
7539   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
7540   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
7541   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
7542   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
7543   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
7544   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
7545   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
7546   { TYPE_EMPTY,         NULL,                   ""                      },
7547   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7548
7549   { 0,                  NULL,                   NULL                    }
7550 };
7551
7552 static struct TokenInfo setup_info_shortcuts_3[] =
7553 {
7554   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
7555   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
7556   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
7557   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
7558   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
7559   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
7560   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
7561   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
7562   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
7563   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
7564   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
7565   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
7566   { TYPE_EMPTY,         NULL,                   ""                      },
7567   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7568
7569   { 0,                  NULL,                   NULL                    }
7570 };
7571
7572 static struct TokenInfo setup_info_shortcuts_4[] =
7573 {
7574   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
7575   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
7576   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
7577   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
7578   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
7579   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
7580   { TYPE_EMPTY,         NULL,                   ""                      },
7581   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7582
7583   { 0,                  NULL,                   NULL                    }
7584 };
7585
7586 static struct TokenInfo setup_info_shortcuts_5[] =
7587 {
7588   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
7589   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
7590   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
7591   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
7592   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
7593   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
7594   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
7595   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
7596   { TYPE_EMPTY,         NULL,                   ""                      },
7597   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7598
7599   { 0,                  NULL,                   NULL                    }
7600 };
7601
7602 static Key getSetupKey(void)
7603 {
7604   Key key = KSYM_UNDEFINED;
7605   boolean got_key_event = FALSE;
7606
7607   while (!got_key_event)
7608   {
7609     Event event;
7610
7611     if (NextValidEvent(&event))
7612     {
7613       switch (event.type)
7614       {
7615         case EVENT_KEYPRESS:
7616           {
7617             key = GetEventKey((KeyEvent *)&event, TRUE);
7618
7619             // press 'Escape' or 'Enter' to keep the existing key binding
7620             if (key == KSYM_Escape || key == KSYM_Return)
7621               key = KSYM_UNDEFINED;     // keep old value
7622
7623             got_key_event = TRUE;
7624           }
7625           break;
7626
7627         case EVENT_KEYRELEASE:
7628           key_joystick_mapping = 0;
7629           break;
7630
7631         default:
7632           HandleOtherEvents(&event);
7633           break;
7634       }
7635     }
7636
7637     BackToFront();
7638   }
7639
7640   return key;
7641 }
7642
7643 static int getSetupValueFont(int type, void *value)
7644 {
7645   if (type & TYPE_GHOSTED)
7646     return FONT_OPTION_OFF;
7647   else if (type & TYPE_KEY)
7648     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
7649   else if (type & TYPE_STRING)
7650     return FONT_VALUE_2;
7651   else if (type & TYPE_ECS_AGA)
7652     return FONT_VALUE_1;
7653   else if (type & TYPE_BOOLEAN_STYLE)
7654     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
7655   else if (type & TYPE_YES_NO_AUTO)
7656     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
7657             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
7658   else if (type & TYPE_PLAYER)
7659     return FONT_VALUE_1;
7660   else
7661     return FONT_VALUE_1;
7662 }
7663
7664 static int getSetupValueFontNarrow(int type, int font_nr)
7665 {
7666   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
7667           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
7668           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
7669           font_nr);
7670 }
7671
7672 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
7673 {
7674   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7675   struct TokenInfo *si = &setup_info[si_pos];
7676   boolean font_draw_xoffset_modified = FALSE;
7677   boolean scrollbar_needed = (num_setup_info < max_setup_info);
7678   int font_draw_xoffset_old = -1;
7679   int xoffset = (scrollbar_needed ? -1 : 0);
7680   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
7681   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
7682   int xpos = menu_screen_value_xpos;
7683   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
7684   int startx = mSX + xpos * 32;
7685   int starty = mSY + ypos * 32;
7686   int type = si->type;
7687   void *value = si->value;
7688   char *value_string = getSetupValue(type, value);
7689   int font_nr_default = getSetupValueFont(type, value);
7690   int font_width_default = getFontWidth(font_nr_default);
7691   int font_nr = font_nr_default;
7692   int i;
7693
7694   if (value_string == NULL)
7695     return;
7696
7697   if (type & TYPE_KEY)
7698   {
7699     xpos = MENU_SCREEN_START_XPOS;
7700
7701     if (type & TYPE_QUERY)
7702       value_string = "<press key>";
7703   }
7704   else if (type & TYPE_STRING)
7705   {
7706     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
7707
7708     xpos = MENU_SCREEN_START_XPOS;
7709
7710     if (strlen(value_string) > max_value_len)
7711       value_string[max_value_len] = '\0';
7712   }
7713   else if (type & TYPE_YES_NO_AUTO)
7714   {
7715     xpos = menu_screen_value_xpos - 1;
7716   }
7717   else if (type & TYPE_PLAYER)
7718   {
7719     int displayed_player_nr = *(int *)value + 1;
7720
7721     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
7722   }
7723
7724   startx = mSX + xpos * 32;
7725   starty = mSY + ypos * 32;
7726
7727   // special check if right-side setup values moved left due to scrollbar
7728   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
7729   {
7730     int max_menu_text_length = 26;      // maximum text length for classic menu
7731     int font_xoffset = getFontDrawOffsetX(font_nr);
7732     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
7733     int text_font_nr = getMenuTextFont(FONT_MENU_2);
7734     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
7735     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
7736
7737     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
7738     {
7739       // when using narrow font, left-shifting text "auto" not needed
7740       if (type & TYPE_YES_NO_AUTO)
7741         xpos += 1;
7742
7743       xpos += 1;
7744       startx = mSX + xpos * 32;
7745
7746       font_nr = getSetupValueFontNarrow(type, font_nr);
7747     }
7748   }
7749
7750   // downward compatibility correction for Juergen Bonhagen's menu settings
7751   if (setup_mode != SETUP_MODE_INPUT)
7752   {
7753     int max_menu_text_length_big = (menu_screen_value_xpos -
7754                                     MENU_SCREEN_START_XPOS);
7755     int max_menu_text_length_medium = max_menu_text_length_big * 2;
7756     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
7757     int font1_xoffset = getFontDrawOffsetX(font_nr);
7758     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
7759     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
7760     int text_font_nr = getMenuTextFont(FONT_MENU_2);
7761     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
7762     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
7763     boolean correct_font_draw_xoffset = FALSE;
7764
7765     if (xpos == MENU_SCREEN_START_XPOS &&
7766         startx + font1_xoffset < text_startx + text_font_xoffset)
7767       correct_font_draw_xoffset = TRUE;
7768
7769     if (xpos == menu_screen_value_xpos &&
7770         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
7771       correct_font_draw_xoffset = TRUE;
7772
7773     // check if setup value would overlap with setup text when printed
7774     // (this can happen for extreme/wrong values for font draw offset)
7775     if (correct_font_draw_xoffset)
7776     {
7777       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
7778       font_draw_xoffset_modified = TRUE;
7779
7780       if (type & TYPE_KEY)
7781         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
7782       else if (!(type & TYPE_STRING))
7783         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
7784           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
7785     }
7786   }
7787
7788   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
7789     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
7790
7791   DrawText(startx, starty, value_string, font_nr);
7792
7793   if (type & TYPE_PLAYER)
7794   {
7795     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
7796     int player_nr = *(int *)value;
7797     int xoff = font->draw_xoffset + getFontWidth(font_nr);
7798     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
7799     int startx2 = startx + xoff;
7800     int starty2 = starty + yoff;
7801
7802     if (DrawingOnBackground(startx2, starty2))
7803       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
7804
7805     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
7806                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
7807   }
7808
7809   if (font_draw_xoffset_modified)
7810     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
7811 }
7812
7813 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
7814 {
7815   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7816   struct TokenInfo *si = &setup_info[si_pos];
7817
7818   if (si->type & TYPE_BOOLEAN_STYLE)
7819   {
7820     *(boolean *)si->value ^= TRUE;
7821   }
7822   else if (si->type & TYPE_YES_NO_AUTO)
7823   {
7824     *(int *)si->value =
7825       (dx == -1 ?
7826        (*(int *)si->value == AUTO ? TRUE :
7827         *(int *)si->value == TRUE ? FALSE : AUTO) :
7828        (*(int *)si->value == TRUE ? AUTO :
7829         *(int *)si->value == AUTO ? FALSE : TRUE));
7830   }
7831   else if (si->type & TYPE_KEY)
7832   {
7833     Key key;
7834
7835     si->type |= TYPE_QUERY;
7836     drawSetupValue(screen_pos, setup_info_pos_raw);
7837     si->type &= ~TYPE_QUERY;
7838
7839     key = getSetupKey();
7840     if (key != KSYM_UNDEFINED)
7841       *(Key *)si->value = key;
7842   }
7843   else if (si->type & TYPE_PLAYER)
7844   {
7845     int player_nr = *(int *)si->value;
7846
7847     if (dx)
7848       player_nr += dx;
7849     else
7850       player_nr = Request("Choose player", REQ_PLAYER) - 1;
7851
7852     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
7853   }
7854
7855   drawSetupValue(screen_pos, setup_info_pos_raw);
7856
7857   // fullscreen state may have changed at this point
7858   if (si->value == &setup.fullscreen)
7859     ToggleFullscreenIfNeeded();
7860
7861   // network mode may have changed at this point
7862   if (si->value == &setup.network_mode)
7863     ToggleNetworkModeIfNeeded();
7864
7865   // API server mode may have changed at this point
7866   if (si->value == &setup.use_api_server)
7867     ToggleUseApiServerIfNeeded();
7868
7869   // game speed list may have changed at this point
7870   if (si->value == &setup.game_speed_extended)
7871     ToggleGameSpeedsListIfNeeded();
7872 }
7873
7874 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
7875 {
7876   static struct TokenInfo *setup_info_final = NULL;
7877   int list_size = 0;
7878   int list_pos = 0;
7879   int i;
7880
7881   // determine maximum list size of target list
7882   while (setup_info_orig[list_size++].type != 0);
7883
7884   // free, allocate and clear memory for target list
7885   checked_free(setup_info_final);
7886   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
7887
7888   // copy setup info list without setup entries marked as hidden
7889   for (i = 0; setup_info_orig[i].type != 0; i++)
7890   {
7891     // skip setup entries configured to be hidden
7892     if (hideSetupEntry(setup_info_orig[i].value))
7893       continue;
7894
7895     // skip skippable setup entries if screen is lower than usual
7896     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
7897         setup_info_orig[i].type == TYPE_SKIPPABLE)
7898       continue;
7899
7900     setup_info_final[list_pos++] = setup_info_orig[i];
7901   }
7902
7903   return setup_info_final;
7904 }
7905
7906 static void DrawSetupScreen_Generic(void)
7907 {
7908   int fade_mask = REDRAW_FIELD;
7909   boolean redraw_all = FALSE;
7910   char *title_string = NULL;
7911   int i;
7912
7913   if (CheckFadeAll())
7914     fade_mask = REDRAW_ALL;
7915
7916   UnmapAllGadgets();
7917   FadeMenuSoundsAndMusic();
7918
7919   FreeScreenGadgets();
7920   CreateScreenGadgets();
7921
7922   if (redraw_mask & REDRAW_ALL)
7923     redraw_all = TRUE;
7924
7925   FadeOut(fade_mask);
7926
7927   // needed if different viewport properties defined for setup screen
7928   ChangeViewportPropertiesIfNeeded();
7929
7930   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
7931
7932   ClearField();
7933
7934   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
7935
7936   if (setup_mode == SETUP_MODE_MAIN)
7937   {
7938     setup_info = setup_info_main;
7939     title_string = STR_SETUP_MAIN;
7940   }
7941   else if (setup_mode == SETUP_MODE_GAME)
7942   {
7943     setup_info = setup_info_game;
7944     title_string = STR_SETUP_GAME;
7945   }
7946   else if (setup_mode == SETUP_MODE_ENGINES)
7947   {
7948     setup_info = setup_info_engines;
7949     title_string = STR_SETUP_ENGINES;
7950   }
7951   else if (setup_mode == SETUP_MODE_EDITOR)
7952   {
7953     setup_info = setup_info_editor;
7954     title_string = STR_SETUP_EDITOR;
7955   }
7956   else if (setup_mode == SETUP_MODE_GRAPHICS)
7957   {
7958     setup_info = setup_info_graphics;
7959     title_string = STR_SETUP_GRAPHICS;
7960   }
7961   else if (setup_mode == SETUP_MODE_SOUND)
7962   {
7963     setup_info = setup_info_sound;
7964     title_string = STR_SETUP_SOUND;
7965   }
7966   else if (setup_mode == SETUP_MODE_ARTWORK)
7967   {
7968     setup_info = setup_info_artwork;
7969     title_string = STR_SETUP_ARTWORK;
7970   }
7971   else if (setup_mode == SETUP_MODE_TOUCH)
7972   {
7973     setup_info = setup_info_touch;
7974     title_string = STR_SETUP_TOUCH;
7975
7976     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
7977       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
7978     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
7979       setup_info = setup_info_touch_wipe_gestures;
7980   }
7981   else if (setup_mode == SETUP_MODE_SHORTCUTS)
7982   {
7983     setup_info = setup_info_shortcuts;
7984     title_string = STR_SETUP_SHORTCUTS;
7985   }
7986   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
7987   {
7988     setup_info = setup_info_shortcuts_1;
7989     title_string = STR_SETUP_SHORTCUTS;
7990   }
7991   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
7992   {
7993     setup_info = setup_info_shortcuts_2;
7994     title_string = STR_SETUP_SHORTCUTS;
7995   }
7996   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
7997   {
7998     setup_info = setup_info_shortcuts_3;
7999     title_string = STR_SETUP_SHORTCUTS;
8000   }
8001   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
8002   {
8003     setup_info = setup_info_shortcuts_4;
8004     title_string = STR_SETUP_SHORTCUTS;
8005   }
8006   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
8007   {
8008     setup_info = setup_info_shortcuts_5;
8009     title_string = STR_SETUP_SHORTCUTS;
8010   }
8011
8012   // use modified setup info without setup entries marked as hidden
8013   setup_info = getSetupInfoFinal(setup_info);
8014
8015   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
8016
8017   // determine maximal number of setup entries that can be displayed on screen
8018   num_setup_info = 0;
8019   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
8020     num_setup_info++;
8021
8022   // determine maximal number of setup entries available for this setup screen
8023   max_setup_info = 0;
8024   for (i = 0; setup_info[i].type != 0; i++)
8025     max_setup_info++;
8026
8027   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
8028
8029   MapScreenGadgets(max_setup_info);
8030
8031   if (redraw_all)
8032     redraw_mask = fade_mask = REDRAW_ALL;
8033
8034   DrawMaskedBorder(fade_mask);
8035
8036   FadeIn(fade_mask);
8037 }
8038
8039 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
8040 {
8041   menu_info = setup_info;
8042
8043   HandleMenuScreen(mx, my, dx, dy, button,
8044                    setup_mode, num_setup_info, max_setup_info);
8045 }
8046
8047 static void DrawSetupScreen_Input(void)
8048 {
8049   int i;
8050
8051   FadeOut(REDRAW_FIELD);
8052
8053   ClearField();
8054
8055   setup_info = getSetupInfoFinal(setup_info_input);
8056
8057   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
8058
8059   for (i = 0; setup_info[i].type != 0; i++)
8060   {
8061     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
8062       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
8063     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
8064       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
8065     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
8066       initCursor(i, IMG_MENU_BUTTON);
8067
8068     DrawCursorAndText_Setup(i, -1, FALSE);
8069   }
8070
8071   // create gadgets for setup input menu screen
8072   FreeScreenGadgets();
8073   CreateScreenGadgets();
8074
8075   // map gadgets for setup input menu screen
8076   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
8077
8078   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
8079
8080   FadeIn(REDRAW_FIELD);
8081 }
8082
8083 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8084 {
8085   if (device_name == NULL)
8086     return;
8087
8088   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8089     device_nr = 0;
8090
8091   if (strlen(device_name) > 1)
8092   {
8093     char c1 = device_name[strlen(device_name) - 1];
8094     char c2 = device_name[strlen(device_name) - 2];
8095
8096     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8097       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8098   }
8099   else
8100     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8101             strlen(device_name));
8102 }
8103
8104 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8105 {
8106   int i;
8107   static struct SetupKeyboardInfo custom_key;
8108   static struct
8109   {
8110     Key *key;
8111     char *text;
8112   } custom[] =
8113   {
8114     { &custom_key.left,  "Axis/Pad Left"  },
8115     { &custom_key.right, "Axis/Pad Right" },
8116     { &custom_key.up,    "Axis/Pad Up"    },
8117     { &custom_key.down,  "Axis/Pad Down"  },
8118     { &custom_key.snap,  "Button 1/A/X"   },
8119     { &custom_key.drop,  "Button 2/B/Y"   }
8120   };
8121   static char *joystick_name[MAX_PLAYERS] =
8122   {
8123     "Joystick1",
8124     "Joystick2",
8125     "Joystick3",
8126     "Joystick4"
8127   };
8128   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8129   int font_nr_info = FONT_MENU_1;
8130   int font_nr_name = FONT_VALUE_OLD;
8131   int font_nr_on   = FONT_VALUE_1;
8132   int font_nr_off  = FONT_VALUE_OLD;
8133   int pos = 4;
8134
8135   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8136   {
8137     font_nr_info = FONT_MENU_2;
8138     font_nr_on   = FONT_VALUE_NARROW;
8139     font_nr_off  = FONT_VALUE_OLD_NARROW;
8140   }
8141
8142   custom_key = setup.input[player_nr].key;
8143
8144   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8145            FONT_INPUT_1_ACTIVE);
8146
8147   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8148                              TILEX, TILEY);
8149   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8150                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8151
8152   if (setup.input[player_nr].use_joystick)
8153   {
8154     char *device_name = setup.input[player_nr].joy.device_name;
8155     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8156     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8157     char *text = joystick_name[joystick_nr];
8158     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8159
8160     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8161     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8162   }
8163   else
8164   {
8165     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8166     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8167   }
8168
8169   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8170     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8171   else
8172     pos = 3;
8173
8174   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8175   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8176   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8177   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8178
8179   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8180   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8181   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8182   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8183   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8184   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8185
8186   for (i = 0; i < 6; i++)
8187   {
8188     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8189
8190     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8191              "              ", font_nr_on);
8192     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8193              (setup.input[player_nr].use_joystick ?
8194               custom[i].text :
8195               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8196   }
8197 }
8198
8199 static int input_player_nr = 0;
8200
8201 static void HandleSetupScreen_Input_Player(int step, int direction)
8202 {
8203   int old_player_nr = input_player_nr;
8204   int new_player_nr;
8205
8206   new_player_nr = old_player_nr + step * direction;
8207   if (new_player_nr < 0)
8208     new_player_nr = 0;
8209   if (new_player_nr > MAX_PLAYERS - 1)
8210     new_player_nr = MAX_PLAYERS - 1;
8211
8212   if (new_player_nr != old_player_nr)
8213   {
8214     input_player_nr = new_player_nr;
8215
8216     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8217   }
8218 }
8219
8220 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8221 {
8222   static int choice = 0;
8223   int x = 0;
8224   int y = choice;
8225   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8226   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8227   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8228   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8229
8230   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8231   {
8232     int i;
8233
8234     for (i = 0; setup_info_input[i].type != 0; i++)
8235     {
8236       // adjust menu structure according to skipped setup entries
8237       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8238       {
8239         pos_empty2--;
8240         pos_end--;
8241       }
8242     }
8243   }
8244
8245   if (button == MB_MENU_INITIALIZE)
8246   {
8247     // input setup menu may have changed size due to graphics configuration
8248     if (choice >= pos_empty1)
8249       choice = pos_end;
8250
8251     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8252
8253     DrawCursorAndText_Setup(choice, -1, TRUE);
8254
8255     return;
8256   }
8257   else if (button == MB_MENU_LEAVE)
8258   {
8259     setup_mode = SETUP_MODE_MAIN;
8260     DrawSetupScreen();
8261     InitJoysticks();
8262
8263     return;
8264   }
8265
8266   if (mx || my)         // mouse input
8267   {
8268     x = (mx - mSX) / 32;
8269     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8270   }
8271   else if (dx || dy)    // keyboard input
8272   {
8273     if (dx && choice == 0)
8274       x = (dx < 0 ? 10 : 12);
8275     else if ((dx && choice == 1) ||
8276              (dx == -1 && choice == pos_end))
8277       button = MB_MENU_CHOICE;
8278     else if (dy)
8279       y = choice + dy;
8280
8281     if (y >= pos_empty1 && y <= pos_empty2)
8282       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
8283   }
8284
8285   if (y == 0 && dx != 0 && button)
8286   {
8287     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
8288   }
8289   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
8290            y >= pos_start && y <= pos_end &&
8291            !(y >= pos_empty1 && y <= pos_empty2))
8292   {
8293     if (button)
8294     {
8295       if (y != choice)
8296       {
8297         DrawCursorAndText_Setup(choice, -1, FALSE);
8298         DrawCursorAndText_Setup(y, -1, TRUE);
8299
8300         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
8301
8302         choice = y;
8303       }
8304     }
8305     else
8306     {
8307       if (y == 1)
8308       {
8309         char *device_name = setup.input[input_player_nr].joy.device_name;
8310
8311         if (!setup.input[input_player_nr].use_joystick)
8312         {
8313           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
8314
8315           setJoystickDeviceToNr(device_name, new_device_nr);
8316           setup.input[input_player_nr].use_joystick = TRUE;
8317         }
8318         else
8319         {
8320           int device_nr = getJoystickNrFromDeviceName(device_name);
8321           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
8322
8323           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
8324             setup.input[input_player_nr].use_joystick = FALSE;
8325           else
8326             setJoystickDeviceToNr(device_name, new_device_nr);
8327         }
8328
8329         drawPlayerSetupInputInfo(input_player_nr, FALSE);
8330       }
8331       else if (y == 2)
8332       {
8333         if (setup.input[input_player_nr].use_joystick)
8334           ConfigureJoystick(input_player_nr);
8335         else
8336           CustomizeKeyboard(input_player_nr);
8337       }
8338       else if (y == pos_end)
8339       {
8340         InitJoysticks();
8341
8342         FadeSetLeaveMenu();
8343
8344         setup_mode = SETUP_MODE_MAIN;
8345         DrawSetupScreen();
8346       }
8347     }
8348   }
8349 }
8350
8351 static boolean CustomizeKeyboardMain(int player_nr)
8352 {
8353   int i;
8354   int step_nr;
8355   boolean finished = FALSE;
8356   static struct SetupKeyboardInfo custom_key;
8357   static struct
8358   {
8359     Key *key;
8360     char *text;
8361   } customize_step[] =
8362   {
8363     { &custom_key.left,  "Move Left"    },
8364     { &custom_key.right, "Move Right"   },
8365     { &custom_key.up,    "Move Up"      },
8366     { &custom_key.down,  "Move Down"    },
8367     { &custom_key.snap,  "Snap Field"   },
8368     { &custom_key.drop,  "Drop Element" }
8369   };
8370   int font_nr_old = FONT_VALUE_OLD;
8371   int font_nr_new = FONT_VALUE_1;
8372   boolean success = FALSE;
8373
8374   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8375   {
8376     font_nr_old = FONT_VALUE_OLD_NARROW;
8377     font_nr_new = FONT_VALUE_NARROW;
8378   }
8379
8380   // read existing key bindings from player setup
8381   custom_key = setup.input[player_nr].key;
8382
8383   FadeSetEnterMenu();
8384   FadeOut(REDRAW_FIELD);
8385
8386   ClearField();
8387
8388   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
8389
8390   step_nr = 0;
8391   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8392            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8393   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8394            "Key:", FONT_INPUT_1_ACTIVE);
8395   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8396            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
8397
8398   FadeIn(REDRAW_FIELD);
8399
8400   while (!finished)
8401   {
8402     Event event;
8403
8404     if (NextValidEvent(&event))
8405     {
8406       switch (event.type)
8407       {
8408         case EVENT_KEYPRESS:
8409           {
8410             Key key = GetEventKey((KeyEvent *)&event, FALSE);
8411
8412             // press 'Escape' to abort and keep the old key bindings
8413             if (key == KSYM_Escape)
8414             {
8415               FadeSkipNextFadeIn();
8416
8417               finished = TRUE;
8418
8419               break;
8420             }
8421
8422             // press 'Enter' to keep the existing key binding
8423             if (key == KSYM_Return)
8424               key = *customize_step[step_nr].key;
8425
8426             // check if key already used
8427             for (i = 0; i < step_nr; i++)
8428               if (*customize_step[i].key == key)
8429                 break;
8430             if (i < step_nr)
8431               break;
8432
8433             // got new key binding
8434             *customize_step[step_nr].key = key;
8435             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8436                      "             ", font_nr_new);
8437             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8438                      getKeyNameFromKey(key), font_nr_new);
8439             step_nr++;
8440
8441             // un-highlight last query
8442             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
8443                      customize_step[step_nr - 1].text, FONT_MENU_1);
8444             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
8445                      "Key:", FONT_MENU_1);
8446
8447             // all keys configured
8448             if (step_nr == 6)
8449             {
8450               finished = TRUE;
8451               success = TRUE;
8452
8453               break;
8454             }
8455
8456             // query next key binding
8457             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8458                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8459             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8460                      "Key:", FONT_INPUT_1_ACTIVE);
8461             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8462                      getKeyNameFromKey(*customize_step[step_nr].key),
8463                      font_nr_old);
8464           }
8465           break;
8466
8467         case EVENT_KEYRELEASE:
8468           key_joystick_mapping = 0;
8469           break;
8470
8471         default:
8472           HandleOtherEvents(&event);
8473           break;
8474       }
8475     }
8476
8477     BackToFront();
8478   }
8479
8480   // write new key bindings back to player setup, if successfully finished
8481   if (success)
8482     setup.input[player_nr].key = custom_key;
8483
8484   return success;
8485 }
8486
8487 void CustomizeKeyboard(int player_nr)
8488 {
8489   boolean success = CustomizeKeyboardMain(player_nr);
8490
8491   if (success)
8492   {
8493     int font_nr = FONT_TITLE_1;
8494     int font_height = getFontHeight(font_nr);
8495     int ypos1 = SYSIZE / 2 - font_height * 2;
8496     int ypos2 = SYSIZE / 2 - font_height * 1;
8497     unsigned int wait_frame_delay = 0;
8498     unsigned int wait_frame_delay_value = 2000;
8499
8500     ResetDelayCounter(&wait_frame_delay);
8501
8502     ClearField();
8503
8504     DrawTextSCentered(ypos1, font_nr, "Keyboard");
8505     DrawTextSCentered(ypos2, font_nr, "configured!");
8506
8507     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8508       BackToFront();
8509
8510     ClearEventQueue();
8511   }
8512
8513   DrawSetupScreen_Input();
8514 }
8515
8516 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
8517
8518 #define MARKER_BUTTON           1
8519 #define MARKER_AXIS_X           2
8520 #define MARKER_AXIS_Y           3
8521
8522 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
8523 {
8524   static boolean bitmaps_initialized = FALSE;
8525   boolean screen_initialized = FALSE;
8526   static Bitmap *controller, *button, *axis_x, *axis_y;
8527   char *name;
8528   boolean success = TRUE;
8529   boolean done = FALSE, next = FALSE;
8530   Event event;
8531   int alpha = 200, alpha_step = -1;
8532   int alpha_ticks = 0;
8533   char mapping[4096], temp[256];
8534   int font_name = MENU_SETUP_FONT_TITLE;
8535   int font_info = MENU_SETUP_FONT_TEXT;
8536   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
8537   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
8538   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
8539   int ystep_name = getMenuTextStep(spacing_name, font_name);
8540   int ystep_line = getMenuTextStep(spacing_line, font_info);
8541   int ystep_para = getMenuTextStep(spacing_para, font_info);
8542   int i, j;
8543
8544   struct
8545   {
8546     int x, y;
8547     int marker;
8548     char *field;
8549     int axis, button, hat, hat_value;
8550     char mapping[4096];
8551   }
8552   *step, *prev_step, steps[] =
8553   {
8554     { 356, 155, MARKER_BUTTON, "a",             },
8555     { 396, 122, MARKER_BUTTON, "b",             },
8556     { 320, 125, MARKER_BUTTON, "x",             },
8557     { 358,  95, MARKER_BUTTON, "y",             },
8558     { 162, 125, MARKER_BUTTON, "back",          },
8559     { 216, 125, MARKER_BUTTON, "guide",         },
8560     { 271, 125, MARKER_BUTTON, "start",         },
8561     { 110, 200, MARKER_BUTTON, "dpleft",        },
8562     { 146, 228, MARKER_BUTTON, "dpdown",        },
8563     { 178, 200, MARKER_BUTTON, "dpright",       },
8564     { 146, 172, MARKER_BUTTON, "dpup",          },
8565     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
8566     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
8567     { 382,  40, MARKER_BUTTON, "rightshoulder", },
8568     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
8569     {  73, 141, MARKER_BUTTON, "leftstick",     },
8570     { 282, 210, MARKER_BUTTON, "rightstick",    },
8571     {  73, 141, MARKER_AXIS_X, "leftx",         },
8572     {  73, 141, MARKER_AXIS_Y, "lefty",         },
8573     { 282, 210, MARKER_AXIS_X, "rightx",        },
8574     { 282, 210, MARKER_AXIS_Y, "righty",        },
8575   };
8576
8577   unsigned int event_frame_delay = 0;
8578   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
8579
8580   ResetDelayCounter(&event_frame_delay);
8581
8582   if (!bitmaps_initialized)
8583   {
8584     controller = LoadCustomImage("joystick/controller.png");
8585     button     = LoadCustomImage("joystick/button.png");
8586     axis_x     = LoadCustomImage("joystick/axis_x.png");
8587     axis_y     = LoadCustomImage("joystick/axis_y.png");
8588
8589     bitmaps_initialized = TRUE;
8590   }
8591
8592   name = getFormattedJoystickName(SDL_JoystickName(joystick));
8593
8594 #if DEBUG_JOYSTICKS
8595   // print info about the joystick we are watching
8596   Debug("joystick", "watching joystick %d: (%s)",
8597         SDL_JoystickInstanceID(joystick), name);
8598   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
8599         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
8600         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
8601 #endif
8602
8603   // initialize mapping with GUID and name
8604   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
8605
8606   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
8607            temp, name, SDL_GetPlatform());
8608
8609   // loop through all steps (buttons and axes), getting joystick events
8610   for (i = 0; i < SDL_arraysize(steps) && !done;)
8611   {
8612     Bitmap *marker = button;    // initialize with reliable default value
8613
8614     step = &steps[i];
8615     strcpy(step->mapping, mapping);
8616     step->axis = -1;
8617     step->button = -1;
8618     step->hat = -1;
8619     step->hat_value = -1;
8620
8621     marker = (step->marker == MARKER_BUTTON ? button :
8622               step->marker == MARKER_AXIS_X ? axis_x :
8623               step->marker == MARKER_AXIS_Y ? axis_y : marker);
8624
8625     next = FALSE;
8626
8627     while (!done && !next)
8628     {
8629       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
8630       alpha_ticks = SDL_GetTicks();
8631
8632       if (alpha >= 255)
8633       {
8634         alpha = 255;
8635         alpha_step = -1;
8636       }
8637       else if (alpha < 128)
8638       {
8639         alpha = 127;
8640         alpha_step = 1;
8641       }
8642
8643       int controller_x = SX + (SXSIZE - controller->width) / 2;
8644       int controller_y = SY + ystep_line;
8645
8646       int marker_x = controller_x + step->x;
8647       int marker_y = controller_y + step->y;
8648
8649       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
8650       int ystart2 = ystart1 + ystep_name + ystep_line;
8651
8652       ClearField();
8653
8654       DrawTextSCentered(ystart1, font_name, name);
8655
8656       DrawTextSCentered(ystart2, font_info,
8657                         "Press buttons and move axes on");
8658       ystart2 += ystep_line;
8659       DrawTextSCentered(ystart2, font_info,
8660                         "your controller when indicated.");
8661       ystart2 += ystep_line;
8662       DrawTextSCentered(ystart2, font_info,
8663                         "(Your controller may look different.)");
8664       ystart2 += ystep_para;
8665
8666 #if defined(PLATFORM_ANDROID)
8667       DrawTextSCentered(ystart2, font_info,
8668                         "To correct a mistake,");
8669       ystart2 += ystep_line;
8670       DrawTextSCentered(ystart2, font_info,
8671                         "press the 'back' button.");
8672       ystart2 += ystep_line;
8673       DrawTextSCentered(ystart2, font_info,
8674                         "To skip a button or axis,");
8675       ystart2 += ystep_line;
8676       DrawTextSCentered(ystart2, font_info,
8677                         "press the 'menu' button.");
8678 #else
8679       DrawTextSCentered(ystart2, font_info,
8680                         "To correct a mistake,");
8681       ystart2 += ystep_line;
8682       DrawTextSCentered(ystart2, font_info,
8683                         "press the 'backspace' key.");
8684       ystart2 += ystep_line;
8685       DrawTextSCentered(ystart2, font_info,
8686                         "To skip a button or axis,");
8687       ystart2 += ystep_line;
8688       DrawTextSCentered(ystart2, font_info,
8689                         "press the 'return' key.");
8690       ystart2 += ystep_line;
8691       DrawTextSCentered(ystart2, font_info,
8692                         "To exit, press the 'escape' key.");
8693 #endif
8694
8695       BlitBitmapMasked(controller, drawto, 0, 0,
8696                        controller->width, controller->height,
8697                        controller_x, controller_y);
8698
8699       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
8700       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
8701
8702       BlitBitmapMasked(marker, drawto, 0, 0,
8703                        marker->width, marker->height,
8704                        marker_x, marker_y);
8705
8706       if (!screen_initialized)
8707         FadeIn(REDRAW_FIELD);
8708       else
8709         BackToFront();
8710
8711       screen_initialized = TRUE;
8712
8713       while (NextValidEvent(&event))
8714       {
8715         switch (event.type)
8716         {
8717           case SDL_JOYAXISMOTION:
8718             if (event.jaxis.value > 20000 ||
8719                 event.jaxis.value < -20000)
8720             {
8721               for (j = 0; j < i; j++)
8722                 if (steps[j].axis == event.jaxis.axis)
8723                   break;
8724
8725               if (j == i)
8726               {
8727                 if (step->marker != MARKER_AXIS_X &&
8728                     step->marker != MARKER_AXIS_Y)
8729                   break;
8730
8731                 step->axis = event.jaxis.axis;
8732                 strcat(mapping, step->field);
8733                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
8734                 strcat(mapping, temp);
8735                 i++;
8736                 next = TRUE;
8737               }
8738             }
8739
8740             break;
8741
8742           case SDL_JOYHATMOTION:
8743             // ignore centering; we're probably just coming back
8744             // to the center from the previous item we set
8745             if (event.jhat.value == SDL_HAT_CENTERED)
8746               break;
8747
8748             for (j = 0; j < i; j++)
8749               if (steps[j].hat == event.jhat.hat &&
8750                   steps[j].hat_value == event.jhat.value)
8751                 break;
8752
8753             if (j == i)
8754             {
8755               step->hat = event.jhat.hat;
8756               step->hat_value = event.jhat.value;
8757               strcat(mapping, step->field);
8758               snprintf(temp, sizeof(temp), ":h%u.%u,",
8759                        event.jhat.hat, event.jhat.value );
8760               strcat(mapping, temp);
8761               i++;
8762               next = TRUE;
8763             }
8764
8765             break;
8766
8767           case SDL_JOYBALLMOTION:
8768             break;
8769
8770           case SDL_JOYBUTTONUP:
8771             for (j = 0; j < i; j++)
8772               if (steps[j].button == event.jbutton.button)
8773                 break;
8774
8775             if (j == i)
8776             {
8777               step->button = event.jbutton.button;
8778               strcat(mapping, step->field);
8779               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
8780               strcat(mapping, temp);
8781               i++;
8782               next = TRUE;
8783             }
8784
8785             break;
8786
8787           case SDL_FINGERDOWN:
8788           case SDL_MOUSEBUTTONDOWN:
8789             // skip this step
8790             i++;
8791             next = TRUE;
8792
8793             break;
8794
8795           case SDL_KEYDOWN:
8796             if (event.key.keysym.sym == KSYM_BackSpace ||
8797                 event.key.keysym.sym == KSYM_Back)
8798             {
8799               if (i == 0)
8800               {
8801                 // leave screen
8802                 success = FALSE;
8803                 done = TRUE;
8804
8805                 break;
8806               }
8807
8808               // undo this step
8809               prev_step = &steps[i - 1];
8810               strcpy(mapping, prev_step->mapping);
8811               i--;
8812               next = TRUE;
8813
8814               break;
8815             }
8816
8817             if (event.key.keysym.sym == KSYM_space ||
8818                 event.key.keysym.sym == KSYM_Return ||
8819                 event.key.keysym.sym == KSYM_Menu)
8820             {
8821               // skip this step
8822               i++;
8823               next = TRUE;
8824
8825               break;
8826             }
8827
8828             if (event.key.keysym.sym == KSYM_Escape)
8829             {
8830               // leave screen
8831               success = FALSE;
8832               done = TRUE;
8833             }
8834
8835             break;
8836
8837           case SDL_QUIT:
8838             program.exit_function(0);
8839             break;
8840
8841           default:
8842             break;
8843         }
8844
8845         // do not handle events for longer than standard frame delay period
8846         if (DelayReached(&event_frame_delay, event_frame_delay_value))
8847           break;
8848       }
8849     }
8850   }
8851
8852   if (success)
8853   {
8854 #if DEBUG_JOYSTICKS
8855     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
8856 #endif
8857
8858     // activate mapping for this game
8859     SDL_GameControllerAddMapping(mapping);
8860
8861     // save mapping to personal mappings
8862     SaveSetup_AddGameControllerMapping(mapping);
8863   }
8864
8865   // wait until the last pending event was removed from event queue
8866   while (NextValidEvent(&event));
8867
8868   return success;
8869 }
8870
8871 static int ConfigureJoystickMain(int player_nr)
8872 {
8873   char *device_name = setup.input[player_nr].joy.device_name;
8874   int joystick_nr = getJoystickNrFromDeviceName(device_name);
8875   boolean joystick_active = CheckJoystickOpened(joystick_nr);
8876   int success = FALSE;
8877   int i;
8878
8879   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
8880     return JOYSTICK_NOT_AVAILABLE;
8881
8882   if (!joystick_active || !setup.input[player_nr].use_joystick)
8883     return JOYSTICK_NOT_AVAILABLE;
8884
8885   FadeSetEnterMenu();
8886   FadeOut(REDRAW_FIELD);
8887
8888   // close all joystick devices (potentially opened as game controllers)
8889   for (i = 0; i < SDL_NumJoysticks(); i++)
8890     SDLCloseJoystick(i);
8891
8892   // open joystick device as plain joystick to configure as game controller
8893   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
8894
8895   // as the joystick was successfully opened before, this should not happen
8896   if (joystick == NULL)
8897     return FALSE;
8898
8899   // create new game controller mapping (buttons and axes) for joystick device
8900   success = ConfigureJoystickMapButtonsAndAxes(joystick);
8901
8902   // close joystick (and maybe re-open as configured game controller later)
8903   SDL_JoystickClose(joystick);
8904
8905   // re-open all joystick devices (potentially as game controllers)
8906   for (i = 0; i < SDL_NumJoysticks(); i++)
8907     SDLOpenJoystick(i);
8908
8909   // clear all joystick input actions for all joystick devices
8910   SDLClearJoystickState();
8911
8912   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
8913 }
8914
8915 void ConfigureJoystick(int player_nr)
8916 {
8917   boolean state = ConfigureJoystickMain(player_nr);
8918
8919   if (state != JOYSTICK_NOT_CONFIGURED)
8920   {
8921     boolean success = (state == JOYSTICK_CONFIGURED);
8922     char message1[MAX_OUTPUT_LINESIZE + 1];
8923     char *message2 = (success ? "configured!" : "not available!");
8924     char *device_name = setup.input[player_nr].joy.device_name;
8925     int nr = getJoystickNrFromDeviceName(device_name) + 1;
8926     int font_nr = FONT_TITLE_1;
8927     int font_height = getFontHeight(font_nr);
8928     int ypos1 = SYSIZE / 2 - font_height * 2;
8929     int ypos2 = SYSIZE / 2 - font_height * 1;
8930     unsigned int wait_frame_delay = 0;
8931     unsigned int wait_frame_delay_value = 2000;
8932
8933     ResetDelayCounter(&wait_frame_delay);
8934
8935     ClearField();
8936
8937     sprintf(message1, "Joystick %d", nr);
8938
8939     DrawTextSCentered(ypos1, font_nr, message1);
8940     DrawTextSCentered(ypos2, font_nr, message2);
8941
8942     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8943       BackToFront();
8944
8945     ClearEventQueue();
8946   }
8947
8948   DrawSetupScreen_Input();
8949 }
8950
8951 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
8952 {
8953   if (y < video.screen_height / 3)
8954   {
8955     // remap touch gadgets to access upper part of the screen
8956     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8957     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
8958   }
8959   else if (y > 2 * video.screen_height / 3)
8960   {
8961     // remap touch gadgets to access lower part of the screen
8962     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8963     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
8964   }
8965 }
8966
8967 static boolean ConfigureVirtualButtonsMain(void)
8968 {
8969   static char *customize_step_text[] =
8970   {
8971     "Move Left",
8972     "Move Right",
8973     "Move Up",
8974     "Move Down",
8975     "Snap Field",
8976     "Drop Element"
8977   };
8978   char grid_button[] =
8979   {
8980     CHAR_GRID_BUTTON_LEFT,
8981     CHAR_GRID_BUTTON_RIGHT,
8982     CHAR_GRID_BUTTON_UP,
8983     CHAR_GRID_BUTTON_DOWN,
8984     CHAR_GRID_BUTTON_SNAP,
8985     CHAR_GRID_BUTTON_DROP
8986   };
8987   enum
8988   {
8989     ACTION_NONE,
8990     ACTION_ESCAPE,
8991     ACTION_BACK,
8992     ACTION_NEXT
8993   };
8994   int font_nr = FONT_INPUT_1_ACTIVE;
8995   int font_height = getFontHeight(font_nr);
8996   int ypos1 = SYSIZE / 2 - font_height * 2;
8997   int ypos2 = SYSIZE / 2 - font_height * 1;
8998   boolean success = FALSE;
8999   boolean finished = FALSE;
9000   int step_nr = 0;
9001   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
9002   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9003   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9004   boolean set_grid_button = FALSE;
9005   int nr = GRID_ACTIVE_NR();
9006   int x, y;
9007
9008   for (x = 0; x < MAX_GRID_XSIZE; x++)
9009     for (y = 0; y < MAX_GRID_YSIZE; y++)
9010       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
9011
9012   overlay.grid_button_highlight = grid_button[step_nr];
9013
9014   UnmapAllGadgets();
9015
9016   FadeSetEnterMenu();
9017   FadeOut(REDRAW_FIELD);
9018
9019   ClearField();
9020
9021   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9022   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9023   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9024
9025   FadeIn(REDRAW_FIELD);
9026
9027   SetOverlayShowGrid(TRUE);
9028
9029   // map gadgets for setup touch buttons menu screen
9030   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9031
9032   while (!finished)
9033   {
9034     Event event;
9035
9036     while (NextValidEvent(&event))
9037     {
9038       int action = ACTION_NONE;
9039
9040       // ---------- handle events and set the resulting action ----------
9041
9042       switch (event.type)
9043       {
9044         case EVENT_USER:
9045           {
9046             UserEvent *user = (UserEvent *)&event;
9047             int id = user->value1;
9048
9049             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
9050                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
9051                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
9052                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
9053                       ACTION_NONE);
9054           }
9055           break;
9056
9057         case EVENT_KEYPRESS:
9058           {
9059             Key key = GetEventKey((KeyEvent *)&event, FALSE);
9060
9061             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
9062                       key == KSYM_BackSpace ||
9063                       key == KSYM_Back ?        ACTION_BACK :
9064                       key == KSYM_Return ||
9065                       key == KSYM_Menu ||
9066                       key == KSYM_space ?       ACTION_NEXT :
9067                       ACTION_NONE);
9068           }
9069           break;
9070
9071         case EVENT_KEYRELEASE:
9072           key_joystick_mapping = 0;
9073           break;
9074
9075         case EVENT_BUTTONPRESS:
9076         case EVENT_BUTTONRELEASE:
9077           {
9078             ButtonEvent *button = (ButtonEvent *)&event;
9079
9080             motion_status = FALSE;
9081
9082             if (button->type == EVENT_BUTTONPRESS)
9083               button_status = button->button;
9084             else
9085               button_status = MB_RELEASED;
9086
9087             if (HandleGadgets(button->x, button->y, button_status))
9088             {
9089               // do not handle this button event anymore
9090               break;
9091             }
9092
9093             button->x += video.screen_xoffset;
9094             button->y += video.screen_yoffset;
9095
9096             x = button->x * overlay.grid_xsize / video.screen_width;
9097             y = button->y * overlay.grid_ysize / video.screen_height;
9098
9099             if (button->type == EVENT_BUTTONPRESS)
9100             {
9101               grid_button_draw =
9102                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9103                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9104
9105               set_grid_button = TRUE;
9106             }
9107
9108             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9109           }
9110           break;
9111
9112         case EVENT_MOTIONNOTIFY:
9113           {
9114             MotionEvent *motion = (MotionEvent *)&event;
9115
9116             motion_status = TRUE;
9117
9118             if (HandleGadgets(motion->x, motion->y, button_status))
9119             {
9120               // do not handle this button event anymore
9121               break;
9122             }
9123
9124             motion->x += video.screen_xoffset;
9125             motion->y += video.screen_yoffset;
9126
9127             x = motion->x * overlay.grid_xsize / video.screen_width;
9128             y = motion->y * overlay.grid_ysize / video.screen_height;
9129
9130             set_grid_button = TRUE;
9131
9132             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9133           }
9134           break;
9135
9136         case SDL_WINDOWEVENT:
9137           HandleWindowEvent((WindowEvent *) &event);
9138
9139           // check if device has been rotated
9140           if (nr != GRID_ACTIVE_NR())
9141           {
9142             nr = GRID_ACTIVE_NR();
9143
9144             for (x = 0; x < MAX_GRID_XSIZE; x++)
9145               for (y = 0; y < MAX_GRID_YSIZE; y++)
9146                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9147                   overlay.grid_button[x][y];
9148           }
9149
9150           break;
9151
9152         case SDL_APP_WILLENTERBACKGROUND:
9153         case SDL_APP_DIDENTERBACKGROUND:
9154         case SDL_APP_WILLENTERFOREGROUND:
9155         case SDL_APP_DIDENTERFOREGROUND:
9156           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9157           break;
9158
9159         default:
9160           HandleOtherEvents(&event);
9161           break;
9162       }
9163
9164       // ---------- perform action set by handling events ----------
9165
9166       if (action == ACTION_ESCAPE)
9167       {
9168         // abort and restore the old key bindings
9169
9170         for (x = 0; x < MAX_GRID_XSIZE; x++)
9171           for (y = 0; y < MAX_GRID_YSIZE; y++)
9172             overlay.grid_button[x][y] = grid_button_old[x][y];
9173
9174         FadeSkipNextFadeIn();
9175
9176         finished = TRUE;
9177       }
9178       else if (action == ACTION_BACK)
9179       {
9180         // keep the configured key bindings and go to previous page
9181
9182         step_nr--;
9183
9184         if (step_nr < 0)
9185         {
9186           FadeSkipNextFadeIn();
9187
9188           finished = TRUE;
9189         }
9190       }
9191       else if (action == ACTION_NEXT)
9192       {
9193         // keep the configured key bindings and go to next page
9194
9195         step_nr++;
9196
9197         // all virtual buttons configured
9198         if (step_nr == 6)
9199         {
9200           finished = TRUE;
9201           success = TRUE;
9202         }
9203       }
9204
9205       if (action != ACTION_NONE && !finished)
9206       {
9207         for (x = 0; x < MAX_GRID_XSIZE; x++)
9208           for (y = 0; y < MAX_GRID_YSIZE; y++)
9209             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9210
9211         overlay.grid_button_highlight = grid_button[step_nr];
9212
9213         // configure next virtual button
9214
9215         ClearField();
9216
9217         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9218         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9219         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9220       }
9221
9222       if (set_grid_button)
9223       {
9224         overlay.grid_button[x][y] =
9225           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9226            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9227            grid_button_tmp[x][y]);
9228
9229         set_grid_button = FALSE;
9230       }
9231     }
9232
9233     BackToFront();
9234   }
9235
9236   for (x = 0; x < MAX_GRID_XSIZE; x++)
9237     for (y = 0; y < MAX_GRID_YSIZE; y++)
9238       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9239
9240   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9241
9242   SetOverlayShowGrid(FALSE);
9243
9244   return success;
9245 }
9246
9247 void ConfigureVirtualButtons(void)
9248 {
9249   boolean success = ConfigureVirtualButtonsMain();
9250
9251   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9252                          SCREEN_MASK_TOUCH2);
9253
9254   if (success)
9255   {
9256     int font_nr = FONT_TITLE_1;
9257     int font_height = getFontHeight(font_nr);
9258     int ypos1 = SYSIZE / 2 - font_height * 2;
9259     int ypos2 = SYSIZE / 2 - font_height * 1;
9260     unsigned int wait_frame_delay = 0;
9261     unsigned int wait_frame_delay_value = 2000;
9262
9263     ResetDelayCounter(&wait_frame_delay);
9264
9265     ClearField();
9266
9267     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9268     DrawTextSCentered(ypos2, font_nr, "configured!");
9269
9270     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9271       BackToFront();
9272
9273     ClearEventQueue();
9274   }
9275 }
9276
9277 void DrawSetupScreen(void)
9278 {
9279   align_xoffset = 0;
9280   align_yoffset = 0;
9281
9282   if (setup_mode == SETUP_MODE_INPUT)
9283     DrawSetupScreen_Input();
9284   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9285     DrawChooseTree(&scores_type_current);
9286   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9287     DrawChooseTree(&game_speed_current);
9288   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9289     DrawChooseTree(&scroll_delay_current);
9290   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9291     DrawChooseTree(&snapshot_mode_current);
9292   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9293     DrawChooseTree(&window_size_current);
9294   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9295     DrawChooseTree(&scaling_type_current);
9296   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9297     DrawChooseTree(&rendering_mode_current);
9298   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9299     DrawChooseTree(&vsync_mode_current);
9300   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9301     DrawChooseTree(&artwork.gfx_current);
9302   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9303     DrawChooseTree(&artwork.snd_current);
9304   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9305     DrawChooseTree(&artwork.mus_current);
9306   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9307     DrawChooseTree(&volume_simple_current);
9308   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9309     DrawChooseTree(&volume_loops_current);
9310   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9311     DrawChooseTree(&volume_music_current);
9312   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9313     DrawChooseTree(&touch_control_current);
9314   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9315     DrawChooseTree(&move_distance_current);
9316   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9317     DrawChooseTree(&drop_distance_current);
9318   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9319     DrawChooseTree(&transparency_current);
9320   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9321     DrawChooseTree(&grid_size_current[0][0]);
9322   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9323     DrawChooseTree(&grid_size_current[0][1]);
9324   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9325     DrawChooseTree(&grid_size_current[1][0]);
9326   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9327     DrawChooseTree(&grid_size_current[1][1]);
9328   else
9329     DrawSetupScreen_Generic();
9330
9331   PlayMenuSoundsAndMusic();
9332 }
9333
9334 void RedrawSetupScreenAfterFullscreenToggle(void)
9335 {
9336   if (setup_mode == SETUP_MODE_GRAPHICS ||
9337       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9338   {
9339     // update list selection from "setup.window_scaling_percent"
9340     execSetupGraphics_setWindowSizes(TRUE);
9341
9342     DrawSetupScreen();
9343   }
9344 }
9345
9346 void RedrawSetupScreenAfterScreenRotation(int nr)
9347 {
9348   int x, y;
9349
9350   if (setup_mode == SETUP_MODE_TOUCH)
9351   {
9352     // update virtual button settings (depending on screen orientation)
9353     DrawSetupScreen();
9354   }
9355   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
9356   {
9357     // save already configured virtual buttons
9358     for (x = 0; x < MAX_GRID_XSIZE; x++)
9359       for (y = 0; y < MAX_GRID_YSIZE; y++)
9360         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9361   }
9362 }
9363
9364 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
9365 {
9366   if (setup_mode == SETUP_MODE_INPUT)
9367     HandleSetupScreen_Input(mx, my, dx, dy, button);
9368   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9369     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
9370   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9371     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
9372   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9373     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
9374   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9375     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
9376   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9377     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
9378   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9379     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
9380   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9381     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
9382   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9383     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
9384   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9385     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
9386   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9387     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
9388   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9389     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
9390   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9391     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
9392   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9393     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
9394   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9395     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
9396   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9397     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
9398   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9399     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
9400   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9401     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
9402   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9403     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
9404   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9405     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
9406   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9407     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
9408   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9409     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
9410   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9411     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
9412   else
9413     HandleSetupScreen_Generic(mx, my, dx, dy, button);
9414 }
9415
9416 void HandleGameActions(void)
9417 {
9418   if (setup.ask_on_game_over)
9419     CheckGameOver();
9420
9421   if (game.restart_game_message != NULL)
9422   {
9423     RequestRestartGame(game.restart_game_message);
9424
9425     return;
9426   }
9427
9428   if (game_status != GAME_MODE_PLAYING)
9429     return;
9430
9431   GameActions();                // main game loop
9432
9433   if (tape.auto_play && !tape.playing)
9434     AutoPlayTapesContinue();    // continue automatically playing next tape
9435 }
9436
9437
9438 // ---------- new screen button stuff --------------------------------------
9439
9440 static struct
9441 {
9442   int gfx_unpressed, gfx_pressed;
9443   struct MenuPosInfo *pos;
9444   boolean *check_value;
9445   int gadget_id;
9446   int screen_mask;
9447   unsigned int event_mask;
9448   boolean is_touch_button;
9449   char *infotext;
9450 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
9451 {
9452   {
9453     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
9454     &menu.main.button.prev_level, NULL,
9455     SCREEN_CTRL_ID_PREV_LEVEL,
9456     SCREEN_MASK_MAIN,
9457     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9458     FALSE, "previous level"
9459   },
9460   {
9461     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
9462     &menu.main.button.next_level, NULL,
9463     SCREEN_CTRL_ID_NEXT_LEVEL,
9464     SCREEN_MASK_MAIN,
9465     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9466     FALSE, "next level"
9467   },
9468   {
9469     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE,
9470     &menu.scores.button.prev_level, NULL,
9471     SCREEN_CTRL_ID_PREV_LEVEL2,
9472     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9473     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9474     FALSE, "previous level"
9475   },
9476   {
9477     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE,
9478     &menu.scores.button.next_level, NULL,
9479     SCREEN_CTRL_ID_NEXT_LEVEL2,
9480     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9481     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9482     FALSE, "next level"
9483   },
9484   {
9485     IMG_MENU_BUTTON_PREV_SCORE, IMG_MENU_BUTTON_PREV_SCORE_ACTIVE,
9486     &menu.scores.button.prev_score, NULL,
9487     SCREEN_CTRL_ID_PREV_SCORE,
9488     SCREEN_MASK_SCORES_INFO,
9489     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9490     FALSE, "previous score"
9491   },
9492   {
9493     IMG_MENU_BUTTON_NEXT_SCORE, IMG_MENU_BUTTON_NEXT_SCORE_ACTIVE,
9494     &menu.scores.button.next_score, NULL,
9495     SCREEN_CTRL_ID_NEXT_SCORE,
9496     SCREEN_MASK_SCORES_INFO,
9497     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9498     FALSE, "next score"
9499   },
9500   {
9501     IMG_MENU_BUTTON_PLAY_TAPE, IMG_MENU_BUTTON_PLAY_TAPE,
9502     &menu.scores.button.play_tape, NULL,
9503     SCREEN_CTRL_ID_PLAY_TAPE,
9504     SCREEN_MASK_SCORES_INFO,
9505     GD_EVENT_RELEASED,
9506     FALSE, "play tape"
9507   },
9508   {
9509     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE,
9510     &menu.main.button.first_level, NULL,
9511     SCREEN_CTRL_ID_FIRST_LEVEL,
9512     SCREEN_MASK_MAIN,
9513     GD_EVENT_RELEASED,
9514     FALSE, "first level"
9515   },
9516   {
9517     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE,
9518     &menu.main.button.last_level, NULL,
9519     SCREEN_CTRL_ID_LAST_LEVEL,
9520     SCREEN_MASK_MAIN,
9521     GD_EVENT_RELEASED,
9522     FALSE, "last level"
9523   },
9524   {
9525     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE,
9526     &menu.main.button.level_number, NULL,
9527     SCREEN_CTRL_ID_LEVEL_NUMBER,
9528     SCREEN_MASK_MAIN,
9529     GD_EVENT_RELEASED,
9530     FALSE, "level number"
9531   },
9532   {
9533     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
9534     &menu.setup.button.prev_player, NULL,
9535     SCREEN_CTRL_ID_PREV_PLAYER,
9536     SCREEN_MASK_INPUT,
9537     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9538     FALSE, "previous player"
9539   },
9540   {
9541     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
9542     &menu.setup.button.next_player, NULL,
9543     SCREEN_CTRL_ID_NEXT_PLAYER,
9544     SCREEN_MASK_INPUT,
9545     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9546     FALSE, "next player"
9547   },
9548   {
9549     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE,
9550     &menu.main.button.insert_solution, NULL,
9551     SCREEN_CTRL_ID_INSERT_SOLUTION,
9552     SCREEN_MASK_MAIN_HAS_SOLUTION,
9553     GD_EVENT_RELEASED,
9554     FALSE, "insert solution tape"
9555   },
9556   {
9557     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE,
9558     &menu.main.button.play_solution, NULL,
9559     SCREEN_CTRL_ID_PLAY_SOLUTION,
9560     SCREEN_MASK_MAIN_HAS_SOLUTION,
9561     GD_EVENT_RELEASED,
9562     FALSE, "play solution tape"
9563   },
9564   {
9565     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE,
9566     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
9567     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
9568     SCREEN_MASK_MAIN,
9569     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
9570     FALSE, "switch ECS/AGA chipset"
9571   },
9572   {
9573     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK,
9574     &menu.setup.button.touch_back, NULL,
9575     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
9576     SCREEN_MASK_TOUCH,
9577     GD_EVENT_RELEASED,
9578     TRUE, "previous page"
9579   },
9580   {
9581     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT,
9582     &menu.setup.button.touch_next, NULL,
9583     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
9584     SCREEN_MASK_TOUCH,
9585     GD_EVENT_RELEASED,
9586     TRUE, "next page"
9587   },
9588   {
9589     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2,
9590     &menu.setup.button.touch_back2, NULL,
9591     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
9592     SCREEN_MASK_TOUCH2,
9593     GD_EVENT_RELEASED,
9594     TRUE, "previous page"
9595   },
9596   {
9597     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2,
9598     &menu.setup.button.touch_next2, NULL,
9599     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
9600     SCREEN_MASK_TOUCH2,
9601     GD_EVENT_RELEASED,
9602     TRUE, "next page"
9603   },
9604 };
9605
9606 static struct
9607 {
9608   int gfx_unpressed, gfx_pressed;
9609   int x, y;
9610   int gadget_id;
9611   char *infotext;
9612 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
9613 {
9614   {
9615     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
9616     -1, -1,     // these values are not constant, but can change at runtime
9617     SCREEN_CTRL_ID_SCROLL_UP,
9618     "scroll up"
9619   },
9620   {
9621     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
9622     -1, -1,     // these values are not constant, but can change at runtime
9623     SCREEN_CTRL_ID_SCROLL_DOWN,
9624     "scroll down"
9625   }
9626 };
9627
9628 static struct
9629 {
9630   int gfx_unpressed, gfx_pressed;
9631   int x, y;
9632   int width, height;
9633   int type;
9634   int gadget_id;
9635   char *infotext;
9636 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
9637 {
9638   {
9639     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
9640     -1, -1,     // these values are not constant, but can change at runtime
9641     -1, -1,     // these values are not constant, but can change at runtime
9642     GD_TYPE_SCROLLBAR_VERTICAL,
9643     SCREEN_CTRL_ID_SCROLL_VERTICAL,
9644     "scroll level series vertically"
9645   }
9646 };
9647
9648 static struct
9649 {
9650   int graphic;
9651   int gadget_id;
9652   int x, y;
9653   int size;
9654   char *value;
9655   char *infotext;
9656 } textinput_info[NUM_SCREEN_TEXTINPUT] =
9657 {
9658   {
9659     IMG_SETUP_INPUT_TEXT,
9660     SCREEN_CTRL_ID_NETWORK_SERVER,
9661     -1, -1,     // these values are not constant, but can change at runtime
9662     MAX_SETUP_TEXT_INPUT_LEN,
9663     network_server_hostname,
9664     "Network Server Hostname / IP"
9665   },
9666 };
9667
9668 static void CreateScreenMenubuttons(void)
9669 {
9670   struct GadgetInfo *gi;
9671   unsigned int event_mask;
9672   int i;
9673
9674   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9675   {
9676     struct MenuPosInfo *pos = menubutton_info[i].pos;
9677     int screen_mask = menubutton_info[i].screen_mask;
9678     boolean is_touch_button = menubutton_info[i].is_touch_button;
9679     boolean is_check_button = menubutton_info[i].check_value != NULL;
9680     boolean is_score_button = (screen_mask & SCREEN_MASK_SCORES_INFO);
9681     boolean has_gfx_pressed = (menubutton_info[i].gfx_pressed ==
9682                                menubutton_info[i].gfx_unpressed);
9683     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9684     int gfx_unpressed, gfx_pressed;
9685     int x, y, width, height;
9686     int gd_x1, gd_x2, gd_y1, gd_y2;
9687     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
9688     int id = menubutton_info[i].gadget_id;
9689     int type = GD_TYPE_NORMAL_BUTTON;
9690     boolean checked = FALSE;
9691
9692     event_mask = menubutton_info[i].event_mask;
9693
9694     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
9695     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
9696
9697     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
9698     height = graphic_info[menubutton_info[i].gfx_pressed].height;
9699
9700     gfx_unpressed = menubutton_info[i].gfx_unpressed;
9701     gfx_pressed   = menubutton_info[i].gfx_pressed;
9702     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9703     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9704     gd_x1 = graphic_info[gfx_unpressed].src_x;
9705     gd_y1 = graphic_info[gfx_unpressed].src_y;
9706     gd_x2 = graphic_info[gfx_pressed].src_x;
9707     gd_y2 = graphic_info[gfx_pressed].src_y;
9708     gd_x1a = gd_x1;
9709     gd_y1a = gd_y1;
9710     gd_x2a = gd_x2;
9711     gd_y2a = gd_y2;
9712
9713     if (has_gfx_pressed)
9714     {
9715       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
9716       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
9717     }
9718
9719     if (is_check_button)
9720     {
9721       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
9722       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
9723       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
9724       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
9725
9726       type = GD_TYPE_CHECK_BUTTON;
9727       checked = *menubutton_info[i].check_value;
9728     }
9729
9730     if (is_score_button)
9731     {
9732       // if x/y set to -1, dynamically place buttons next to title text
9733       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
9734
9735       // special compatibility handling for "Snake Bite" graphics set
9736       if (strPrefix(leveldir_current->identifier, "snake_bite"))
9737         title_width = strlen(INFOTEXT_SCORE_ENTRY) * 32;
9738
9739       if (pos->x == -1)
9740         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
9741              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
9742              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
9743              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
9744
9745       if (pos->y == -1)
9746         y = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ||
9747              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ? mSY + MENU_TITLE1_YPOS : 0);
9748     }
9749
9750     gi = CreateGadget(GDI_CUSTOM_ID, id,
9751                       GDI_CUSTOM_TYPE_ID, i,
9752                       GDI_IMAGE_ID, gfx_unpressed,
9753                       GDI_INFO_TEXT, menubutton_info[i].infotext,
9754                       GDI_X, x,
9755                       GDI_Y, y,
9756                       GDI_WIDTH, width,
9757                       GDI_HEIGHT, height,
9758                       GDI_TYPE, type,
9759                       GDI_STATE, GD_BUTTON_UNPRESSED,
9760                       GDI_CHECKED, checked,
9761                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9762                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9763                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1a, gd_y1a,
9764                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2a, gd_y2a,
9765                       GDI_DIRECT_DRAW, FALSE,
9766                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
9767                       GDI_EVENT_MASK, event_mask,
9768                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9769                       GDI_END);
9770
9771     if (gi == NULL)
9772       Fail("cannot create gadget");
9773
9774     screen_gadget[id] = gi;
9775   }
9776 }
9777
9778 static void CreateScreenScrollbuttons(void)
9779 {
9780   struct GadgetInfo *gi;
9781   unsigned int event_mask;
9782   int i;
9783
9784   // these values are not constant, but can change at runtime
9785   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
9786   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
9787   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
9788   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
9789
9790   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
9791   {
9792     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9793     int gfx_unpressed, gfx_pressed;
9794     int x, y, width, height;
9795     int gd_x1, gd_x2, gd_y1, gd_y2;
9796     int id = scrollbutton_info[i].gadget_id;
9797
9798     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
9799
9800     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
9801     y = mSY + scrollbutton_info[i].y;
9802     width = SC_SCROLLBUTTON_XSIZE;
9803     height = SC_SCROLLBUTTON_YSIZE;
9804
9805     // correct scrollbar position if placed outside menu (playfield) area
9806     if (x > SX + SC_SCROLL_UP_XPOS)
9807       x = SX + SC_SCROLL_UP_XPOS;
9808
9809     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
9810       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
9811                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
9812
9813     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
9814     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
9815     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9816     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9817     gd_x1 = graphic_info[gfx_unpressed].src_x;
9818     gd_y1 = graphic_info[gfx_unpressed].src_y;
9819     gd_x2 = graphic_info[gfx_pressed].src_x;
9820     gd_y2 = graphic_info[gfx_pressed].src_y;
9821
9822     gi = CreateGadget(GDI_CUSTOM_ID, id,
9823                       GDI_CUSTOM_TYPE_ID, i,
9824                       GDI_IMAGE_ID, gfx_unpressed,
9825                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
9826                       GDI_X, x,
9827                       GDI_Y, y,
9828                       GDI_WIDTH, width,
9829                       GDI_HEIGHT, height,
9830                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
9831                       GDI_STATE, GD_BUTTON_UNPRESSED,
9832                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9833                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9834                       GDI_DIRECT_DRAW, FALSE,
9835                       GDI_EVENT_MASK, event_mask,
9836                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9837                       GDI_END);
9838
9839     if (gi == NULL)
9840       Fail("cannot create gadget");
9841
9842     screen_gadget[id] = gi;
9843   }
9844 }
9845
9846 static void CreateScreenScrollbars(void)
9847 {
9848   int i;
9849
9850   // these values are not constant, but can change at runtime
9851   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
9852   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
9853   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
9854   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
9855
9856   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
9857   {
9858     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9859     int gfx_unpressed, gfx_pressed;
9860     int x, y, width, height;
9861     int gd_x1, gd_x2, gd_y1, gd_y2;
9862     struct GadgetInfo *gi;
9863     int items_max, items_visible, item_position;
9864     unsigned int event_mask;
9865     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
9866     int id = scrollbar_info[i].gadget_id;
9867
9868     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
9869
9870     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
9871     y = mSY + scrollbar_info[i].y;
9872     width  = scrollbar_info[i].width;
9873     height = scrollbar_info[i].height;
9874
9875     // correct scrollbar position if placed outside menu (playfield) area
9876     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
9877       x = SX + SC_SCROLL_VERTICAL_XPOS;
9878
9879     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
9880       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
9881
9882     items_max = num_page_entries;
9883     items_visible = num_page_entries;
9884     item_position = 0;
9885
9886     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
9887     gfx_pressed   = scrollbar_info[i].gfx_pressed;
9888     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9889     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9890     gd_x1 = graphic_info[gfx_unpressed].src_x;
9891     gd_y1 = graphic_info[gfx_unpressed].src_y;
9892     gd_x2 = graphic_info[gfx_pressed].src_x;
9893     gd_y2 = graphic_info[gfx_pressed].src_y;
9894
9895     gi = CreateGadget(GDI_CUSTOM_ID, id,
9896                       GDI_CUSTOM_TYPE_ID, i,
9897                       GDI_IMAGE_ID, gfx_unpressed,
9898                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
9899                       GDI_X, x,
9900                       GDI_Y, y,
9901                       GDI_WIDTH, width,
9902                       GDI_HEIGHT, height,
9903                       GDI_TYPE, scrollbar_info[i].type,
9904                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
9905                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
9906                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
9907                       GDI_WHEEL_AREA_X, SX,
9908                       GDI_WHEEL_AREA_Y, SY,
9909                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
9910                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
9911                       GDI_STATE, GD_BUTTON_UNPRESSED,
9912                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9913                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9914                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
9915                       GDI_DIRECT_DRAW, FALSE,
9916                       GDI_EVENT_MASK, event_mask,
9917                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9918                       GDI_END);
9919
9920     if (gi == NULL)
9921       Fail("cannot create gadget");
9922
9923     screen_gadget[id] = gi;
9924   }
9925 }
9926
9927 static void CreateScreenTextInputGadgets(void)
9928 {
9929   int i;
9930
9931   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
9932   {
9933     int graphic = textinput_info[i].graphic;
9934     struct GraphicInfo *gd = &graphic_info[graphic];
9935     int gd_x1 = gd->src_x;
9936     int gd_y1 = gd->src_y;
9937     int gd_x2 = gd->src_x + gd->active_xoffset;
9938     int gd_y2 = gd->src_y + gd->active_yoffset;
9939     struct GadgetInfo *gi;
9940     unsigned int event_mask;
9941     int id = textinput_info[i].gadget_id;
9942     int x = textinput_info[i].x;
9943     int y = textinput_info[i].y;
9944
9945     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
9946
9947     gi = CreateGadget(GDI_CUSTOM_ID, id,
9948                       GDI_CUSTOM_TYPE_ID, i,
9949                       GDI_INFO_TEXT, textinput_info[i].infotext,
9950                       GDI_X, SX + x,
9951                       GDI_Y, SY + y,
9952                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
9953                       GDI_TEXT_VALUE, textinput_info[i].value,
9954                       GDI_TEXT_SIZE, textinput_info[i].size,
9955                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
9956                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
9957                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
9958                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
9959                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
9960                       GDI_DESIGN_WIDTH, gd->width,
9961                       GDI_EVENT_MASK, event_mask,
9962                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9963                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
9964                       GDI_END);
9965
9966     if (gi == NULL)
9967       Fail("cannot create gadget");
9968
9969     screen_gadget[id] = gi;
9970   }
9971 }
9972
9973 void CreateScreenGadgets(void)
9974 {
9975   CreateScreenMenubuttons();
9976
9977   CreateScreenScrollbuttons();
9978   CreateScreenScrollbars();
9979
9980   CreateScreenTextInputGadgets();
9981 }
9982
9983 void FreeScreenGadgets(void)
9984 {
9985   int i;
9986
9987   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
9988     FreeGadget(screen_gadget[i]);
9989 }
9990
9991 static void RedrawScreenMenuGadgets(int screen_mask)
9992 {
9993   int i;
9994
9995   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9996     if (screen_mask & menubutton_info[i].screen_mask)
9997       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
9998 }
9999
10000 static void MapScreenMenuGadgets(int screen_mask)
10001 {
10002   int i;
10003
10004   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10005     if (screen_mask & menubutton_info[i].screen_mask)
10006       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10007 }
10008
10009 static void UnmapScreenMenuGadgets(int screen_mask)
10010 {
10011   int i;
10012
10013   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10014   {
10015     if (screen_mask & menubutton_info[i].screen_mask)
10016     {
10017       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10018
10019       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
10020         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
10021                        screen_gadget[menubutton_info[i].gadget_id]->y,
10022                        screen_gadget[menubutton_info[i].gadget_id]->width,
10023                        screen_gadget[menubutton_info[i].gadget_id]->height);
10024     }
10025   }
10026 }
10027
10028 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
10029 {
10030   if (map_gadgets)
10031     MapScreenMenuGadgets(screen_mask);
10032   else
10033     UnmapScreenMenuGadgets(screen_mask);
10034 }
10035
10036 static void MapScreenGadgets(int num_entries)
10037 {
10038   int i;
10039
10040   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
10041     return;
10042
10043   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10044     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10045
10046   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10047     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10048 }
10049
10050 static void UnmapScreenGadgets()
10051 {
10052   int i;
10053
10054   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10055     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10056
10057   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10058     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10059 }
10060
10061 static void MapScreenTreeGadgets(TreeInfo *ti)
10062 {
10063   MapScreenGadgets(numTreeInfoInGroup(ti));
10064 }
10065
10066 static void UnmapScreenTreeGadgets(void)
10067 {
10068   UnmapScreenGadgets();
10069 }
10070
10071 static void AdjustScoreInfoButtons_SelectScore(int x, int y1, int y2)
10072 {
10073   struct GadgetInfo *gi_1 = screen_gadget[SCREEN_CTRL_ID_PREV_SCORE];
10074   struct GadgetInfo *gi_2 = screen_gadget[SCREEN_CTRL_ID_NEXT_SCORE];
10075   struct MenuPosInfo *pos_1 = menubutton_info[SCREEN_CTRL_ID_PREV_SCORE].pos;
10076   struct MenuPosInfo *pos_2 = menubutton_info[SCREEN_CTRL_ID_NEXT_SCORE].pos;
10077
10078   if (pos_1->x == -1 && pos_1->y == -1)
10079     ModifyGadget(gi_1, GDI_X, x, GDI_Y, y1, GDI_END);
10080
10081   if (pos_2->x == -1 && pos_2->y == -1)
10082     ModifyGadget(gi_2, GDI_X, x, GDI_Y, y2, GDI_END);
10083 }
10084
10085 static void AdjustScoreInfoButtons_PlayTape(int x, int y, boolean visible)
10086 {
10087   struct GadgetInfo *gi = screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE];
10088   struct MenuPosInfo *pos = menubutton_info[SCREEN_CTRL_ID_PLAY_TAPE].pos;
10089
10090   // set gadget position dynamically, pre-defined or off-screen
10091   int xx = (visible ? (pos->x == -1 ? x : pos->x) : POS_OFFSCREEN);
10092   int yy = (visible ? (pos->y == -1 ? y : pos->y) : POS_OFFSCREEN);
10093
10094   ModifyGadget(gi, GDI_X, xx, GDI_Y, yy, GDI_END);
10095   MapGadget(gi);        // (needed if deactivated on last score page)
10096 }
10097
10098 static void HandleScreenGadgets(struct GadgetInfo *gi)
10099 {
10100   int id = gi->custom_id;
10101   int button = gi->event.button;
10102   int step = (button == MB_LEFTBUTTON   ? 1 :
10103               button == MB_MIDDLEBUTTON ? 5 :
10104               button == MB_RIGHTBUTTON  ? 10 : 1);
10105
10106   switch (id)
10107   {
10108     case SCREEN_CTRL_ID_PREV_LEVEL:
10109       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10110       break;
10111
10112     case SCREEN_CTRL_ID_NEXT_LEVEL:
10113       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10114       break;
10115
10116     case SCREEN_CTRL_ID_PREV_LEVEL2:
10117       HandleHallOfFame_SelectLevel(step, -1);
10118       break;
10119
10120     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10121       HandleHallOfFame_SelectLevel(step, +1);
10122       break;
10123
10124     case SCREEN_CTRL_ID_PREV_SCORE:
10125       HandleScoreInfo_SelectScore(step, -1);
10126       break;
10127
10128     case SCREEN_CTRL_ID_NEXT_SCORE:
10129       HandleScoreInfo_SelectScore(step, +1);
10130       break;
10131
10132     case SCREEN_CTRL_ID_PLAY_TAPE:
10133       HandleScoreInfo_PlayTape();
10134       break;
10135
10136     case SCREEN_CTRL_ID_FIRST_LEVEL:
10137       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10138       break;
10139
10140     case SCREEN_CTRL_ID_LAST_LEVEL:
10141       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10142       break;
10143
10144     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10145       CloseDoor(DOOR_CLOSE_2);
10146       SetGameStatus(GAME_MODE_LEVELNR);
10147       DrawChooseLevelNr();
10148       break;
10149
10150     case SCREEN_CTRL_ID_PREV_PLAYER:
10151       HandleSetupScreen_Input_Player(step, -1);
10152       break;
10153
10154     case SCREEN_CTRL_ID_NEXT_PLAYER:
10155       HandleSetupScreen_Input_Player(step, +1);
10156       break;
10157
10158     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10159       InsertSolutionTape();
10160       break;
10161
10162     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10163       PlaySolutionTape();
10164       break;
10165
10166     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10167       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10168       DrawMainMenu();
10169       break;
10170
10171     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10172     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10173     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10174     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10175       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10176       break;
10177
10178     case SCREEN_CTRL_ID_SCROLL_UP:
10179       if (game_status == GAME_MODE_NAMES)
10180         HandleChoosePlayerName(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10181       else if (game_status == GAME_MODE_LEVELS)
10182         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10183       else if (game_status == GAME_MODE_LEVELNR)
10184         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10185       else if (game_status == GAME_MODE_SETUP)
10186         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10187       else if (game_status == GAME_MODE_INFO)
10188         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10189       else if (game_status == GAME_MODE_SCORES)
10190         HandleHallOfFame(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10191       break;
10192
10193     case SCREEN_CTRL_ID_SCROLL_DOWN:
10194       if (game_status == GAME_MODE_NAMES)
10195         HandleChoosePlayerName(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10196       else if (game_status == GAME_MODE_LEVELS)
10197         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10198       else if (game_status == GAME_MODE_LEVELNR)
10199         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10200       else if (game_status == GAME_MODE_SETUP)
10201         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10202       else if (game_status == GAME_MODE_INFO)
10203         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10204       else if (game_status == GAME_MODE_SCORES)
10205         HandleHallOfFame(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10206       break;
10207
10208     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
10209       if (game_status == GAME_MODE_NAMES)
10210         HandleChoosePlayerName(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10211       else if (game_status == GAME_MODE_LEVELS)
10212         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10213       else if (game_status == GAME_MODE_LEVELNR)
10214         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10215       else if (game_status == GAME_MODE_SETUP)
10216         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10217       else if (game_status == GAME_MODE_INFO)
10218         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10219       else if (game_status == GAME_MODE_SCORES)
10220         HandleHallOfFame(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10221       break;
10222
10223     case SCREEN_CTRL_ID_NETWORK_SERVER:
10224     {
10225       if (!strEqual(gi->textinput.value, ""))
10226       {
10227         setString(&setup.network_server_hostname, gi->textinput.value);
10228
10229         network.server_host = setup.network_server_hostname;
10230       }
10231       else
10232       {
10233         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
10234
10235         network.server_host = NULL;
10236       }
10237
10238       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
10239         network.server_host = NULL;
10240
10241       execSetupGame_setNetworkServerText();
10242
10243       DrawSetupScreen();
10244
10245       break;
10246     }
10247
10248     default:
10249       break;
10250   }
10251 }
10252
10253 void DumpScreenIdentifiers(void)
10254 {
10255   int i;
10256
10257   Print("Active screen elements on current screen:\n");
10258
10259   for (i = 0; main_controls[i].nr != -1; i++)
10260   {
10261     struct MainControlInfo *mci = &main_controls[i];
10262
10263     if (mci->button_graphic != -1)
10264     {
10265       char *token = getTokenFromImageID(mci->button_graphic);
10266
10267       Print("- '%s'\n", token);
10268     }
10269   }
10270
10271   Print("Done.\n");
10272 }
10273
10274 boolean DoScreenAction(int image_id)
10275 {
10276   int i;
10277
10278   if (game_status != GAME_MODE_MAIN)
10279     return FALSE;
10280
10281   for (i = 0; main_controls[i].nr != -1; i++)
10282   {
10283     struct MainControlInfo *mci = &main_controls[i];
10284     struct MenuPosInfo *pos = mci->pos_button;
10285
10286     if (mci->button_graphic == image_id)
10287     {
10288       int x = mSX + pos->x;
10289       int y = mSY + pos->y;
10290
10291       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
10292
10293       return TRUE;
10294     }
10295   }
10296
10297   return FALSE;
10298 }
10299
10300 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
10301 {
10302   // get tree info node of newly added level or artwork set
10303   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
10304   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
10305                                                       tree_subdir_new);
10306   if (tree_node_new == NULL)    // should not happen
10307     return;
10308
10309   // if request dialog is active, do nothing
10310   if (game.request_active)
10311     return;
10312
10313   if (game_status == GAME_MODE_MAIN &&
10314       tree_type == TREE_TYPE_LEVEL_DIR)
10315   {
10316     // when adding new level set in main menu, select it as current level set
10317
10318     // change current level set to newly added level set from zip file
10319     leveldir_current = tree_node_new;
10320
10321     // change current level number to first level of newly added level set
10322     level_nr = leveldir_current->first_level;
10323
10324     // redraw screen to reflect changed level set
10325     DrawMainMenu();
10326
10327     // save this level set and level number as last selected level set
10328     SaveLevelSetup_LastSeries();
10329     SaveLevelSetup_SeriesInfo();
10330   }
10331   else if (game_status == GAME_MODE_LEVELS &&
10332            tree_type == TREE_TYPE_LEVEL_DIR)
10333   {
10334     // when adding new level set in level set menu, set cursor and update screen
10335
10336     leveldir_current = tree_node_new;
10337
10338     DrawChooseTree(&leveldir_current);
10339   }
10340   else if (game_status == GAME_MODE_SETUP)
10341   {
10342     // when adding new artwork set in setup menu, set cursor and update screen
10343
10344     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
10345         tree_type == TREE_TYPE_GRAPHICS_DIR)
10346     {
10347       artwork.gfx_current = tree_node_new;
10348
10349       DrawChooseTree(&artwork.gfx_current);
10350     }
10351     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
10352              tree_type == TREE_TYPE_SOUNDS_DIR)
10353     {
10354       artwork.snd_current = tree_node_new;
10355
10356       DrawChooseTree(&artwork.snd_current);
10357     }
10358     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
10359              tree_type == TREE_TYPE_MUSIC_DIR)
10360     {
10361       artwork.mus_current = tree_node_new;
10362
10363       DrawChooseTree(&artwork.mus_current);
10364     }
10365   }
10366 }
10367
10368 static int UploadTapes(void)
10369 {
10370   SetGameStatus(GAME_MODE_LOADING);
10371
10372   FadeSetEnterScreen();
10373   FadeOut(REDRAW_ALL);
10374
10375   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
10376
10377   FadeIn(REDRAW_ALL);
10378
10379   DrawInitTextHead("Uploading tapes");
10380
10381   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
10382   global.autoplay_leveldir = "ALL";
10383   global.autoplay_all = TRUE;
10384
10385   int num_tapes_uploaded = AutoPlayTapes();
10386
10387   global.autoplay_mode = AUTOPLAY_MODE_NONE;
10388   global.autoplay_leveldir = NULL;
10389   global.autoplay_all = FALSE;
10390
10391   SetGameStatus(GAME_MODE_MAIN);
10392
10393   DrawMainMenu();
10394
10395   return num_tapes_uploaded;
10396 }
10397
10398 static boolean OfferUploadTapes(void)
10399 {
10400   if (!Request(setup.has_remaining_tapes ?
10401                "Upload missing tapes to the high score server now?" :
10402                "Upload all your tapes to the high score server now?", REQ_ASK))
10403     return FALSE;
10404
10405   int num_tapes_uploaded = UploadTapes();
10406   char message[100];
10407
10408   if (num_tapes_uploaded < 0)
10409   {
10410     num_tapes_uploaded = -num_tapes_uploaded - 1;
10411
10412     if (num_tapes_uploaded == 0)
10413       sprintf(message, "Upload failed! No tapes uploaded!");
10414     else if (num_tapes_uploaded == 1)
10415       sprintf(message, "Upload failed! Only 1 tape uploaded!");
10416     else
10417       sprintf(message, "Upload failed! Only %d tapes uploaded!",
10418               num_tapes_uploaded);
10419
10420     Request(message, REQ_CONFIRM);
10421
10422     // if uploading tapes failed, add tape upload entry to setup menu
10423     setup.provide_uploading_tapes = TRUE;
10424     setup.has_remaining_tapes = TRUE;
10425
10426     SaveSetup_ServerSetup();
10427
10428     return FALSE;
10429   }
10430
10431   if (num_tapes_uploaded == 0)
10432     sprintf(message, "No tapes uploaded!");
10433   else if (num_tapes_uploaded == 1)
10434     sprintf(message, "1 tape uploaded!");
10435   else
10436     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
10437
10438   Request(message, REQ_CONFIRM);
10439
10440   if (num_tapes_uploaded > 0)
10441     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
10442
10443   // after all tapes have been uploaded, remove entry from setup menu
10444   setup.provide_uploading_tapes = FALSE;
10445   setup.has_remaining_tapes = FALSE;
10446
10447   SaveSetup_ServerSetup();
10448
10449   return TRUE;
10450 }
10451
10452 static void CheckUploadTapes(void)
10453 {
10454   if (!setup.ask_for_uploading_tapes)
10455     return;
10456
10457   // after asking for uploading tapes, do not ask again
10458   setup.ask_for_uploading_tapes = FALSE;
10459   setup.ask_for_remaining_tapes = FALSE;
10460
10461   if (directoryExists(getTapeDir(NULL)))
10462   {
10463     boolean tapes_uploaded = OfferUploadTapes();
10464
10465     if (!tapes_uploaded)
10466     {
10467       Request(setup.has_remaining_tapes ?
10468               "You can upload missing tapes from the setup menu later!" :
10469               "You can upload your tapes from the setup menu later!",
10470               REQ_CONFIRM);
10471     }
10472   }
10473   else
10474   {
10475     // if tapes directory does not exist yet, never offer uploading all tapes
10476     setup.provide_uploading_tapes = FALSE;
10477   }
10478
10479   SaveSetup_ServerSetup();
10480 }
10481
10482 static void UpgradePlayerUUID(void)
10483 {
10484   ApiResetUUIDAsThread(getUUID());
10485 }
10486
10487 static void CheckUpgradePlayerUUID(void)
10488 {
10489   if (setup.player_version > 1)
10490     return;
10491
10492   UpgradePlayerUUID();
10493 }
10494
10495 void CheckApiServerTasks(void)
10496 {
10497   // check if the player's UUID has to be upgraded
10498   CheckUpgradePlayerUUID();
10499
10500   // check if there are any tapes to be uploaded
10501   CheckUploadTapes();
10502 }