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