added setup option to continue recording after replaying tape
[rocksndiamonds.git] / src / screens.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // screens.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "screens.h"
15 #include "events.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "editor.h"
19 #include "files.h"
20 #include "tape.h"
21 #include "anim.h"
22 #include "network.h"
23 #include "init.h"
24 #include "config.h"
25 #include "api.h"
26
27
28 #define DEBUG_JOYSTICKS         0
29
30
31 // screens on the info screen
32 #define INFO_MODE_MAIN                  0
33 #define INFO_MODE_TITLE                 1
34 #define INFO_MODE_ELEMENTS              2
35 #define INFO_MODE_MUSIC                 3
36 #define INFO_MODE_CREDITS               4
37 #define INFO_MODE_PROGRAM               5
38 #define INFO_MODE_VERSION               6
39 #define INFO_MODE_LEVELSET              7
40
41 #define MAX_INFO_MODES                  8
42
43 // screens on the setup screen
44 // (must match GFX_SPECIAL_ARG_SETUP_* values as defined in src/main.h)
45 // (should also match corresponding entries in src/conf_gfx.c)
46 #define SETUP_MODE_MAIN                 0
47 #define SETUP_MODE_GAME                 1
48 #define SETUP_MODE_ENGINES              2
49 #define SETUP_MODE_EDITOR               3
50 #define SETUP_MODE_GRAPHICS             4
51 #define SETUP_MODE_SOUND                5
52 #define SETUP_MODE_ARTWORK              6
53 #define SETUP_MODE_INPUT                7
54 #define SETUP_MODE_TOUCH                8
55 #define SETUP_MODE_SHORTCUTS            9
56 #define SETUP_MODE_SHORTCUTS_1          10
57 #define SETUP_MODE_SHORTCUTS_2          11
58 #define SETUP_MODE_SHORTCUTS_3          12
59 #define SETUP_MODE_SHORTCUTS_4          13
60 #define SETUP_MODE_SHORTCUTS_5          14
61
62 // sub-screens on the setup screen (generic)
63 #define SETUP_MODE_CHOOSE_ARTWORK       15
64 #define SETUP_MODE_CHOOSE_OTHER         16
65
66 // sub-screens on the setup screen (specific)
67 #define SETUP_MODE_CHOOSE_SCORES_TYPE   17
68 #define SETUP_MODE_CHOOSE_GAME_SPEED    18
69 #define SETUP_MODE_CHOOSE_SCROLL_DELAY  19
70 #define SETUP_MODE_CHOOSE_SNAPSHOT_MODE 20
71 #define SETUP_MODE_CHOOSE_WINDOW_SIZE   21
72 #define SETUP_MODE_CHOOSE_SCALING_TYPE  22
73 #define SETUP_MODE_CHOOSE_RENDERING     23
74 #define SETUP_MODE_CHOOSE_VSYNC         24
75 #define SETUP_MODE_CHOOSE_GRAPHICS      25
76 #define SETUP_MODE_CHOOSE_SOUNDS        26
77 #define SETUP_MODE_CHOOSE_MUSIC         27
78 #define SETUP_MODE_CHOOSE_VOLUME_SIMPLE 28
79 #define SETUP_MODE_CHOOSE_VOLUME_LOOPS  29
80 #define SETUP_MODE_CHOOSE_VOLUME_MUSIC  30
81 #define SETUP_MODE_CHOOSE_TOUCH_CONTROL 31
82 #define SETUP_MODE_CHOOSE_MOVE_DISTANCE 32
83 #define SETUP_MODE_CHOOSE_DROP_DISTANCE 33
84 #define SETUP_MODE_CHOOSE_TRANSPARENCY  34
85 #define SETUP_MODE_CHOOSE_GRID_XSIZE_0  35
86 #define SETUP_MODE_CHOOSE_GRID_YSIZE_0  36
87 #define SETUP_MODE_CHOOSE_GRID_XSIZE_1  37
88 #define SETUP_MODE_CHOOSE_GRID_YSIZE_1  38
89 #define SETUP_MODE_CONFIG_VIRT_BUTTONS  39
90
91 #define MAX_SETUP_MODES                 40
92
93 #define MAX_MENU_MODES                  MAX(MAX_INFO_MODES, MAX_SETUP_MODES)
94
95 // setup screen titles
96 #define STR_SETUP_MAIN                  "Setup"
97 #define STR_SETUP_GAME                  "Game & Menu"
98 #define STR_SETUP_ENGINES               "Game Engines"
99 #define STR_SETUP_EDITOR                "Editor"
100 #define STR_SETUP_GRAPHICS              "Graphics"
101 #define STR_SETUP_SOUND                 "Sound & Music"
102 #define STR_SETUP_ARTWORK               "Custom Artwork"
103 #define STR_SETUP_INPUT                 "Input Devices"
104 #define STR_SETUP_TOUCH                 "Touch Controls"
105 #define STR_SETUP_SHORTCUTS             "Key Shortcuts"
106 #define STR_SETUP_EXIT                  "Exit"
107 #define STR_SETUP_SAVE_AND_EXIT         "Save and Exit"
108
109 #define STR_SETUP_CHOOSE_SCORES_TYPE    "Scores Type"
110 #define STR_SETUP_CHOOSE_GAME_SPEED     "Game Speed"
111 #define STR_SETUP_CHOOSE_SCROLL_DELAY   "Scroll Delay"
112 #define STR_SETUP_CHOOSE_SNAPSHOT_MODE  "Snapshot Mode"
113 #define STR_SETUP_CHOOSE_WINDOW_SIZE    "Window Scaling"
114 #define STR_SETUP_CHOOSE_SCALING_TYPE   "Anti-Aliasing"
115 #define STR_SETUP_CHOOSE_RENDERING      "Rendering Mode"
116 #define STR_SETUP_CHOOSE_VSYNC          "VSync Mode"
117 #define STR_SETUP_CHOOSE_VOLUME_SIMPLE  "Sound Volume"
118 #define STR_SETUP_CHOOSE_VOLUME_LOOPS   "Loops Volume"
119 #define STR_SETUP_CHOOSE_VOLUME_MUSIC   "Music Volume"
120 #define STR_SETUP_CHOOSE_TOUCH_CONTROL  "Control Type"
121 #define STR_SETUP_CHOOSE_MOVE_DISTANCE  "Move Distance"
122 #define STR_SETUP_CHOOSE_DROP_DISTANCE  "Drop Distance"
123 #define STR_SETUP_CHOOSE_TRANSPARENCY   "Transparency"
124 #define STR_SETUP_CHOOSE_GRID_XSIZE_0   "Horiz. Buttons"
125 #define STR_SETUP_CHOOSE_GRID_YSIZE_0   "Vert. Buttons"
126 #define STR_SETUP_CHOOSE_GRID_XSIZE_1   "Horiz. Buttons"
127 #define STR_SETUP_CHOOSE_GRID_YSIZE_1   "Vert. Buttons"
128
129 // other screen text constants
130 #define STR_CHOOSE_TREE_EDIT            "Edit"
131 #define MENU_CHOOSE_TREE_FONT(x)        (FONT_TEXT_1 + (x))
132 #define MENU_CHOOSE_TREE_COLOR(ti, a)   TREE_COLOR(ti, a)
133
134 #define TEXT_NEXT_PAGE                  "Press any key or button for next page"
135 #define TEXT_INFO_MENU                  "Press any key or button for info menu"
136
137 // for input setup functions
138 #define SETUPINPUT_SCREEN_POS_START     0
139 #define SETUPINPUT_SCREEN_POS_EMPTY1    3
140 #define SETUPINPUT_SCREEN_POS_EMPTY2    12
141 #define SETUPINPUT_SCREEN_POS_END       13
142
143 #define MENU_SETUP_FONT_TITLE           FONT_TEXT_1
144 #define MENU_SETUP_FONT_TEXT            FONT_TITLE_2
145
146 #define MAX_SETUP_TEXT_INPUT_LEN        28
147
148 // for various menu stuff
149 #define MENU_SCREEN_START_XPOS          1
150 #define MENU_SCREEN_START_YPOS          2
151 #define MENU_SCREEN_VALUE_XPOS          (SCR_FIELDX - 3)
152 #define MENU_SCREEN_TEXT2_XPOS          (SCR_FIELDX - 2)
153 #define MENU_SCREEN_MAX_XPOS            (SCR_FIELDX - 1)
154 #define MENU_TITLE1_YPOS                8
155 #define MENU_TITLE2_YPOS                46
156 #define MENU_INFO_FONT_TITLE            FONT_TEXT_1
157 #define MENU_INFO_FONT_HEAD             FONT_TEXT_2
158 #define MENU_INFO_FONT_TEXT             FONT_TEXT_3
159 #define MENU_INFO_FONT_FOOT             FONT_TEXT_4
160 #define MENU_INFO_SPACE_HEAD            (menu.headline2_spacing_info[info_mode])
161 #define MENU_SCREEN_INFO_SPACE_LEFT     (menu.left_spacing_info[info_mode])
162 #define MENU_SCREEN_INFO_SPACE_RIGHT    (menu.right_spacing_info[info_mode])
163 #define MENU_SCREEN_INFO_SPACE_TOP      (menu.top_spacing_info[info_mode])
164 #define MENU_SCREEN_INFO_SPACE_BOTTOM   (menu.bottom_spacing_info[info_mode])
165 #define MENU_SCREEN_INFO_YSTART1        MENU_SCREEN_INFO_SPACE_TOP
166 #define MENU_SCREEN_INFO_YSTART2        (MENU_SCREEN_INFO_YSTART1 +            \
167                                          getMenuTextStep(MENU_INFO_SPACE_HEAD, \
168                                                          MENU_INFO_FONT_TITLE))
169 #define MENU_SCREEN_INFO_YSTEP          (TILEY + 4)
170 #define MENU_SCREEN_INFO_YBOTTOM        (SYSIZE - MENU_SCREEN_INFO_SPACE_BOTTOM)
171 #define MENU_SCREEN_INFO_YSIZE          (MENU_SCREEN_INFO_YBOTTOM -     \
172                                          MENU_SCREEN_INFO_YSTART2 -     \
173                                          TILEY / 2)
174 #define MAX_INFO_ELEMENTS_ON_SCREEN     128
175 #define STD_INFO_ELEMENTS_ON_SCREEN     (MENU_SCREEN_INFO_YSIZE /       \
176                                          MENU_SCREEN_INFO_YSTEP)
177 #define NUM_INFO_ELEMENTS_FROM_CONF     \
178   (menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] > 0 ?             \
179    menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] :                 \
180    MAX_MENU_ENTRIES_ON_SCREEN)
181 #define NUM_INFO_ELEMENTS_ON_SCREEN     MIN(MIN(STD_INFO_ELEMENTS_ON_SCREEN, \
182                                                 MAX_INFO_ELEMENTS_ON_SCREEN), \
183                                             NUM_INFO_ELEMENTS_FROM_CONF)
184 #define MAX_MENU_ENTRIES_ON_SCREEN      (SCR_FIELDY - MENU_SCREEN_START_YPOS)
185 #define MAX_MENU_TEXT_LENGTH_BIG        13
186 #define MAX_MENU_TEXT_LENGTH_MEDIUM     (MAX_MENU_TEXT_LENGTH_BIG * 2)
187
188 // screen gadget identifiers
189 #define SCREEN_CTRL_ID_PREV_LEVEL       0
190 #define SCREEN_CTRL_ID_NEXT_LEVEL       1
191 #define SCREEN_CTRL_ID_PREV_LEVEL2      2
192 #define SCREEN_CTRL_ID_NEXT_LEVEL2      3
193 #define SCREEN_CTRL_ID_PREV_SCORE       4
194 #define SCREEN_CTRL_ID_NEXT_SCORE       5
195 #define SCREEN_CTRL_ID_PLAY_TAPE        6
196 #define SCREEN_CTRL_ID_FIRST_LEVEL      7
197 #define SCREEN_CTRL_ID_LAST_LEVEL       8
198 #define SCREEN_CTRL_ID_LEVEL_NUMBER     9
199 #define SCREEN_CTRL_ID_PREV_PLAYER      10
200 #define SCREEN_CTRL_ID_NEXT_PLAYER      11
201 #define SCREEN_CTRL_ID_INSERT_SOLUTION  12
202 #define SCREEN_CTRL_ID_PLAY_SOLUTION    13
203 #define SCREEN_CTRL_ID_SWITCH_ECS_AGA   14
204 #define SCREEN_CTRL_ID_TOUCH_PREV_PAGE  15
205 #define SCREEN_CTRL_ID_TOUCH_NEXT_PAGE  16
206 #define SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 17
207 #define SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 18
208
209 #define NUM_SCREEN_MENUBUTTONS          19
210
211 #define SCREEN_CTRL_ID_SCROLL_UP        19
212 #define SCREEN_CTRL_ID_SCROLL_DOWN      20
213 #define SCREEN_CTRL_ID_SCROLL_VERTICAL  21
214 #define SCREEN_CTRL_ID_NETWORK_SERVER   22
215
216 #define NUM_SCREEN_GADGETS              23
217
218 #define NUM_SCREEN_SCROLLBUTTONS        2
219 #define NUM_SCREEN_SCROLLBARS           1
220 #define NUM_SCREEN_TEXTINPUT            1
221
222 #define SCREEN_MASK_MAIN                (1 << 0)
223 #define SCREEN_MASK_MAIN_HAS_SOLUTION   (1 << 1)
224 #define SCREEN_MASK_INPUT               (1 << 2)
225 #define SCREEN_MASK_TOUCH               (1 << 3)
226 #define SCREEN_MASK_TOUCH2              (1 << 4)
227 #define SCREEN_MASK_SCORES              (1 << 5)
228 #define SCREEN_MASK_SCORES_INFO         (1 << 6)
229
230 // graphic position and size values for buttons and scrollbars
231 #define SC_MENUBUTTON_XSIZE             TILEX
232 #define SC_MENUBUTTON_YSIZE             TILEY
233
234 #define SC_SCROLLBUTTON_XSIZE           TILEX
235 #define SC_SCROLLBUTTON_YSIZE           TILEY
236
237 #define SC_SCROLLBAR_XPOS               (SXSIZE - SC_SCROLLBUTTON_XSIZE)
238
239 #define SC_SCROLL_VERTICAL_XSIZE        SC_SCROLLBUTTON_XSIZE
240 #define SC_SCROLL_VERTICAL_YSIZE        ((MAX_MENU_ENTRIES_ON_SCREEN - 2) * \
241                                          SC_SCROLLBUTTON_YSIZE)
242
243 #define SC_SCROLL_UP_XPOS               SC_SCROLLBAR_XPOS
244 #define SC_SCROLL_UP_YPOS               (2 * SC_SCROLLBUTTON_YSIZE)
245
246 #define SC_SCROLL_VERTICAL_XPOS         SC_SCROLLBAR_XPOS
247 #define SC_SCROLL_VERTICAL_YPOS         (SC_SCROLL_UP_YPOS + \
248                                          SC_SCROLLBUTTON_YSIZE)
249
250 #define SC_SCROLL_DOWN_XPOS             SC_SCROLLBAR_XPOS
251 #define SC_SCROLL_DOWN_YPOS             (SC_SCROLL_VERTICAL_YPOS + \
252                                          SC_SCROLL_VERTICAL_YSIZE)
253
254 #define SC_BORDER_SIZE                  14
255
256
257 // forward declarations of internal functions
258 static void HandleScreenGadgets(struct GadgetInfo *);
259 static void HandleSetupScreen_Generic(int, int, int, int, int);
260 static void HandleSetupScreen_Input(int, int, int, int, int);
261 static void CustomizeKeyboard(int);
262 static void ConfigureJoystick(int);
263 static void ConfigureVirtualButtons(void);
264 static void execSetupGame(void);
265 static void execSetupEngines(void);
266 static void execSetupGraphics(void);
267 static void execSetupSound(void);
268 static void execSetupTouch(void);
269 static void execSetupArtwork(void);
270 static void HandleChooseTree(int, int, int, int, int, TreeInfo **);
271
272 static void DrawChoosePlayerName(void);
273 static void DrawChooseLevelSet(void);
274 static void DrawChooseLevelNr(void);
275 static void DrawScoreInfo(int);
276 static void DrawScoreInfo_Content(int);
277 static void DrawInfoScreen(void);
278 static void DrawSetupScreen(void);
279 static void DrawTypeName(void);
280
281 static void DrawInfoScreen_NotAvailable(char *, char *);
282 static void DrawInfoScreen_HelpAnim(int, int, boolean);
283 static void DrawInfoScreen_HelpText(int, int, int, int);
284 static void HandleInfoScreen_Main(int, int, int, int, int);
285 static void HandleInfoScreen_TitleScreen(int, int, int);
286 static void HandleInfoScreen_Elements(int, int, int);
287 static void HandleInfoScreen_Music(int, int, int);
288 static void HandleInfoScreen_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 When Playing:" },
7210   { TYPE_SWITCH,        &setup.autorecord_after_replay, "Auto-Record After Replay:" },
7211   { TYPE_SWITCH,        &setup.auto_pause_on_start, "Start Game in Pause Mode:" },
7212   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
7213   { TYPE_STRING,        &game_speed_text,       ""                      },
7214   { TYPE_SWITCH,        &setup.game_speed_extended, "Game Speed Extended List:" },
7215 #if 1
7216   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7217   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7218 #endif
7219   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
7220   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
7221   { TYPE_SWITCH,        &setup.show_load_save_buttons,"Show Load/Save Buttons:" },
7222   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,"Show Undo/Redo Buttons:" },
7223   { TYPE_EMPTY,         NULL,                   ""                      },
7224   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7225
7226   { 0,                  NULL,                   NULL                    }
7227 };
7228
7229 static struct TokenInfo setup_info_engines[] =
7230 {
7231   { TYPE_HEADLINE,      NULL,                   "Emerald Mine"          },
7232   { TYPE_SWITCH,        &setup.forced_scroll_delay, "Scroll Delay:"     },
7233   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics, "Amiga Graphics Chipset:" },
7234   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,"Low-Pass Filter Sounds:" },
7235   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:" },
7236   { TYPE_EMPTY,         NULL,                   ""                      },
7237   { TYPE_HEADLINE,      NULL,                   "Supaplex"              },
7238   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:" },
7239   { TYPE_EMPTY,         NULL,                   ""                      },
7240   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7241
7242   { 0,                  NULL,                   NULL                    }
7243 };
7244
7245 static struct TokenInfo setup_info_editor[] =
7246 {
7247 #if 0
7248   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
7249   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
7250   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
7251   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
7252   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
7253   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
7254   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
7255   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
7256   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
7257   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
7258 #endif
7259   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
7260   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
7261 #if 0
7262   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
7263 #endif
7264   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
7265   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
7266   { TYPE_EMPTY,         NULL,                   ""                      },
7267 #if 0
7268   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
7269   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
7270   { TYPE_EMPTY,         NULL,                   ""                      },
7271 #endif
7272   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
7273   { TYPE_EMPTY,         NULL,                   ""                      },
7274   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:" },
7275   { TYPE_EMPTY,         NULL,                   ""                      },
7276   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7277
7278   { 0,                  NULL,                   NULL                    }
7279 };
7280
7281 static struct TokenInfo setup_info_graphics[] =
7282 {
7283 #if !defined(PLATFORM_ANDROID) && !defined(PLATFORM_EMSCRIPTEN)
7284   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
7285   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
7286   { TYPE_STRING,        &window_size_text,      ""                      },
7287   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
7288   { TYPE_STRING,        &scaling_type_text,     ""                      },
7289   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
7290   { TYPE_STRING,        &rendering_mode_text,   ""                      },
7291 #endif
7292 #if 0
7293   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7294   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7295 #endif
7296 #if !defined(PLATFORM_EMSCRIPTEN)
7297   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode, "Vertical Sync (VSync):" },
7298   { TYPE_STRING,        &vsync_mode_text,       ""                      },
7299 #endif
7300   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
7301   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
7302   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
7303   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
7304   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
7305   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
7306   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,  debug_xsn_mode          },
7307   { TYPE_EMPTY,         NULL,                   ""                      },
7308   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7309
7310   { 0,                  NULL,                   NULL                    }
7311 };
7312
7313 static struct TokenInfo setup_info_sound[] =
7314 {
7315   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
7316   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
7317   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
7318   { TYPE_EMPTY,         NULL,                   ""                      },
7319   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
7320   { TYPE_STRING,        &volume_simple_text,    ""                      },
7321   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
7322   { TYPE_STRING,        &volume_loops_text,     ""                      },
7323   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
7324   { TYPE_STRING,        &volume_music_text,     ""                      },
7325   { TYPE_EMPTY,         NULL,                   ""                      },
7326   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7327
7328   { 0,                  NULL,                   NULL                    }
7329 };
7330
7331 static struct TokenInfo setup_info_artwork[] =
7332 {
7333   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
7334   { TYPE_STRING,        &graphics_set_name,     ""                      },
7335   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
7336   { TYPE_STRING,        &sounds_set_name,       ""                      },
7337   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
7338   { TYPE_STRING,        &music_set_name,        ""                      },
7339   { TYPE_EMPTY,         NULL,                   ""                      },
7340   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
7341   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
7342   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
7343   { TYPE_EMPTY,         NULL,                   ""                      },
7344   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7345
7346   { 0,                  NULL,                   NULL                    }
7347 };
7348
7349 static struct TokenInfo setup_info_input[] =
7350 {
7351   { TYPE_SWITCH,        NULL,                   "Player:"               },
7352   { TYPE_SWITCH,        NULL,                   "Device:"               },
7353   { TYPE_SWITCH,        NULL,                   ""                      },
7354   { TYPE_SKIPPABLE,     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_EMPTY,         NULL,                   ""                      },
7363   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7364   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7365
7366   { 0,                  NULL,                   NULL                    }
7367 };
7368
7369 static struct TokenInfo setup_info_touch[] =
7370 {
7371   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7372   { TYPE_STRING,        &touch_controls_text,   ""                      },
7373   { TYPE_EMPTY,         NULL,                   ""                      },
7374   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7375
7376   { 0,                  NULL,                   NULL                    }
7377 };
7378
7379 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
7380 {
7381   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7382   { TYPE_STRING,        &touch_controls_text,   ""                      },
7383   { TYPE_EMPTY,         NULL,                   ""                      },
7384   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0, "Horizontal Buttons (Landscape):"   },
7385   { TYPE_STRING,        &grid_size_text[0][0],  ""                      },
7386   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0, "Vertical Buttons (Landscape):"     },
7387   { TYPE_STRING,        &grid_size_text[0][1],  ""                      },
7388   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7389   { TYPE_STRING,        &transparency_text,     ""                      },
7390   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7391   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7392   { TYPE_EMPTY,         NULL,                   ""                      },
7393   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7394   { TYPE_EMPTY,         NULL,                   ""                      },
7395   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7396
7397   { 0,                  NULL,                   NULL                    }
7398 };
7399
7400 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
7401 {
7402   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7403   { TYPE_STRING,        &touch_controls_text,   ""                      },
7404   { TYPE_EMPTY,         NULL,                   ""                      },
7405   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1, "Horizontal Buttons (Portrait):"    },
7406   { TYPE_STRING,        &grid_size_text[1][0],  ""                      },
7407   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1, "Vertical Buttons (Portrait):"      },
7408   { TYPE_STRING,        &grid_size_text[1][1],  ""                      },
7409   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7410   { TYPE_STRING,        &transparency_text,     ""                      },
7411   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7412   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7413   { TYPE_EMPTY,         NULL,                   ""                      },
7414   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7415   { TYPE_EMPTY,         NULL,                   ""                      },
7416   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7417
7418   { 0,                  NULL,                   NULL                    }
7419 };
7420
7421 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
7422 {
7423   setup_info_touch_virtual_buttons_0,
7424   setup_info_touch_virtual_buttons_1
7425 };
7426
7427 static struct TokenInfo setup_info_touch_wipe_gestures[] =
7428 {
7429   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7430   { TYPE_STRING,        &touch_controls_text,   ""                      },
7431   { TYPE_EMPTY,         NULL,                   ""                      },
7432   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
7433   { TYPE_STRING,        &move_distance_text,    ""                      },
7434   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
7435   { TYPE_STRING,        &drop_distance_text,    ""                      },
7436   { TYPE_EMPTY,         NULL,                   ""                      },
7437   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7438
7439   { 0,                  NULL,                   NULL                    }
7440 };
7441
7442 static struct TokenInfo setup_info_shortcuts[] =
7443 {
7444   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
7445   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
7446   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
7447   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
7448   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
7449   { TYPE_EMPTY,         NULL,                   ""                      },
7450   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7451
7452   { 0,                  NULL,                   NULL                    }
7453 };
7454
7455 static struct TokenInfo setup_info_shortcuts_1[] =
7456 {
7457   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
7458   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
7459   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
7460   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
7461   { TYPE_KEYTEXT,       NULL,           "Restart Game:",                },
7462   { TYPE_KEY,           &setup.shortcut.restart_game, ""                },
7463   { TYPE_KEYTEXT,       NULL,           "Replay & Pause Before End:",   },
7464   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""            },
7465   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
7466   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
7467   { TYPE_EMPTY,         NULL,                   ""                      },
7468   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
7469   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
7470   { TYPE_EMPTY,         NULL,                   ""                      },
7471   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7472
7473   { 0,                  NULL,                   NULL                    }
7474 };
7475
7476 static struct TokenInfo setup_info_shortcuts_2[] =
7477 {
7478   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
7479   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
7480   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
7481   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
7482   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
7483   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
7484   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
7485   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
7486   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
7487   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
7488   { TYPE_EMPTY,         NULL,                   ""                      },
7489   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7490
7491   { 0,                  NULL,                   NULL                    }
7492 };
7493
7494 static struct TokenInfo setup_info_shortcuts_3[] =
7495 {
7496   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
7497   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
7498   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
7499   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
7500   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
7501   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
7502   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
7503   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
7504   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
7505   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
7506   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
7507   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
7508   { TYPE_EMPTY,         NULL,                   ""                      },
7509   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7510
7511   { 0,                  NULL,                   NULL                    }
7512 };
7513
7514 static struct TokenInfo setup_info_shortcuts_4[] =
7515 {
7516   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
7517   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
7518   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
7519   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
7520   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
7521   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
7522   { TYPE_EMPTY,         NULL,                   ""                      },
7523   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7524
7525   { 0,                  NULL,                   NULL                    }
7526 };
7527
7528 static struct TokenInfo setup_info_shortcuts_5[] =
7529 {
7530   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
7531   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
7532   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
7533   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
7534   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
7535   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
7536   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
7537   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
7538   { TYPE_EMPTY,         NULL,                   ""                      },
7539   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7540
7541   { 0,                  NULL,                   NULL                    }
7542 };
7543
7544 static Key getSetupKey(void)
7545 {
7546   Key key = KSYM_UNDEFINED;
7547   boolean got_key_event = FALSE;
7548
7549   while (!got_key_event)
7550   {
7551     Event event;
7552
7553     if (NextValidEvent(&event))
7554     {
7555       switch (event.type)
7556       {
7557         case EVENT_KEYPRESS:
7558           {
7559             key = GetEventKey((KeyEvent *)&event);
7560
7561             // press 'Escape' or 'Enter' to keep the existing key binding
7562             if (key == KSYM_Escape || key == KSYM_Return)
7563               key = KSYM_UNDEFINED;     // keep old value
7564
7565             got_key_event = TRUE;
7566           }
7567           break;
7568
7569         case EVENT_KEYRELEASE:
7570           key_joystick_mapping = 0;
7571           break;
7572
7573         default:
7574           HandleOtherEvents(&event);
7575           break;
7576       }
7577     }
7578
7579     BackToFront();
7580   }
7581
7582   return key;
7583 }
7584
7585 static int getSetupValueFont(int type, void *value)
7586 {
7587   if (type & TYPE_GHOSTED)
7588     return FONT_OPTION_OFF;
7589   else if (type & TYPE_KEY)
7590     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
7591   else if (type & TYPE_STRING)
7592     return FONT_VALUE_2;
7593   else if (type & TYPE_ECS_AGA)
7594     return FONT_VALUE_1;
7595   else if (type & TYPE_BOOLEAN_STYLE)
7596     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
7597   else if (type & TYPE_YES_NO_AUTO)
7598     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
7599             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
7600   else if (type & TYPE_PLAYER)
7601     return FONT_VALUE_1;
7602   else
7603     return FONT_VALUE_1;
7604 }
7605
7606 static int getSetupValueFontNarrow(int type, int font_nr)
7607 {
7608   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
7609           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
7610           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
7611           font_nr);
7612 }
7613
7614 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
7615 {
7616   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7617   struct TokenInfo *si = &setup_info[si_pos];
7618   boolean font_draw_xoffset_modified = FALSE;
7619   boolean scrollbar_needed = (num_setup_info < max_setup_info);
7620   int font_draw_xoffset_old = -1;
7621   int xoffset = (scrollbar_needed ? -1 : 0);
7622   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
7623   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
7624   int xpos = menu_screen_value_xpos;
7625   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
7626   int startx = mSX + xpos * 32;
7627   int starty = mSY + ypos * 32;
7628   int type = si->type;
7629   void *value = si->value;
7630   char *value_string = getSetupValue(type, value);
7631   int font_nr_default = getSetupValueFont(type, value);
7632   int font_width_default = getFontWidth(font_nr_default);
7633   int font_nr = font_nr_default;
7634   int i;
7635
7636   if (value_string == NULL)
7637     return;
7638
7639   if (type & TYPE_KEY)
7640   {
7641     xpos = MENU_SCREEN_START_XPOS;
7642
7643     if (type & TYPE_QUERY)
7644       value_string = "<press key>";
7645   }
7646   else if (type & TYPE_STRING)
7647   {
7648     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
7649
7650     xpos = MENU_SCREEN_START_XPOS;
7651
7652     if (strlen(value_string) > max_value_len)
7653       value_string[max_value_len] = '\0';
7654   }
7655   else if (type & TYPE_YES_NO_AUTO)
7656   {
7657     xpos = menu_screen_value_xpos - 1;
7658   }
7659   else if (type & TYPE_PLAYER)
7660   {
7661     int displayed_player_nr = *(int *)value + 1;
7662
7663     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
7664   }
7665
7666   startx = mSX + xpos * 32;
7667   starty = mSY + ypos * 32;
7668
7669   // special check if right-side setup values moved left due to scrollbar
7670   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
7671   {
7672     int max_menu_text_length = 26;      // maximum text length for classic menu
7673     int font_xoffset = getFontDrawOffsetX(font_nr);
7674     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
7675     int text_font_nr = getMenuTextFont(FONT_MENU_2);
7676     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
7677     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
7678
7679     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
7680     {
7681       // when using narrow font, left-shifting text "auto" not needed
7682       if (type & TYPE_YES_NO_AUTO)
7683         xpos += 1;
7684
7685       xpos += 1;
7686       startx = mSX + xpos * 32;
7687
7688       font_nr = getSetupValueFontNarrow(type, font_nr);
7689     }
7690   }
7691
7692   // downward compatibility correction for Juergen Bonhagen's menu settings
7693   if (setup_mode != SETUP_MODE_INPUT)
7694   {
7695     int max_menu_text_length_big = (menu_screen_value_xpos -
7696                                     MENU_SCREEN_START_XPOS);
7697     int max_menu_text_length_medium = max_menu_text_length_big * 2;
7698     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
7699     int font1_xoffset = getFontDrawOffsetX(font_nr);
7700     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
7701     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
7702     int text_font_nr = getMenuTextFont(FONT_MENU_2);
7703     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
7704     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
7705     boolean correct_font_draw_xoffset = FALSE;
7706
7707     if (xpos == MENU_SCREEN_START_XPOS &&
7708         startx + font1_xoffset < text_startx + text_font_xoffset)
7709       correct_font_draw_xoffset = TRUE;
7710
7711     if (xpos == menu_screen_value_xpos &&
7712         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
7713       correct_font_draw_xoffset = TRUE;
7714
7715     // check if setup value would overlap with setup text when printed
7716     // (this can happen for extreme/wrong values for font draw offset)
7717     if (correct_font_draw_xoffset)
7718     {
7719       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
7720       font_draw_xoffset_modified = TRUE;
7721
7722       if (type & TYPE_KEY)
7723         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
7724       else if (!(type & TYPE_STRING))
7725         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
7726           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
7727     }
7728   }
7729
7730   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
7731     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
7732
7733   DrawText(startx, starty, value_string, font_nr);
7734
7735   if (type & TYPE_PLAYER)
7736   {
7737     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
7738     int player_nr = *(int *)value;
7739     int xoff = font->draw_xoffset + getFontWidth(font_nr);
7740     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
7741     int startx2 = startx + xoff;
7742     int starty2 = starty + yoff;
7743
7744     if (DrawingOnBackground(startx2, starty2))
7745       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
7746
7747     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
7748                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
7749   }
7750
7751   if (font_draw_xoffset_modified)
7752     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
7753 }
7754
7755 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
7756 {
7757   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7758   struct TokenInfo *si = &setup_info[si_pos];
7759
7760   if (si->type & TYPE_BOOLEAN_STYLE)
7761   {
7762     *(boolean *)si->value ^= TRUE;
7763   }
7764   else if (si->type & TYPE_YES_NO_AUTO)
7765   {
7766     *(int *)si->value =
7767       (dx == -1 ?
7768        (*(int *)si->value == AUTO ? TRUE :
7769         *(int *)si->value == TRUE ? FALSE : AUTO) :
7770        (*(int *)si->value == TRUE ? AUTO :
7771         *(int *)si->value == AUTO ? FALSE : TRUE));
7772   }
7773   else if (si->type & TYPE_KEY)
7774   {
7775     Key key;
7776
7777     si->type |= TYPE_QUERY;
7778     drawSetupValue(screen_pos, setup_info_pos_raw);
7779     si->type &= ~TYPE_QUERY;
7780
7781     key = getSetupKey();
7782     if (key != KSYM_UNDEFINED)
7783       *(Key *)si->value = key;
7784   }
7785   else if (si->type & TYPE_PLAYER)
7786   {
7787     int player_nr = *(int *)si->value;
7788
7789     if (dx)
7790       player_nr += dx;
7791     else
7792       player_nr = Request("Choose player", REQ_PLAYER) - 1;
7793
7794     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
7795   }
7796
7797   drawSetupValue(screen_pos, setup_info_pos_raw);
7798
7799   // fullscreen state may have changed at this point
7800   if (si->value == &setup.fullscreen)
7801     ToggleFullscreenIfNeeded();
7802
7803   // network mode may have changed at this point
7804   if (si->value == &setup.network_mode)
7805     ToggleNetworkModeIfNeeded();
7806
7807   // API server mode may have changed at this point
7808   if (si->value == &setup.use_api_server)
7809     ToggleUseApiServerIfNeeded();
7810
7811   // game speed list may have changed at this point
7812   if (si->value == &setup.game_speed_extended)
7813     ToggleGameSpeedsListIfNeeded();
7814 }
7815
7816 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
7817 {
7818   static struct TokenInfo *setup_info_final = NULL;
7819   int list_size = 0;
7820   int list_pos = 0;
7821   int i;
7822
7823   // determine maximum list size of target list
7824   while (setup_info_orig[list_size++].type != 0);
7825
7826   // free, allocate and clear memory for target list
7827   checked_free(setup_info_final);
7828   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
7829
7830   // copy setup info list without setup entries marked as hidden
7831   for (i = 0; setup_info_orig[i].type != 0; i++)
7832   {
7833     // skip setup entries configured to be hidden
7834     if (hideSetupEntry(setup_info_orig[i].value))
7835       continue;
7836
7837     // skip skippable setup entries if screen is lower than usual
7838     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
7839         setup_info_orig[i].type == TYPE_SKIPPABLE)
7840       continue;
7841
7842     setup_info_final[list_pos++] = setup_info_orig[i];
7843   }
7844
7845   return setup_info_final;
7846 }
7847
7848 static void DrawSetupScreen_Generic(void)
7849 {
7850   int fade_mask = REDRAW_FIELD;
7851   boolean redraw_all = FALSE;
7852   char *title_string = NULL;
7853   int i;
7854
7855   if (CheckFadeAll())
7856     fade_mask = REDRAW_ALL;
7857
7858   UnmapAllGadgets();
7859   FadeMenuSoundsAndMusic();
7860
7861   FreeScreenGadgets();
7862   CreateScreenGadgets();
7863
7864   if (redraw_mask & REDRAW_ALL)
7865     redraw_all = TRUE;
7866
7867   FadeOut(fade_mask);
7868
7869   // needed if different viewport properties defined for setup screen
7870   ChangeViewportPropertiesIfNeeded();
7871
7872   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
7873
7874   ClearField();
7875
7876   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
7877
7878   if (setup_mode == SETUP_MODE_MAIN)
7879   {
7880     setup_info = setup_info_main;
7881     title_string = STR_SETUP_MAIN;
7882   }
7883   else if (setup_mode == SETUP_MODE_GAME)
7884   {
7885     setup_info = setup_info_game;
7886     title_string = STR_SETUP_GAME;
7887   }
7888   else if (setup_mode == SETUP_MODE_ENGINES)
7889   {
7890     setup_info = setup_info_engines;
7891     title_string = STR_SETUP_ENGINES;
7892   }
7893   else if (setup_mode == SETUP_MODE_EDITOR)
7894   {
7895     setup_info = setup_info_editor;
7896     title_string = STR_SETUP_EDITOR;
7897   }
7898   else if (setup_mode == SETUP_MODE_GRAPHICS)
7899   {
7900     setup_info = setup_info_graphics;
7901     title_string = STR_SETUP_GRAPHICS;
7902   }
7903   else if (setup_mode == SETUP_MODE_SOUND)
7904   {
7905     setup_info = setup_info_sound;
7906     title_string = STR_SETUP_SOUND;
7907   }
7908   else if (setup_mode == SETUP_MODE_ARTWORK)
7909   {
7910     setup_info = setup_info_artwork;
7911     title_string = STR_SETUP_ARTWORK;
7912   }
7913   else if (setup_mode == SETUP_MODE_TOUCH)
7914   {
7915     setup_info = setup_info_touch;
7916     title_string = STR_SETUP_TOUCH;
7917
7918     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
7919       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
7920     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
7921       setup_info = setup_info_touch_wipe_gestures;
7922   }
7923   else if (setup_mode == SETUP_MODE_SHORTCUTS)
7924   {
7925     setup_info = setup_info_shortcuts;
7926     title_string = STR_SETUP_SHORTCUTS;
7927   }
7928   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
7929   {
7930     setup_info = setup_info_shortcuts_1;
7931     title_string = STR_SETUP_SHORTCUTS;
7932   }
7933   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
7934   {
7935     setup_info = setup_info_shortcuts_2;
7936     title_string = STR_SETUP_SHORTCUTS;
7937   }
7938   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
7939   {
7940     setup_info = setup_info_shortcuts_3;
7941     title_string = STR_SETUP_SHORTCUTS;
7942   }
7943   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
7944   {
7945     setup_info = setup_info_shortcuts_4;
7946     title_string = STR_SETUP_SHORTCUTS;
7947   }
7948   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
7949   {
7950     setup_info = setup_info_shortcuts_5;
7951     title_string = STR_SETUP_SHORTCUTS;
7952   }
7953
7954   // use modified setup info without setup entries marked as hidden
7955   setup_info = getSetupInfoFinal(setup_info);
7956
7957   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
7958
7959   // determine maximal number of setup entries that can be displayed on screen
7960   num_setup_info = 0;
7961   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
7962     num_setup_info++;
7963
7964   // determine maximal number of setup entries available for this setup screen
7965   max_setup_info = 0;
7966   for (i = 0; setup_info[i].type != 0; i++)
7967     max_setup_info++;
7968
7969   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
7970
7971   MapScreenGadgets(max_setup_info);
7972
7973   if (redraw_all)
7974     redraw_mask = fade_mask = REDRAW_ALL;
7975
7976   DrawMaskedBorder(fade_mask);
7977
7978   FadeIn(fade_mask);
7979 }
7980
7981 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
7982 {
7983   menu_info = setup_info;
7984
7985   HandleMenuScreen(mx, my, dx, dy, button,
7986                    setup_mode, num_setup_info, max_setup_info);
7987 }
7988
7989 static void DrawSetupScreen_Input(void)
7990 {
7991   int i;
7992
7993   FadeOut(REDRAW_FIELD);
7994
7995   ClearField();
7996
7997   setup_info = getSetupInfoFinal(setup_info_input);
7998
7999   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
8000
8001   for (i = 0; setup_info[i].type != 0; i++)
8002   {
8003     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
8004       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
8005     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
8006       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
8007     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
8008       initCursor(i, IMG_MENU_BUTTON);
8009
8010     DrawCursorAndText_Setup(i, -1, FALSE);
8011   }
8012
8013   // create gadgets for setup input menu screen
8014   FreeScreenGadgets();
8015   CreateScreenGadgets();
8016
8017   // map gadgets for setup input menu screen
8018   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
8019
8020   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
8021
8022   FadeIn(REDRAW_FIELD);
8023 }
8024
8025 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8026 {
8027   if (device_name == NULL)
8028     return;
8029
8030   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8031     device_nr = 0;
8032
8033   if (strlen(device_name) > 1)
8034   {
8035     char c1 = device_name[strlen(device_name) - 1];
8036     char c2 = device_name[strlen(device_name) - 2];
8037
8038     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8039       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8040   }
8041   else
8042     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8043             strlen(device_name));
8044 }
8045
8046 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8047 {
8048   int i;
8049   static struct SetupKeyboardInfo custom_key;
8050   static struct
8051   {
8052     Key *key;
8053     char *text;
8054   } custom[] =
8055   {
8056     { &custom_key.left,  "Axis/Pad Left"  },
8057     { &custom_key.right, "Axis/Pad Right" },
8058     { &custom_key.up,    "Axis/Pad Up"    },
8059     { &custom_key.down,  "Axis/Pad Down"  },
8060     { &custom_key.snap,  "Button 1/A/X"   },
8061     { &custom_key.drop,  "Button 2/B/Y"   }
8062   };
8063   static char *joystick_name[MAX_PLAYERS] =
8064   {
8065     "Joystick1",
8066     "Joystick2",
8067     "Joystick3",
8068     "Joystick4"
8069   };
8070   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8071   int font_nr_info = FONT_MENU_1;
8072   int font_nr_name = FONT_VALUE_OLD;
8073   int font_nr_on   = FONT_VALUE_1;
8074   int font_nr_off  = FONT_VALUE_OLD;
8075   int pos = 4;
8076
8077   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8078   {
8079     font_nr_info = FONT_MENU_2;
8080     font_nr_on   = FONT_VALUE_NARROW;
8081     font_nr_off  = FONT_VALUE_OLD_NARROW;
8082   }
8083
8084   custom_key = setup.input[player_nr].key;
8085
8086   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8087            FONT_INPUT_1_ACTIVE);
8088
8089   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8090                              TILEX, TILEY);
8091   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8092                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8093
8094   if (setup.input[player_nr].use_joystick)
8095   {
8096     char *device_name = setup.input[player_nr].joy.device_name;
8097     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8098     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8099     char *text = joystick_name[joystick_nr];
8100     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8101
8102     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8103     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8104   }
8105   else
8106   {
8107     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8108     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8109   }
8110
8111   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8112     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8113   else
8114     pos = 3;
8115
8116   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8117   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8118   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8119   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8120
8121   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8122   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8123   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8124   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8125   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8126   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8127
8128   for (i = 0; i < 6; i++)
8129   {
8130     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8131
8132     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8133              "              ", font_nr_on);
8134     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8135              (setup.input[player_nr].use_joystick ?
8136               custom[i].text :
8137               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8138   }
8139 }
8140
8141 static int input_player_nr = 0;
8142
8143 static void HandleSetupScreen_Input_Player(int step, int direction)
8144 {
8145   int old_player_nr = input_player_nr;
8146   int new_player_nr;
8147
8148   new_player_nr = old_player_nr + step * direction;
8149   if (new_player_nr < 0)
8150     new_player_nr = 0;
8151   if (new_player_nr > MAX_PLAYERS - 1)
8152     new_player_nr = MAX_PLAYERS - 1;
8153
8154   if (new_player_nr != old_player_nr)
8155   {
8156     input_player_nr = new_player_nr;
8157
8158     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8159   }
8160 }
8161
8162 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8163 {
8164   static int choice = 0;
8165   int x = 0;
8166   int y = choice;
8167   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8168   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8169   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8170   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8171
8172   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8173   {
8174     int i;
8175
8176     for (i = 0; setup_info_input[i].type != 0; i++)
8177     {
8178       // adjust menu structure according to skipped setup entries
8179       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8180       {
8181         pos_empty2--;
8182         pos_end--;
8183       }
8184     }
8185   }
8186
8187   if (button == MB_MENU_INITIALIZE)
8188   {
8189     // input setup menu may have changed size due to graphics configuration
8190     if (choice >= pos_empty1)
8191       choice = pos_end;
8192
8193     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8194
8195     DrawCursorAndText_Setup(choice, -1, TRUE);
8196
8197     return;
8198   }
8199   else if (button == MB_MENU_LEAVE)
8200   {
8201     setup_mode = SETUP_MODE_MAIN;
8202     DrawSetupScreen();
8203     InitJoysticks();
8204
8205     return;
8206   }
8207
8208   if (mx || my)         // mouse input
8209   {
8210     x = (mx - mSX) / 32;
8211     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8212   }
8213   else if (dx || dy)    // keyboard input
8214   {
8215     if (dx && choice == 0)
8216       x = (dx < 0 ? 10 : 12);
8217     else if ((dx && choice == 1) ||
8218              (dx == -1 && choice == pos_end))
8219       button = MB_MENU_CHOICE;
8220     else if (dy)
8221       y = choice + dy;
8222
8223     if (y >= pos_empty1 && y <= pos_empty2)
8224       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
8225   }
8226
8227   if (y == 0 && dx != 0 && button)
8228   {
8229     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
8230   }
8231   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
8232            y >= pos_start && y <= pos_end &&
8233            !(y >= pos_empty1 && y <= pos_empty2))
8234   {
8235     if (button)
8236     {
8237       if (y != choice)
8238       {
8239         DrawCursorAndText_Setup(choice, -1, FALSE);
8240         DrawCursorAndText_Setup(y, -1, TRUE);
8241
8242         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
8243
8244         choice = y;
8245       }
8246     }
8247     else
8248     {
8249       if (y == 1)
8250       {
8251         char *device_name = setup.input[input_player_nr].joy.device_name;
8252
8253         if (!setup.input[input_player_nr].use_joystick)
8254         {
8255           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
8256
8257           setJoystickDeviceToNr(device_name, new_device_nr);
8258           setup.input[input_player_nr].use_joystick = TRUE;
8259         }
8260         else
8261         {
8262           int device_nr = getJoystickNrFromDeviceName(device_name);
8263           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
8264
8265           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
8266             setup.input[input_player_nr].use_joystick = FALSE;
8267           else
8268             setJoystickDeviceToNr(device_name, new_device_nr);
8269         }
8270
8271         drawPlayerSetupInputInfo(input_player_nr, FALSE);
8272       }
8273       else if (y == 2)
8274       {
8275         if (setup.input[input_player_nr].use_joystick)
8276           ConfigureJoystick(input_player_nr);
8277         else
8278           CustomizeKeyboard(input_player_nr);
8279       }
8280       else if (y == pos_end)
8281       {
8282         InitJoysticks();
8283
8284         FadeSetLeaveMenu();
8285
8286         setup_mode = SETUP_MODE_MAIN;
8287         DrawSetupScreen();
8288       }
8289     }
8290   }
8291 }
8292
8293 static boolean CustomizeKeyboardMain(int player_nr)
8294 {
8295   int i;
8296   int step_nr;
8297   boolean finished = FALSE;
8298   static struct SetupKeyboardInfo custom_key;
8299   static struct
8300   {
8301     Key *key;
8302     char *text;
8303   } customize_step[] =
8304   {
8305     { &custom_key.left,  "Move Left"    },
8306     { &custom_key.right, "Move Right"   },
8307     { &custom_key.up,    "Move Up"      },
8308     { &custom_key.down,  "Move Down"    },
8309     { &custom_key.snap,  "Snap Field"   },
8310     { &custom_key.drop,  "Drop Element" }
8311   };
8312   int font_nr_old = FONT_VALUE_OLD;
8313   int font_nr_new = FONT_VALUE_1;
8314   boolean success = FALSE;
8315
8316   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8317   {
8318     font_nr_old = FONT_VALUE_OLD_NARROW;
8319     font_nr_new = FONT_VALUE_NARROW;
8320   }
8321
8322   // read existing key bindings from player setup
8323   custom_key = setup.input[player_nr].key;
8324
8325   FadeSetEnterMenu();
8326   FadeOut(REDRAW_FIELD);
8327
8328   ClearField();
8329
8330   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
8331
8332   step_nr = 0;
8333   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8334            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8335   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8336            "Key:", FONT_INPUT_1_ACTIVE);
8337   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8338            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
8339
8340   FadeIn(REDRAW_FIELD);
8341
8342   while (!finished)
8343   {
8344     Event event;
8345     DelayCounter event_frame_delay = { GAME_FRAME_DELAY };
8346
8347     // reset frame delay counter directly after updating screen
8348     ResetDelayCounter(&event_frame_delay);
8349
8350     while (NextValidEvent(&event))
8351     {
8352       switch (event.type)
8353       {
8354         case EVENT_KEYPRESS:
8355           {
8356             Key key = GetEventKey((KeyEvent *)&event);
8357
8358             // press 'Escape' to abort and keep the old key bindings
8359             if (key == KSYM_Escape)
8360             {
8361               FadeSkipNextFadeIn();
8362
8363               finished = TRUE;
8364
8365               break;
8366             }
8367
8368             // press 'Enter' to keep the existing key binding
8369             if (key == KSYM_Return)
8370               key = *customize_step[step_nr].key;
8371
8372             // check if key already used
8373             for (i = 0; i < step_nr; i++)
8374               if (*customize_step[i].key == key)
8375                 break;
8376             if (i < step_nr)
8377               break;
8378
8379             // got new key binding
8380             *customize_step[step_nr].key = key;
8381             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8382                      "             ", font_nr_new);
8383             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8384                      getKeyNameFromKey(key), font_nr_new);
8385             step_nr++;
8386
8387             // un-highlight last query
8388             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
8389                      customize_step[step_nr - 1].text, FONT_MENU_1);
8390             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
8391                      "Key:", FONT_MENU_1);
8392
8393             // all keys configured
8394             if (step_nr == 6)
8395             {
8396               finished = TRUE;
8397               success = TRUE;
8398
8399               break;
8400             }
8401
8402             // query next key binding
8403             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8404                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8405             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8406                      "Key:", FONT_INPUT_1_ACTIVE);
8407             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8408                      getKeyNameFromKey(*customize_step[step_nr].key),
8409                      font_nr_old);
8410           }
8411           break;
8412
8413         case EVENT_KEYRELEASE:
8414           key_joystick_mapping = 0;
8415           break;
8416
8417         default:
8418           HandleOtherEvents(&event);
8419           break;
8420       }
8421
8422       // do not handle events for longer than standard frame delay period
8423       if (DelayReached(&event_frame_delay))
8424         break;
8425     }
8426
8427     BackToFront();
8428   }
8429
8430   // write new key bindings back to player setup, if successfully finished
8431   if (success)
8432     setup.input[player_nr].key = custom_key;
8433
8434   return success;
8435 }
8436
8437 void CustomizeKeyboard(int player_nr)
8438 {
8439   boolean success = CustomizeKeyboardMain(player_nr);
8440
8441   if (success)
8442   {
8443     int font_nr = FONT_TITLE_1;
8444     int font_height = getFontHeight(font_nr);
8445     int ypos1 = SYSIZE / 2 - font_height * 2;
8446     int ypos2 = SYSIZE / 2 - font_height * 1;
8447     DelayCounter wait_frame_delay = { 2000 };
8448
8449     ResetDelayCounter(&wait_frame_delay);
8450
8451     ClearField();
8452
8453     DrawTextSCentered(ypos1, font_nr, "Keyboard");
8454     DrawTextSCentered(ypos2, font_nr, "configured!");
8455
8456     while (!DelayReached(&wait_frame_delay))
8457       BackToFront();
8458
8459     ClearEventQueue();
8460   }
8461
8462   DrawSetupScreen_Input();
8463 }
8464
8465 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
8466
8467 #define MARKER_BUTTON           1
8468 #define MARKER_AXIS_X           2
8469 #define MARKER_AXIS_Y           3
8470
8471 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
8472 {
8473   static boolean bitmaps_initialized = FALSE;
8474   boolean screen_initialized = FALSE;
8475   static Bitmap *controller, *button, *axis_x, *axis_y;
8476   char *name;
8477   boolean success = TRUE;
8478   boolean done = FALSE, next = FALSE;
8479   Event event;
8480   int alpha = 200, alpha_step = -1;
8481   int alpha_ticks = 0;
8482   char mapping[4096], temp[256];
8483   int font_name = MENU_SETUP_FONT_TITLE;
8484   int font_info = MENU_SETUP_FONT_TEXT;
8485   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
8486   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
8487   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
8488   int ystep_name = getMenuTextStep(spacing_name, font_name);
8489   int ystep_line = getMenuTextStep(spacing_line, font_info);
8490   int ystep_para = getMenuTextStep(spacing_para, font_info);
8491   int i, j;
8492
8493   struct
8494   {
8495     int x, y;
8496     int marker;
8497     char *field;
8498     int axis, button, hat, hat_value;
8499     char mapping[4096];
8500   }
8501   *step, *prev_step, steps[] =
8502   {
8503     { 356, 155, MARKER_BUTTON, "a",             },
8504     { 396, 122, MARKER_BUTTON, "b",             },
8505     { 320, 125, MARKER_BUTTON, "x",             },
8506     { 358,  95, MARKER_BUTTON, "y",             },
8507     { 162, 125, MARKER_BUTTON, "back",          },
8508     { 216, 125, MARKER_BUTTON, "guide",         },
8509     { 271, 125, MARKER_BUTTON, "start",         },
8510     { 110, 200, MARKER_BUTTON, "dpleft",        },
8511     { 146, 228, MARKER_BUTTON, "dpdown",        },
8512     { 178, 200, MARKER_BUTTON, "dpright",       },
8513     { 146, 172, MARKER_BUTTON, "dpup",          },
8514     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
8515     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
8516     { 382,  40, MARKER_BUTTON, "rightshoulder", },
8517     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
8518     {  73, 141, MARKER_BUTTON, "leftstick",     },
8519     { 282, 210, MARKER_BUTTON, "rightstick",    },
8520     {  73, 141, MARKER_AXIS_X, "leftx",         },
8521     {  73, 141, MARKER_AXIS_Y, "lefty",         },
8522     { 282, 210, MARKER_AXIS_X, "rightx",        },
8523     { 282, 210, MARKER_AXIS_Y, "righty",        },
8524   };
8525
8526   if (!bitmaps_initialized)
8527   {
8528     controller = LoadCustomImage("joystick/controller.png");
8529     button     = LoadCustomImage("joystick/button.png");
8530     axis_x     = LoadCustomImage("joystick/axis_x.png");
8531     axis_y     = LoadCustomImage("joystick/axis_y.png");
8532
8533     bitmaps_initialized = TRUE;
8534   }
8535
8536   name = getFormattedJoystickName(SDL_JoystickName(joystick));
8537
8538 #if DEBUG_JOYSTICKS
8539   // print info about the joystick we are watching
8540   Debug("joystick", "watching joystick %d: (%s)",
8541         SDL_JoystickInstanceID(joystick), name);
8542   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
8543         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
8544         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
8545 #endif
8546
8547   // initialize mapping with GUID and name
8548   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
8549
8550   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
8551            temp, name, SDL_GetPlatform());
8552
8553   // loop through all steps (buttons and axes), getting joystick events
8554   for (i = 0; i < SDL_arraysize(steps) && !done;)
8555   {
8556     Bitmap *marker = button;    // initialize with reliable default value
8557
8558     step = &steps[i];
8559     strcpy(step->mapping, mapping);
8560     step->axis = -1;
8561     step->button = -1;
8562     step->hat = -1;
8563     step->hat_value = -1;
8564
8565     marker = (step->marker == MARKER_BUTTON ? button :
8566               step->marker == MARKER_AXIS_X ? axis_x :
8567               step->marker == MARKER_AXIS_Y ? axis_y : marker);
8568
8569     next = FALSE;
8570
8571     while (!done && !next)
8572     {
8573       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
8574       alpha_ticks = SDL_GetTicks();
8575
8576       if (alpha >= 255)
8577       {
8578         alpha = 255;
8579         alpha_step = -1;
8580       }
8581       else if (alpha < 128)
8582       {
8583         alpha = 127;
8584         alpha_step = 1;
8585       }
8586
8587       int controller_x = SX + (SXSIZE - controller->width) / 2;
8588       int controller_y = SY + ystep_line;
8589
8590       int marker_x = controller_x + step->x;
8591       int marker_y = controller_y + step->y;
8592
8593       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
8594       int ystart2 = ystart1 + ystep_name + ystep_line;
8595
8596       ClearField();
8597
8598       DrawTextSCentered(ystart1, font_name, name);
8599
8600       DrawTextSCentered(ystart2, font_info,
8601                         "Press buttons and move axes on");
8602       ystart2 += ystep_line;
8603       DrawTextSCentered(ystart2, font_info,
8604                         "your controller when indicated.");
8605       ystart2 += ystep_line;
8606       DrawTextSCentered(ystart2, font_info,
8607                         "(Your controller may look different.)");
8608       ystart2 += ystep_para;
8609
8610 #if defined(PLATFORM_ANDROID)
8611       DrawTextSCentered(ystart2, font_info,
8612                         "To correct a mistake,");
8613       ystart2 += ystep_line;
8614       DrawTextSCentered(ystart2, font_info,
8615                         "press the 'back' button.");
8616       ystart2 += ystep_line;
8617       DrawTextSCentered(ystart2, font_info,
8618                         "To skip a button or axis,");
8619       ystart2 += ystep_line;
8620       DrawTextSCentered(ystart2, font_info,
8621                         "press the 'menu' button.");
8622 #else
8623       DrawTextSCentered(ystart2, font_info,
8624                         "To correct a mistake,");
8625       ystart2 += ystep_line;
8626       DrawTextSCentered(ystart2, font_info,
8627                         "press the 'backspace' key.");
8628       ystart2 += ystep_line;
8629       DrawTextSCentered(ystart2, font_info,
8630                         "To skip a button or axis,");
8631       ystart2 += ystep_line;
8632       DrawTextSCentered(ystart2, font_info,
8633                         "press the 'return' key.");
8634       ystart2 += ystep_line;
8635       DrawTextSCentered(ystart2, font_info,
8636                         "To exit, press the 'escape' key.");
8637 #endif
8638
8639       BlitBitmapMasked(controller, drawto, 0, 0,
8640                        controller->width, controller->height,
8641                        controller_x, controller_y);
8642
8643       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
8644       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
8645
8646       BlitBitmapMasked(marker, drawto, 0, 0,
8647                        marker->width, marker->height,
8648                        marker_x, marker_y);
8649
8650       if (!screen_initialized)
8651         FadeIn(REDRAW_FIELD);
8652       else
8653         BackToFront();
8654
8655       screen_initialized = TRUE;
8656
8657       DelayCounter event_frame_delay = { GAME_FRAME_DELAY };
8658
8659       // reset frame delay counter directly after updating screen
8660       ResetDelayCounter(&event_frame_delay);
8661
8662       while (NextValidEvent(&event))
8663       {
8664         switch (event.type)
8665         {
8666           case SDL_JOYAXISMOTION:
8667             if (event.jaxis.value > 20000 ||
8668                 event.jaxis.value < -20000)
8669             {
8670               for (j = 0; j < i; j++)
8671                 if (steps[j].axis == event.jaxis.axis)
8672                   break;
8673
8674               if (j == i)
8675               {
8676                 if (step->marker != MARKER_AXIS_X &&
8677                     step->marker != MARKER_AXIS_Y)
8678                   break;
8679
8680                 step->axis = event.jaxis.axis;
8681                 strcat(mapping, step->field);
8682                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
8683                 strcat(mapping, temp);
8684                 i++;
8685                 next = TRUE;
8686               }
8687             }
8688
8689             break;
8690
8691           case SDL_JOYHATMOTION:
8692             // ignore centering; we're probably just coming back
8693             // to the center from the previous item we set
8694             if (event.jhat.value == SDL_HAT_CENTERED)
8695               break;
8696
8697             for (j = 0; j < i; j++)
8698               if (steps[j].hat == event.jhat.hat &&
8699                   steps[j].hat_value == event.jhat.value)
8700                 break;
8701
8702             if (j == i)
8703             {
8704               step->hat = event.jhat.hat;
8705               step->hat_value = event.jhat.value;
8706               strcat(mapping, step->field);
8707               snprintf(temp, sizeof(temp), ":h%u.%u,",
8708                        event.jhat.hat, event.jhat.value );
8709               strcat(mapping, temp);
8710               i++;
8711               next = TRUE;
8712             }
8713
8714             break;
8715
8716           case SDL_JOYBALLMOTION:
8717             break;
8718
8719           case SDL_JOYBUTTONUP:
8720             for (j = 0; j < i; j++)
8721               if (steps[j].button == event.jbutton.button)
8722                 break;
8723
8724             if (j == i)
8725             {
8726               step->button = event.jbutton.button;
8727               strcat(mapping, step->field);
8728               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
8729               strcat(mapping, temp);
8730               i++;
8731               next = TRUE;
8732             }
8733
8734             break;
8735
8736           case SDL_FINGERDOWN:
8737           case SDL_MOUSEBUTTONDOWN:
8738             // skip this step
8739             i++;
8740             next = TRUE;
8741
8742             break;
8743
8744           case SDL_KEYDOWN:
8745             if (event.key.keysym.sym == KSYM_BackSpace ||
8746                 event.key.keysym.sym == KSYM_Back)
8747             {
8748               if (i == 0)
8749               {
8750                 // leave screen
8751                 success = FALSE;
8752                 done = TRUE;
8753
8754                 break;
8755               }
8756
8757               // undo this step
8758               prev_step = &steps[i - 1];
8759               strcpy(mapping, prev_step->mapping);
8760               i--;
8761               next = TRUE;
8762
8763               break;
8764             }
8765
8766             if (event.key.keysym.sym == KSYM_space ||
8767                 event.key.keysym.sym == KSYM_Return ||
8768                 event.key.keysym.sym == KSYM_Menu)
8769             {
8770               // skip this step
8771               i++;
8772               next = TRUE;
8773
8774               break;
8775             }
8776
8777             if (event.key.keysym.sym == KSYM_Escape)
8778             {
8779               // leave screen
8780               success = FALSE;
8781               done = TRUE;
8782             }
8783
8784             break;
8785
8786           case SDL_QUIT:
8787             program.exit_function(0);
8788             break;
8789
8790           default:
8791             break;
8792         }
8793
8794         // do not handle events for longer than standard frame delay period
8795         if (DelayReached(&event_frame_delay))
8796           break;
8797       }
8798     }
8799   }
8800
8801   if (success)
8802   {
8803 #if DEBUG_JOYSTICKS
8804     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
8805 #endif
8806
8807     // activate mapping for this game
8808     SDL_GameControllerAddMapping(mapping);
8809
8810     // save mapping to personal mappings
8811     SaveSetup_AddGameControllerMapping(mapping);
8812   }
8813
8814   // wait until the last pending event was removed from event queue
8815   while (NextValidEvent(&event));
8816
8817   return success;
8818 }
8819
8820 static int ConfigureJoystickMain(int player_nr)
8821 {
8822   char *device_name = setup.input[player_nr].joy.device_name;
8823   int joystick_nr = getJoystickNrFromDeviceName(device_name);
8824   boolean joystick_active = CheckJoystickOpened(joystick_nr);
8825   int success = FALSE;
8826   int i;
8827
8828   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
8829     return JOYSTICK_NOT_AVAILABLE;
8830
8831   if (!joystick_active || !setup.input[player_nr].use_joystick)
8832     return JOYSTICK_NOT_AVAILABLE;
8833
8834   FadeSetEnterMenu();
8835   FadeOut(REDRAW_FIELD);
8836
8837   // close all joystick devices (potentially opened as game controllers)
8838   for (i = 0; i < SDL_NumJoysticks(); i++)
8839     SDLCloseJoystick(i);
8840
8841   // open joystick device as plain joystick to configure as game controller
8842   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
8843
8844   // as the joystick was successfully opened before, this should not happen
8845   if (joystick == NULL)
8846     return FALSE;
8847
8848   // create new game controller mapping (buttons and axes) for joystick device
8849   success = ConfigureJoystickMapButtonsAndAxes(joystick);
8850
8851   // close joystick (and maybe re-open as configured game controller later)
8852   SDL_JoystickClose(joystick);
8853
8854   // re-open all joystick devices (potentially as game controllers)
8855   for (i = 0; i < SDL_NumJoysticks(); i++)
8856     SDLOpenJoystick(i);
8857
8858   // clear all joystick input actions for all joystick devices
8859   SDLClearJoystickState();
8860
8861   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
8862 }
8863
8864 void ConfigureJoystick(int player_nr)
8865 {
8866   boolean state = ConfigureJoystickMain(player_nr);
8867
8868   if (state != JOYSTICK_NOT_CONFIGURED)
8869   {
8870     boolean success = (state == JOYSTICK_CONFIGURED);
8871     char message1[MAX_OUTPUT_LINESIZE + 1];
8872     char *message2 = (success ? "configured!" : "not available!");
8873     char *device_name = setup.input[player_nr].joy.device_name;
8874     int nr = getJoystickNrFromDeviceName(device_name) + 1;
8875     int font_nr = FONT_TITLE_1;
8876     int font_height = getFontHeight(font_nr);
8877     int ypos1 = SYSIZE / 2 - font_height * 2;
8878     int ypos2 = SYSIZE / 2 - font_height * 1;
8879     DelayCounter wait_frame_delay = { 2000 };
8880
8881     ResetDelayCounter(&wait_frame_delay);
8882
8883     ClearField();
8884
8885     sprintf(message1, "Joystick %d", nr);
8886
8887     DrawTextSCentered(ypos1, font_nr, message1);
8888     DrawTextSCentered(ypos2, font_nr, message2);
8889
8890     while (!DelayReached(&wait_frame_delay))
8891       BackToFront();
8892
8893     ClearEventQueue();
8894   }
8895
8896   DrawSetupScreen_Input();
8897 }
8898
8899 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
8900 {
8901   if (y < video.screen_height / 3)
8902   {
8903     // remap touch gadgets to access upper part of the screen
8904     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8905     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
8906   }
8907   else if (y > 2 * video.screen_height / 3)
8908   {
8909     // remap touch gadgets to access lower part of the screen
8910     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8911     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
8912   }
8913 }
8914
8915 static boolean ConfigureVirtualButtonsMain(void)
8916 {
8917   static char *customize_step_text[] =
8918   {
8919     "Move Left",
8920     "Move Right",
8921     "Move Up",
8922     "Move Down",
8923     "Snap Field",
8924     "Drop Element"
8925   };
8926   char grid_button[] =
8927   {
8928     CHAR_GRID_BUTTON_LEFT,
8929     CHAR_GRID_BUTTON_RIGHT,
8930     CHAR_GRID_BUTTON_UP,
8931     CHAR_GRID_BUTTON_DOWN,
8932     CHAR_GRID_BUTTON_SNAP,
8933     CHAR_GRID_BUTTON_DROP
8934   };
8935   enum
8936   {
8937     ACTION_NONE,
8938     ACTION_ESCAPE,
8939     ACTION_BACK,
8940     ACTION_NEXT
8941   };
8942   int font_nr = FONT_INPUT_1_ACTIVE;
8943   int font_height = getFontHeight(font_nr);
8944   int ypos1 = SYSIZE / 2 - font_height * 2;
8945   int ypos2 = SYSIZE / 2 - font_height * 1;
8946   boolean success = FALSE;
8947   boolean finished = FALSE;
8948   int step_nr = 0;
8949   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
8950   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
8951   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
8952   boolean set_grid_button = FALSE;
8953   int nr = GRID_ACTIVE_NR();
8954   int x, y;
8955
8956   for (x = 0; x < MAX_GRID_XSIZE; x++)
8957     for (y = 0; y < MAX_GRID_YSIZE; y++)
8958       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
8959
8960   overlay.grid_button_highlight = grid_button[step_nr];
8961
8962   UnmapAllGadgets();
8963
8964   FadeSetEnterMenu();
8965   FadeOut(REDRAW_FIELD);
8966
8967   ClearField();
8968
8969   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
8970   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
8971   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
8972
8973   FadeIn(REDRAW_FIELD);
8974
8975   SetOverlayShowGrid(TRUE);
8976
8977   // map gadgets for setup touch buttons menu screen
8978   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8979
8980   while (!finished)
8981   {
8982     Event event;
8983
8984     while (NextValidEvent(&event))
8985     {
8986       int action = ACTION_NONE;
8987
8988       // ---------- handle events and set the resulting action ----------
8989
8990       switch (event.type)
8991       {
8992         case EVENT_USER:
8993           {
8994             UserEvent *user = (UserEvent *)&event;
8995             int id = user->value1;
8996
8997             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
8998                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
8999                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
9000                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
9001                       ACTION_NONE);
9002           }
9003           break;
9004
9005         case EVENT_KEYPRESS:
9006           {
9007             Key key = GetEventKey((KeyEvent *)&event);
9008
9009             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
9010                       key == KSYM_BackSpace ||
9011                       key == KSYM_Back ?        ACTION_BACK :
9012                       key == KSYM_Return ||
9013                       key == KSYM_Menu ||
9014                       key == KSYM_space ?       ACTION_NEXT :
9015                       ACTION_NONE);
9016           }
9017           break;
9018
9019         case EVENT_KEYRELEASE:
9020           key_joystick_mapping = 0;
9021           break;
9022
9023         case EVENT_BUTTONPRESS:
9024         case EVENT_BUTTONRELEASE:
9025           {
9026             ButtonEvent *button = (ButtonEvent *)&event;
9027
9028             motion_status = FALSE;
9029
9030             if (button->type == EVENT_BUTTONPRESS)
9031               button_status = button->button;
9032             else
9033               button_status = MB_RELEASED;
9034
9035             if (HandleGadgets(button->x, button->y, button_status))
9036             {
9037               // do not handle this button event anymore
9038               break;
9039             }
9040
9041             button->x += video.screen_xoffset;
9042             button->y += video.screen_yoffset;
9043
9044             x = button->x * overlay.grid_xsize / video.screen_width;
9045             y = button->y * overlay.grid_ysize / video.screen_height;
9046
9047             if (button->type == EVENT_BUTTONPRESS)
9048             {
9049               grid_button_draw =
9050                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9051                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9052
9053               set_grid_button = TRUE;
9054             }
9055
9056             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9057           }
9058           break;
9059
9060         case EVENT_MOTIONNOTIFY:
9061           {
9062             MotionEvent *motion = (MotionEvent *)&event;
9063
9064             motion_status = TRUE;
9065
9066             if (HandleGadgets(motion->x, motion->y, button_status))
9067             {
9068               // do not handle this button event anymore
9069               break;
9070             }
9071
9072             motion->x += video.screen_xoffset;
9073             motion->y += video.screen_yoffset;
9074
9075             x = motion->x * overlay.grid_xsize / video.screen_width;
9076             y = motion->y * overlay.grid_ysize / video.screen_height;
9077
9078             set_grid_button = TRUE;
9079
9080             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9081           }
9082           break;
9083
9084         case SDL_WINDOWEVENT:
9085           HandleWindowEvent((WindowEvent *) &event);
9086
9087           // check if device has been rotated
9088           if (nr != GRID_ACTIVE_NR())
9089           {
9090             nr = GRID_ACTIVE_NR();
9091
9092             for (x = 0; x < MAX_GRID_XSIZE; x++)
9093               for (y = 0; y < MAX_GRID_YSIZE; y++)
9094                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9095                   overlay.grid_button[x][y];
9096           }
9097
9098           break;
9099
9100         case SDL_APP_WILLENTERBACKGROUND:
9101         case SDL_APP_DIDENTERBACKGROUND:
9102         case SDL_APP_WILLENTERFOREGROUND:
9103         case SDL_APP_DIDENTERFOREGROUND:
9104           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9105           break;
9106
9107         default:
9108           HandleOtherEvents(&event);
9109           break;
9110       }
9111
9112       // ---------- perform action set by handling events ----------
9113
9114       if (action == ACTION_ESCAPE)
9115       {
9116         // abort and restore the old key bindings
9117
9118         for (x = 0; x < MAX_GRID_XSIZE; x++)
9119           for (y = 0; y < MAX_GRID_YSIZE; y++)
9120             overlay.grid_button[x][y] = grid_button_old[x][y];
9121
9122         FadeSkipNextFadeIn();
9123
9124         finished = TRUE;
9125       }
9126       else if (action == ACTION_BACK)
9127       {
9128         // keep the configured key bindings and go to previous page
9129
9130         step_nr--;
9131
9132         if (step_nr < 0)
9133         {
9134           FadeSkipNextFadeIn();
9135
9136           finished = TRUE;
9137         }
9138       }
9139       else if (action == ACTION_NEXT)
9140       {
9141         // keep the configured key bindings and go to next page
9142
9143         step_nr++;
9144
9145         // all virtual buttons configured
9146         if (step_nr == 6)
9147         {
9148           finished = TRUE;
9149           success = TRUE;
9150         }
9151       }
9152
9153       if (action != ACTION_NONE && !finished)
9154       {
9155         for (x = 0; x < MAX_GRID_XSIZE; x++)
9156           for (y = 0; y < MAX_GRID_YSIZE; y++)
9157             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9158
9159         overlay.grid_button_highlight = grid_button[step_nr];
9160
9161         // configure next virtual button
9162
9163         ClearField();
9164
9165         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9166         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9167         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9168       }
9169
9170       if (set_grid_button)
9171       {
9172         overlay.grid_button[x][y] =
9173           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9174            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9175            grid_button_tmp[x][y]);
9176
9177         set_grid_button = FALSE;
9178       }
9179     }
9180
9181     BackToFront();
9182   }
9183
9184   for (x = 0; x < MAX_GRID_XSIZE; x++)
9185     for (y = 0; y < MAX_GRID_YSIZE; y++)
9186       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9187
9188   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9189
9190   SetOverlayShowGrid(FALSE);
9191
9192   return success;
9193 }
9194
9195 void ConfigureVirtualButtons(void)
9196 {
9197   boolean success = ConfigureVirtualButtonsMain();
9198
9199   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9200                          SCREEN_MASK_TOUCH2);
9201
9202   if (success)
9203   {
9204     int font_nr = FONT_TITLE_1;
9205     int font_height = getFontHeight(font_nr);
9206     int ypos1 = SYSIZE / 2 - font_height * 2;
9207     int ypos2 = SYSIZE / 2 - font_height * 1;
9208     DelayCounter wait_frame_delay = { 2000 };
9209
9210     ResetDelayCounter(&wait_frame_delay);
9211
9212     ClearField();
9213
9214     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9215     DrawTextSCentered(ypos2, font_nr, "configured!");
9216
9217     while (!DelayReached(&wait_frame_delay))
9218       BackToFront();
9219
9220     ClearEventQueue();
9221   }
9222 }
9223
9224 void DrawSetupScreen(void)
9225 {
9226   align_xoffset = 0;
9227   align_yoffset = 0;
9228
9229   if (setup_mode == SETUP_MODE_INPUT)
9230     DrawSetupScreen_Input();
9231   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9232     DrawChooseTree(&scores_type_current);
9233   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9234     DrawChooseTree(&game_speed_current);
9235   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9236     DrawChooseTree(&scroll_delay_current);
9237   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9238     DrawChooseTree(&snapshot_mode_current);
9239   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9240     DrawChooseTree(&window_size_current);
9241   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9242     DrawChooseTree(&scaling_type_current);
9243   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9244     DrawChooseTree(&rendering_mode_current);
9245   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9246     DrawChooseTree(&vsync_mode_current);
9247   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9248     DrawChooseTree(&artwork.gfx_current);
9249   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9250     DrawChooseTree(&artwork.snd_current);
9251   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9252     DrawChooseTree(&artwork.mus_current);
9253   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9254     DrawChooseTree(&volume_simple_current);
9255   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9256     DrawChooseTree(&volume_loops_current);
9257   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9258     DrawChooseTree(&volume_music_current);
9259   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9260     DrawChooseTree(&touch_control_current);
9261   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9262     DrawChooseTree(&move_distance_current);
9263   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9264     DrawChooseTree(&drop_distance_current);
9265   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9266     DrawChooseTree(&transparency_current);
9267   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9268     DrawChooseTree(&grid_size_current[0][0]);
9269   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9270     DrawChooseTree(&grid_size_current[0][1]);
9271   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9272     DrawChooseTree(&grid_size_current[1][0]);
9273   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9274     DrawChooseTree(&grid_size_current[1][1]);
9275   else
9276     DrawSetupScreen_Generic();
9277
9278   PlayMenuSoundsAndMusic();
9279 }
9280
9281 void RedrawSetupScreenAfterFullscreenToggle(void)
9282 {
9283   if (setup_mode == SETUP_MODE_GRAPHICS ||
9284       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9285   {
9286     // update list selection from "setup.window_scaling_percent"
9287     execSetupGraphics_setWindowSizes(TRUE);
9288
9289     DrawSetupScreen();
9290   }
9291 }
9292
9293 void RedrawSetupScreenAfterScreenRotation(int nr)
9294 {
9295   int x, y;
9296
9297   if (setup_mode == SETUP_MODE_TOUCH)
9298   {
9299     // update virtual button settings (depending on screen orientation)
9300     DrawSetupScreen();
9301   }
9302   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
9303   {
9304     // save already configured virtual buttons
9305     for (x = 0; x < MAX_GRID_XSIZE; x++)
9306       for (y = 0; y < MAX_GRID_YSIZE; y++)
9307         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9308   }
9309 }
9310
9311 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
9312 {
9313   if (setup_mode == SETUP_MODE_INPUT)
9314     HandleSetupScreen_Input(mx, my, dx, dy, button);
9315   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9316     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
9317   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9318     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
9319   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9320     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
9321   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9322     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
9323   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9324     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
9325   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9326     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
9327   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9328     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
9329   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9330     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
9331   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9332     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
9333   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9334     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
9335   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9336     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
9337   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9338     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
9339   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9340     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
9341   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9342     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
9343   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9344     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
9345   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9346     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
9347   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9348     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
9349   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9350     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
9351   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9352     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
9353   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9354     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
9355   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9356     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
9357   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9358     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
9359   else
9360     HandleSetupScreen_Generic(mx, my, dx, dy, button);
9361 }
9362
9363 void HandleGameActions(void)
9364 {
9365   if (setup.ask_on_game_over)
9366     CheckGameOver();
9367
9368   if (game.restart_game_message != NULL)
9369   {
9370     RequestRestartGame(game.restart_game_message);
9371
9372     return;
9373   }
9374
9375   if (game_status != GAME_MODE_PLAYING)
9376     return;
9377
9378   GameActions();                // main game loop
9379
9380   if (tape.auto_play && !tape.playing)
9381     AutoPlayTapesContinue();    // continue automatically playing next tape
9382 }
9383
9384
9385 // ---------- new screen button stuff --------------------------------------
9386
9387 static struct
9388 {
9389   int gfx_unpressed, gfx_pressed;
9390   struct MenuPosInfo *pos;
9391   boolean *check_value;
9392   int gadget_id;
9393   int screen_mask;
9394   unsigned int event_mask;
9395   boolean is_touch_button;
9396   char *infotext;
9397 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
9398 {
9399   {
9400     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
9401     &menu.main.button.prev_level, NULL,
9402     SCREEN_CTRL_ID_PREV_LEVEL,
9403     SCREEN_MASK_MAIN,
9404     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9405     FALSE, "previous level"
9406   },
9407   {
9408     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
9409     &menu.main.button.next_level, NULL,
9410     SCREEN_CTRL_ID_NEXT_LEVEL,
9411     SCREEN_MASK_MAIN,
9412     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9413     FALSE, "next level"
9414   },
9415   {
9416     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE,
9417     &menu.scores.button.prev_level, NULL,
9418     SCREEN_CTRL_ID_PREV_LEVEL2,
9419     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9420     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9421     FALSE, "previous level"
9422   },
9423   {
9424     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE,
9425     &menu.scores.button.next_level, NULL,
9426     SCREEN_CTRL_ID_NEXT_LEVEL2,
9427     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9428     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9429     FALSE, "next level"
9430   },
9431   {
9432     IMG_MENU_BUTTON_PREV_SCORE, IMG_MENU_BUTTON_PREV_SCORE_ACTIVE,
9433     &menu.scores.button.prev_score, NULL,
9434     SCREEN_CTRL_ID_PREV_SCORE,
9435     SCREEN_MASK_SCORES_INFO,
9436     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9437     FALSE, "previous score"
9438   },
9439   {
9440     IMG_MENU_BUTTON_NEXT_SCORE, IMG_MENU_BUTTON_NEXT_SCORE_ACTIVE,
9441     &menu.scores.button.next_score, NULL,
9442     SCREEN_CTRL_ID_NEXT_SCORE,
9443     SCREEN_MASK_SCORES_INFO,
9444     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9445     FALSE, "next score"
9446   },
9447   {
9448     IMG_MENU_BUTTON_PLAY_TAPE, IMG_MENU_BUTTON_PLAY_TAPE,
9449     &menu.scores.button.play_tape, NULL,
9450     SCREEN_CTRL_ID_PLAY_TAPE,
9451     SCREEN_MASK_SCORES_INFO,
9452     GD_EVENT_RELEASED,
9453     FALSE, "play tape"
9454   },
9455   {
9456     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE,
9457     &menu.main.button.first_level, NULL,
9458     SCREEN_CTRL_ID_FIRST_LEVEL,
9459     SCREEN_MASK_MAIN,
9460     GD_EVENT_RELEASED,
9461     FALSE, "first level"
9462   },
9463   {
9464     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE,
9465     &menu.main.button.last_level, NULL,
9466     SCREEN_CTRL_ID_LAST_LEVEL,
9467     SCREEN_MASK_MAIN,
9468     GD_EVENT_RELEASED,
9469     FALSE, "last level"
9470   },
9471   {
9472     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE,
9473     &menu.main.button.level_number, NULL,
9474     SCREEN_CTRL_ID_LEVEL_NUMBER,
9475     SCREEN_MASK_MAIN,
9476     GD_EVENT_RELEASED,
9477     FALSE, "level number"
9478   },
9479   {
9480     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
9481     &menu.setup.button.prev_player, NULL,
9482     SCREEN_CTRL_ID_PREV_PLAYER,
9483     SCREEN_MASK_INPUT,
9484     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9485     FALSE, "previous player"
9486   },
9487   {
9488     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
9489     &menu.setup.button.next_player, NULL,
9490     SCREEN_CTRL_ID_NEXT_PLAYER,
9491     SCREEN_MASK_INPUT,
9492     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9493     FALSE, "next player"
9494   },
9495   {
9496     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE,
9497     &menu.main.button.insert_solution, NULL,
9498     SCREEN_CTRL_ID_INSERT_SOLUTION,
9499     SCREEN_MASK_MAIN_HAS_SOLUTION,
9500     GD_EVENT_RELEASED,
9501     FALSE, "insert solution tape"
9502   },
9503   {
9504     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE,
9505     &menu.main.button.play_solution, NULL,
9506     SCREEN_CTRL_ID_PLAY_SOLUTION,
9507     SCREEN_MASK_MAIN_HAS_SOLUTION,
9508     GD_EVENT_RELEASED,
9509     FALSE, "play solution tape"
9510   },
9511   {
9512     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE,
9513     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
9514     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
9515     SCREEN_MASK_MAIN,
9516     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
9517     FALSE, "switch ECS/AGA chipset"
9518   },
9519   {
9520     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK,
9521     &menu.setup.button.touch_back, NULL,
9522     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
9523     SCREEN_MASK_TOUCH,
9524     GD_EVENT_RELEASED,
9525     TRUE, "previous page"
9526   },
9527   {
9528     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT,
9529     &menu.setup.button.touch_next, NULL,
9530     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
9531     SCREEN_MASK_TOUCH,
9532     GD_EVENT_RELEASED,
9533     TRUE, "next page"
9534   },
9535   {
9536     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2,
9537     &menu.setup.button.touch_back2, NULL,
9538     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
9539     SCREEN_MASK_TOUCH2,
9540     GD_EVENT_RELEASED,
9541     TRUE, "previous page"
9542   },
9543   {
9544     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2,
9545     &menu.setup.button.touch_next2, NULL,
9546     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
9547     SCREEN_MASK_TOUCH2,
9548     GD_EVENT_RELEASED,
9549     TRUE, "next page"
9550   },
9551 };
9552
9553 static struct
9554 {
9555   int gfx_unpressed, gfx_pressed;
9556   int x, y;
9557   int gadget_id;
9558   char *infotext;
9559 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
9560 {
9561   {
9562     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
9563     -1, -1,     // these values are not constant, but can change at runtime
9564     SCREEN_CTRL_ID_SCROLL_UP,
9565     "scroll up"
9566   },
9567   {
9568     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
9569     -1, -1,     // these values are not constant, but can change at runtime
9570     SCREEN_CTRL_ID_SCROLL_DOWN,
9571     "scroll down"
9572   }
9573 };
9574
9575 static struct
9576 {
9577   int gfx_unpressed, gfx_pressed;
9578   int x, y;
9579   int width, height;
9580   int type;
9581   int gadget_id;
9582   char *infotext;
9583 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
9584 {
9585   {
9586     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
9587     -1, -1,     // these values are not constant, but can change at runtime
9588     -1, -1,     // these values are not constant, but can change at runtime
9589     GD_TYPE_SCROLLBAR_VERTICAL,
9590     SCREEN_CTRL_ID_SCROLL_VERTICAL,
9591     "scroll level series vertically"
9592   }
9593 };
9594
9595 static struct
9596 {
9597   int graphic;
9598   int gadget_id;
9599   int x, y;
9600   int size;
9601   char *value;
9602   char *infotext;
9603 } textinput_info[NUM_SCREEN_TEXTINPUT] =
9604 {
9605   {
9606     IMG_SETUP_INPUT_TEXT,
9607     SCREEN_CTRL_ID_NETWORK_SERVER,
9608     -1, -1,     // these values are not constant, but can change at runtime
9609     MAX_SETUP_TEXT_INPUT_LEN,
9610     network_server_hostname,
9611     "Network Server Hostname / IP"
9612   },
9613 };
9614
9615 static void CreateScreenMenubuttons(void)
9616 {
9617   struct GadgetInfo *gi;
9618   unsigned int event_mask;
9619   int i;
9620
9621   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9622   {
9623     struct MenuPosInfo *pos = menubutton_info[i].pos;
9624     int screen_mask = menubutton_info[i].screen_mask;
9625     boolean is_touch_button = menubutton_info[i].is_touch_button;
9626     boolean is_check_button = menubutton_info[i].check_value != NULL;
9627     boolean is_score_button = (screen_mask & SCREEN_MASK_SCORES_INFO);
9628     boolean has_gfx_pressed = (menubutton_info[i].gfx_pressed ==
9629                                menubutton_info[i].gfx_unpressed);
9630     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9631     int gfx_unpressed, gfx_pressed;
9632     int x, y, width, height;
9633     int gd_x1, gd_x2, gd_y1, gd_y2;
9634     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
9635     int id = menubutton_info[i].gadget_id;
9636     int type = GD_TYPE_NORMAL_BUTTON;
9637     boolean checked = FALSE;
9638
9639     // do not use touch buttons if overlay touch buttons are disabled
9640     if (is_touch_button && !setup.touch.overlay_buttons)
9641       continue;
9642
9643     event_mask = menubutton_info[i].event_mask;
9644
9645     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
9646     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
9647
9648     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
9649     height = graphic_info[menubutton_info[i].gfx_pressed].height;
9650
9651     gfx_unpressed = menubutton_info[i].gfx_unpressed;
9652     gfx_pressed   = menubutton_info[i].gfx_pressed;
9653     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9654     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9655     gd_x1 = graphic_info[gfx_unpressed].src_x;
9656     gd_y1 = graphic_info[gfx_unpressed].src_y;
9657     gd_x2 = graphic_info[gfx_pressed].src_x;
9658     gd_y2 = graphic_info[gfx_pressed].src_y;
9659     gd_x1a = gd_x1;
9660     gd_y1a = gd_y1;
9661     gd_x2a = gd_x2;
9662     gd_y2a = gd_y2;
9663
9664     if (has_gfx_pressed)
9665     {
9666       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
9667       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
9668     }
9669
9670     if (is_check_button)
9671     {
9672       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
9673       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
9674       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
9675       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
9676
9677       type = GD_TYPE_CHECK_BUTTON;
9678       checked = *menubutton_info[i].check_value;
9679     }
9680
9681     if (is_score_button)
9682     {
9683       // if x/y set to -1, dynamically place buttons next to title text
9684       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
9685
9686       // special compatibility handling for "Snake Bite" graphics set
9687       if (strPrefix(leveldir_current->identifier, "snake_bite"))
9688         title_width = strlen(INFOTEXT_SCORE_ENTRY) * 32;
9689
9690       // use "SX" here to center buttons (ignore horizontal draw offset)
9691       if (pos->x == -1)
9692         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
9693              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
9694              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
9695              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
9696
9697       // use "mSY" here to place buttons (respect vertical draw offset)
9698       if (pos->y == -1)
9699         y = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ||
9700              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ? mSY + MENU_TITLE1_YPOS : 0);
9701     }
9702
9703     gi = CreateGadget(GDI_CUSTOM_ID, id,
9704                       GDI_CUSTOM_TYPE_ID, i,
9705                       GDI_IMAGE_ID, gfx_unpressed,
9706                       GDI_INFO_TEXT, menubutton_info[i].infotext,
9707                       GDI_X, x,
9708                       GDI_Y, y,
9709                       GDI_WIDTH, width,
9710                       GDI_HEIGHT, height,
9711                       GDI_TYPE, type,
9712                       GDI_STATE, GD_BUTTON_UNPRESSED,
9713                       GDI_CHECKED, checked,
9714                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9715                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9716                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1a, gd_y1a,
9717                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2a, gd_y2a,
9718                       GDI_DIRECT_DRAW, FALSE,
9719                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
9720                       GDI_EVENT_MASK, event_mask,
9721                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9722                       GDI_END);
9723
9724     if (gi == NULL)
9725       Fail("cannot create gadget");
9726
9727     screen_gadget[id] = gi;
9728   }
9729 }
9730
9731 static void CreateScreenScrollbuttons(void)
9732 {
9733   struct GadgetInfo *gi;
9734   unsigned int event_mask;
9735   int i;
9736
9737   // these values are not constant, but can change at runtime
9738   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
9739   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
9740   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
9741   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
9742
9743   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
9744   {
9745     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9746     int gfx_unpressed, gfx_pressed;
9747     int x, y, width, height;
9748     int gd_x1, gd_x2, gd_y1, gd_y2;
9749     int id = scrollbutton_info[i].gadget_id;
9750
9751     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
9752
9753     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
9754     y = mSY + scrollbutton_info[i].y;
9755     width = SC_SCROLLBUTTON_XSIZE;
9756     height = SC_SCROLLBUTTON_YSIZE;
9757
9758     // correct scrollbar position if placed outside menu (playfield) area
9759     if (x > SX + SC_SCROLL_UP_XPOS)
9760       x = SX + SC_SCROLL_UP_XPOS;
9761
9762     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
9763       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
9764                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
9765
9766     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
9767     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
9768     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9769     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9770     gd_x1 = graphic_info[gfx_unpressed].src_x;
9771     gd_y1 = graphic_info[gfx_unpressed].src_y;
9772     gd_x2 = graphic_info[gfx_pressed].src_x;
9773     gd_y2 = graphic_info[gfx_pressed].src_y;
9774
9775     gi = CreateGadget(GDI_CUSTOM_ID, id,
9776                       GDI_CUSTOM_TYPE_ID, i,
9777                       GDI_IMAGE_ID, gfx_unpressed,
9778                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
9779                       GDI_X, x,
9780                       GDI_Y, y,
9781                       GDI_WIDTH, width,
9782                       GDI_HEIGHT, height,
9783                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
9784                       GDI_STATE, GD_BUTTON_UNPRESSED,
9785                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9786                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9787                       GDI_DIRECT_DRAW, FALSE,
9788                       GDI_EVENT_MASK, event_mask,
9789                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9790                       GDI_END);
9791
9792     if (gi == NULL)
9793       Fail("cannot create gadget");
9794
9795     screen_gadget[id] = gi;
9796   }
9797 }
9798
9799 static void CreateScreenScrollbars(void)
9800 {
9801   int i;
9802
9803   // these values are not constant, but can change at runtime
9804   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
9805   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
9806   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
9807   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
9808
9809   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
9810   {
9811     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9812     int gfx_unpressed, gfx_pressed;
9813     int x, y, width, height;
9814     int gd_x1, gd_x2, gd_y1, gd_y2;
9815     struct GadgetInfo *gi;
9816     int items_max, items_visible, item_position;
9817     unsigned int event_mask;
9818     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
9819     int id = scrollbar_info[i].gadget_id;
9820
9821     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
9822
9823     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
9824     y = mSY + scrollbar_info[i].y;
9825     width  = scrollbar_info[i].width;
9826     height = scrollbar_info[i].height;
9827
9828     // correct scrollbar position if placed outside menu (playfield) area
9829     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
9830       x = SX + SC_SCROLL_VERTICAL_XPOS;
9831
9832     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
9833       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
9834
9835     items_max = num_page_entries;
9836     items_visible = num_page_entries;
9837     item_position = 0;
9838
9839     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
9840     gfx_pressed   = scrollbar_info[i].gfx_pressed;
9841     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9842     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9843     gd_x1 = graphic_info[gfx_unpressed].src_x;
9844     gd_y1 = graphic_info[gfx_unpressed].src_y;
9845     gd_x2 = graphic_info[gfx_pressed].src_x;
9846     gd_y2 = graphic_info[gfx_pressed].src_y;
9847
9848     gi = CreateGadget(GDI_CUSTOM_ID, id,
9849                       GDI_CUSTOM_TYPE_ID, i,
9850                       GDI_IMAGE_ID, gfx_unpressed,
9851                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
9852                       GDI_X, x,
9853                       GDI_Y, y,
9854                       GDI_WIDTH, width,
9855                       GDI_HEIGHT, height,
9856                       GDI_TYPE, scrollbar_info[i].type,
9857                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
9858                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
9859                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
9860                       GDI_WHEEL_AREA_X, SX,
9861                       GDI_WHEEL_AREA_Y, SY,
9862                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
9863                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
9864                       GDI_STATE, GD_BUTTON_UNPRESSED,
9865                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9866                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9867                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
9868                       GDI_DIRECT_DRAW, FALSE,
9869                       GDI_EVENT_MASK, event_mask,
9870                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9871                       GDI_END);
9872
9873     if (gi == NULL)
9874       Fail("cannot create gadget");
9875
9876     screen_gadget[id] = gi;
9877   }
9878 }
9879
9880 static void CreateScreenTextInputGadgets(void)
9881 {
9882   int i;
9883
9884   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
9885   {
9886     int graphic = textinput_info[i].graphic;
9887     struct GraphicInfo *gd = &graphic_info[graphic];
9888     int gd_x1 = gd->src_x;
9889     int gd_y1 = gd->src_y;
9890     int gd_x2 = gd->src_x + gd->active_xoffset;
9891     int gd_y2 = gd->src_y + gd->active_yoffset;
9892     struct GadgetInfo *gi;
9893     unsigned int event_mask;
9894     int id = textinput_info[i].gadget_id;
9895     int x = textinput_info[i].x;
9896     int y = textinput_info[i].y;
9897
9898     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
9899
9900     gi = CreateGadget(GDI_CUSTOM_ID, id,
9901                       GDI_CUSTOM_TYPE_ID, i,
9902                       GDI_INFO_TEXT, textinput_info[i].infotext,
9903                       GDI_X, SX + x,
9904                       GDI_Y, SY + y,
9905                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
9906                       GDI_TEXT_VALUE, textinput_info[i].value,
9907                       GDI_TEXT_SIZE, textinput_info[i].size,
9908                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
9909                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
9910                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
9911                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
9912                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
9913                       GDI_DESIGN_WIDTH, gd->width,
9914                       GDI_EVENT_MASK, event_mask,
9915                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9916                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
9917                       GDI_END);
9918
9919     if (gi == NULL)
9920       Fail("cannot create gadget");
9921
9922     screen_gadget[id] = gi;
9923   }
9924 }
9925
9926 void CreateScreenGadgets(void)
9927 {
9928   CreateScreenMenubuttons();
9929
9930   CreateScreenScrollbuttons();
9931   CreateScreenScrollbars();
9932
9933   CreateScreenTextInputGadgets();
9934 }
9935
9936 void FreeScreenGadgets(void)
9937 {
9938   int i;
9939
9940   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
9941     FreeGadget(screen_gadget[i]);
9942 }
9943
9944 static void RedrawScreenMenuGadgets(int screen_mask)
9945 {
9946   int i;
9947
9948   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9949     if (screen_mask & menubutton_info[i].screen_mask)
9950       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
9951 }
9952
9953 static void MapScreenMenuGadgets(int screen_mask)
9954 {
9955   int i;
9956
9957   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9958     if (screen_mask & menubutton_info[i].screen_mask)
9959       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
9960 }
9961
9962 static void UnmapScreenMenuGadgets(int screen_mask)
9963 {
9964   int i;
9965
9966   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9967   {
9968     if (screen_mask & menubutton_info[i].screen_mask)
9969     {
9970       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
9971
9972       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
9973         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
9974                        screen_gadget[menubutton_info[i].gadget_id]->y,
9975                        screen_gadget[menubutton_info[i].gadget_id]->width,
9976                        screen_gadget[menubutton_info[i].gadget_id]->height);
9977     }
9978   }
9979 }
9980
9981 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
9982 {
9983   if (map_gadgets)
9984     MapScreenMenuGadgets(screen_mask);
9985   else
9986     UnmapScreenMenuGadgets(screen_mask);
9987 }
9988
9989 static void MapScreenGadgets(int num_entries)
9990 {
9991   int i;
9992
9993   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
9994     return;
9995
9996   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
9997     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
9998
9999   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10000     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10001 }
10002
10003 static void UnmapScreenGadgets()
10004 {
10005   int i;
10006
10007   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10008     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10009
10010   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10011     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10012 }
10013
10014 static void MapScreenTreeGadgets(TreeInfo *ti)
10015 {
10016   MapScreenGadgets(numTreeInfoInGroup(ti));
10017 }
10018
10019 static void UnmapScreenTreeGadgets(void)
10020 {
10021   UnmapScreenGadgets();
10022 }
10023
10024 static void AdjustScoreInfoButtons_SelectScore(int x, int y1, int y2)
10025 {
10026   struct GadgetInfo *gi_1 = screen_gadget[SCREEN_CTRL_ID_PREV_SCORE];
10027   struct GadgetInfo *gi_2 = screen_gadget[SCREEN_CTRL_ID_NEXT_SCORE];
10028   struct MenuPosInfo *pos_1 = menubutton_info[SCREEN_CTRL_ID_PREV_SCORE].pos;
10029   struct MenuPosInfo *pos_2 = menubutton_info[SCREEN_CTRL_ID_NEXT_SCORE].pos;
10030
10031   if (pos_1->x == -1 && pos_1->y == -1)
10032     ModifyGadget(gi_1, GDI_X, x, GDI_Y, y1, GDI_END);
10033
10034   if (pos_2->x == -1 && pos_2->y == -1)
10035     ModifyGadget(gi_2, GDI_X, x, GDI_Y, y2, GDI_END);
10036 }
10037
10038 static void AdjustScoreInfoButtons_PlayTape(int x, int y, boolean visible)
10039 {
10040   struct GadgetInfo *gi = screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE];
10041   struct MenuPosInfo *pos = menubutton_info[SCREEN_CTRL_ID_PLAY_TAPE].pos;
10042
10043   // set gadget position dynamically, pre-defined or off-screen
10044   int xx = (visible ? (pos->x == -1 ? x : pos->x) : POS_OFFSCREEN);
10045   int yy = (visible ? (pos->y == -1 ? y : pos->y) : POS_OFFSCREEN);
10046
10047   ModifyGadget(gi, GDI_X, xx, GDI_Y, yy, GDI_END);
10048   MapGadget(gi);        // (needed if deactivated on last score page)
10049 }
10050
10051 static void HandleScreenGadgets(struct GadgetInfo *gi)
10052 {
10053   int id = gi->custom_id;
10054   int button = gi->event.button;
10055   int step = (button == MB_LEFTBUTTON   ? 1 :
10056               button == MB_MIDDLEBUTTON ? 5 :
10057               button == MB_RIGHTBUTTON  ? 10 : 1);
10058
10059   switch (id)
10060   {
10061     case SCREEN_CTRL_ID_PREV_LEVEL:
10062       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10063       break;
10064
10065     case SCREEN_CTRL_ID_NEXT_LEVEL:
10066       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10067       break;
10068
10069     case SCREEN_CTRL_ID_PREV_LEVEL2:
10070       HandleHallOfFame_SelectLevel(step, -1);
10071       break;
10072
10073     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10074       HandleHallOfFame_SelectLevel(step, +1);
10075       break;
10076
10077     case SCREEN_CTRL_ID_PREV_SCORE:
10078       HandleScoreInfo_SelectScore(step, -1);
10079       break;
10080
10081     case SCREEN_CTRL_ID_NEXT_SCORE:
10082       HandleScoreInfo_SelectScore(step, +1);
10083       break;
10084
10085     case SCREEN_CTRL_ID_PLAY_TAPE:
10086       HandleScoreInfo_PlayTape();
10087       break;
10088
10089     case SCREEN_CTRL_ID_FIRST_LEVEL:
10090       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10091       break;
10092
10093     case SCREEN_CTRL_ID_LAST_LEVEL:
10094       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10095       break;
10096
10097     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10098       CloseDoor(DOOR_CLOSE_2);
10099       SetGameStatus(GAME_MODE_LEVELNR);
10100       DrawChooseLevelNr();
10101       break;
10102
10103     case SCREEN_CTRL_ID_PREV_PLAYER:
10104       HandleSetupScreen_Input_Player(step, -1);
10105       break;
10106
10107     case SCREEN_CTRL_ID_NEXT_PLAYER:
10108       HandleSetupScreen_Input_Player(step, +1);
10109       break;
10110
10111     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10112       InsertSolutionTape();
10113       break;
10114
10115     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10116       PlaySolutionTape();
10117       break;
10118
10119     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10120       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10121       DrawMainMenu();
10122       break;
10123
10124     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10125     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10126     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10127     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10128       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10129       break;
10130
10131     case SCREEN_CTRL_ID_SCROLL_UP:
10132       if (game_status == GAME_MODE_NAMES)
10133         HandleChoosePlayerName(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10134       else if (game_status == GAME_MODE_LEVELS)
10135         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10136       else if (game_status == GAME_MODE_LEVELNR)
10137         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10138       else if (game_status == GAME_MODE_SETUP)
10139         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10140       else if (game_status == GAME_MODE_INFO)
10141         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10142       else if (game_status == GAME_MODE_SCORES)
10143         HandleHallOfFame(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10144       break;
10145
10146     case SCREEN_CTRL_ID_SCROLL_DOWN:
10147       if (game_status == GAME_MODE_NAMES)
10148         HandleChoosePlayerName(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10149       else if (game_status == GAME_MODE_LEVELS)
10150         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10151       else if (game_status == GAME_MODE_LEVELNR)
10152         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10153       else if (game_status == GAME_MODE_SETUP)
10154         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10155       else if (game_status == GAME_MODE_INFO)
10156         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10157       else if (game_status == GAME_MODE_SCORES)
10158         HandleHallOfFame(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10159       break;
10160
10161     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
10162       if (game_status == GAME_MODE_NAMES)
10163         HandleChoosePlayerName(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10164       else if (game_status == GAME_MODE_LEVELS)
10165         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10166       else if (game_status == GAME_MODE_LEVELNR)
10167         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10168       else if (game_status == GAME_MODE_SETUP)
10169         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10170       else if (game_status == GAME_MODE_INFO)
10171         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10172       else if (game_status == GAME_MODE_SCORES)
10173         HandleHallOfFame(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10174       break;
10175
10176     case SCREEN_CTRL_ID_NETWORK_SERVER:
10177     {
10178       if (!strEqual(gi->textinput.value, ""))
10179       {
10180         setString(&setup.network_server_hostname, gi->textinput.value);
10181
10182         network.server_host = setup.network_server_hostname;
10183       }
10184       else
10185       {
10186         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
10187
10188         network.server_host = NULL;
10189       }
10190
10191       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
10192         network.server_host = NULL;
10193
10194       execSetupGame_setNetworkServerText();
10195
10196       DrawSetupScreen();
10197
10198       break;
10199     }
10200
10201     default:
10202       break;
10203   }
10204 }
10205
10206 void HandleScreenGadgetKeys(Key key)
10207 {
10208   if (key == setup.shortcut.tape_play)
10209     HandleScreenGadgets(screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE]);
10210 }
10211
10212 void DumpScreenIdentifiers(void)
10213 {
10214   int i;
10215
10216   Print("Active screen elements on current screen:\n");
10217
10218   for (i = 0; main_controls[i].nr != -1; i++)
10219   {
10220     struct MainControlInfo *mci = &main_controls[i];
10221
10222     if (mci->button_graphic != -1)
10223     {
10224       char *token = getTokenFromImageID(mci->button_graphic);
10225
10226       Print("- '%s'\n", token);
10227     }
10228   }
10229
10230   Print("Done.\n");
10231 }
10232
10233 boolean DoScreenAction(int image_id)
10234 {
10235   int i;
10236
10237   if (game_status != GAME_MODE_MAIN)
10238     return FALSE;
10239
10240   for (i = 0; main_controls[i].nr != -1; i++)
10241   {
10242     struct MainControlInfo *mci = &main_controls[i];
10243     struct MenuPosInfo *pos = mci->pos_button;
10244
10245     if (mci->button_graphic == image_id)
10246     {
10247       int x = mSX + pos->x;
10248       int y = mSY + pos->y;
10249
10250       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
10251
10252       return TRUE;
10253     }
10254   }
10255
10256   return FALSE;
10257 }
10258
10259 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
10260 {
10261   // get tree info node of newly added level or artwork set
10262   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
10263   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
10264                                                       tree_subdir_new);
10265   if (tree_node_new == NULL)    // should not happen
10266     return;
10267
10268   // if request dialog is active, do nothing
10269   if (game.request_active)
10270     return;
10271
10272   if (game_status == GAME_MODE_MAIN &&
10273       tree_type == TREE_TYPE_LEVEL_DIR)
10274   {
10275     // when adding new level set in main menu, select it as current level set
10276
10277     // change current level set to newly added level set from zip file
10278     leveldir_current = tree_node_new;
10279
10280     // change current level number to first level of newly added level set
10281     level_nr = leveldir_current->first_level;
10282
10283     // redraw screen to reflect changed level set
10284     DrawMainMenu();
10285
10286     // save this level set and level number as last selected level set
10287     SaveLevelSetup_LastSeries();
10288     SaveLevelSetup_SeriesInfo();
10289   }
10290   else if (game_status == GAME_MODE_LEVELS &&
10291            tree_type == TREE_TYPE_LEVEL_DIR)
10292   {
10293     // when adding new level set in level set menu, set cursor and update screen
10294
10295     leveldir_current = tree_node_new;
10296
10297     DrawChooseTree(&leveldir_current);
10298   }
10299   else if (game_status == GAME_MODE_SETUP)
10300   {
10301     // when adding new artwork set in setup menu, set cursor and update screen
10302
10303     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
10304         tree_type == TREE_TYPE_GRAPHICS_DIR)
10305     {
10306       artwork.gfx_current = tree_node_new;
10307
10308       DrawChooseTree(&artwork.gfx_current);
10309     }
10310     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
10311              tree_type == TREE_TYPE_SOUNDS_DIR)
10312     {
10313       artwork.snd_current = tree_node_new;
10314
10315       DrawChooseTree(&artwork.snd_current);
10316     }
10317     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
10318              tree_type == TREE_TYPE_MUSIC_DIR)
10319     {
10320       artwork.mus_current = tree_node_new;
10321
10322       DrawChooseTree(&artwork.mus_current);
10323     }
10324   }
10325 }
10326
10327 static int UploadTapes(void)
10328 {
10329   SetGameStatus(GAME_MODE_LOADING);
10330
10331   FadeSetEnterScreen();
10332   FadeOut(REDRAW_ALL);
10333
10334   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
10335
10336   FadeIn(REDRAW_ALL);
10337
10338   DrawInitTextHead("Uploading tapes");
10339
10340   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
10341   global.autoplay_leveldir = "ALL";
10342   global.autoplay_all = TRUE;
10343
10344   int num_tapes_uploaded = AutoPlayTapes();
10345
10346   global.autoplay_mode = AUTOPLAY_MODE_NONE;
10347   global.autoplay_leveldir = NULL;
10348   global.autoplay_all = FALSE;
10349
10350   SetGameStatus(GAME_MODE_MAIN);
10351
10352   DrawMainMenu();
10353
10354   return num_tapes_uploaded;
10355 }
10356
10357 static boolean OfferUploadTapes(void)
10358 {
10359   if (!Request(setup.has_remaining_tapes ?
10360                "Upload missing tapes to the high score server now?" :
10361                "Upload all your tapes to the high score server now?", REQ_ASK))
10362     return FALSE;
10363
10364   // when uploading tapes, make sure that high score server is enabled
10365   runtime.use_api_server = setup.use_api_server = TRUE;
10366
10367   int num_tapes_uploaded = UploadTapes();
10368   char message[100];
10369
10370   if (num_tapes_uploaded < 0)
10371   {
10372     num_tapes_uploaded = -num_tapes_uploaded - 1;
10373
10374     if (num_tapes_uploaded == 0)
10375       sprintf(message, "Upload failed! No tapes uploaded!");
10376     else if (num_tapes_uploaded == 1)
10377       sprintf(message, "Upload failed! Only 1 tape uploaded!");
10378     else
10379       sprintf(message, "Upload failed! Only %d tapes uploaded!",
10380               num_tapes_uploaded);
10381
10382     Request(message, REQ_CONFIRM);
10383
10384     // if uploading tapes failed, add tape upload entry to setup menu
10385     setup.provide_uploading_tapes = TRUE;
10386     setup.has_remaining_tapes = TRUE;
10387
10388     SaveSetup_ServerSetup();
10389
10390     return FALSE;
10391   }
10392
10393   if (num_tapes_uploaded == 0)
10394     sprintf(message, "No tapes uploaded!");
10395   else if (num_tapes_uploaded == 1)
10396     sprintf(message, "1 tape uploaded!");
10397   else
10398     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
10399
10400   Request(message, REQ_CONFIRM);
10401
10402   if (num_tapes_uploaded > 0)
10403     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
10404
10405   // after all tapes have been uploaded, remove entry from setup menu
10406   setup.provide_uploading_tapes = FALSE;
10407   setup.has_remaining_tapes = FALSE;
10408
10409   SaveSetup_ServerSetup();
10410
10411   return TRUE;
10412 }
10413
10414 static void CheckUploadTapes(void)
10415 {
10416   if (!setup.ask_for_uploading_tapes)
10417     return;
10418
10419   // after asking for uploading tapes, do not ask again
10420   setup.ask_for_uploading_tapes = FALSE;
10421   setup.ask_for_remaining_tapes = FALSE;
10422
10423   if (directoryExists(getTapeDir(NULL)))
10424   {
10425     boolean tapes_uploaded = OfferUploadTapes();
10426
10427     if (!tapes_uploaded)
10428     {
10429       Request(setup.has_remaining_tapes ?
10430               "You can upload missing tapes from the setup menu later!" :
10431               "You can upload your tapes from the setup menu later!",
10432               REQ_CONFIRM);
10433     }
10434   }
10435   else
10436   {
10437     // if tapes directory does not exist yet, never offer uploading all tapes
10438     setup.provide_uploading_tapes = FALSE;
10439   }
10440
10441   SaveSetup_ServerSetup();
10442 }
10443
10444 static void UpgradePlayerUUID(void)
10445 {
10446   ApiResetUUIDAsThread(getUUID());
10447 }
10448
10449 static void CheckUpgradePlayerUUID(void)
10450 {
10451   if (setup.player_version > 1)
10452     return;
10453
10454   UpgradePlayerUUID();
10455 }
10456
10457 void CheckApiServerTasks(void)
10458 {
10459   // check if the player's UUID has to be upgraded
10460   CheckUpgradePlayerUUID();
10461
10462   // check if there are any tapes to be uploaded
10463   CheckUploadTapes();
10464 }