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