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