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