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