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