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