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