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