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