048359fe13c54e0ed4b59a0dfd9938651bb544fa
[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);
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   int font_width = getFontWidth(font_text);
5378   int font_height = getFontHeight(font_text);
5379   int tape_date_width  = getTextWidth(entry->tape_date, font_text);
5380   int pad_left = xstart2;
5381   int pad_right = MENU_SCREEN_INFO_SPACE_RIGHT;
5382   int max_chars_per_line = (SXSIZE - pad_left - pad_right) / font_width;
5383   int max_lines_per_text = 5;
5384   int lines;
5385
5386   ClearField();
5387
5388   // redraw score selection buttons (which have just been erased)
5389   RedrawScreenMenuGadgets(SCREEN_MASK_SCORES);
5390
5391   if (score_entries == NULL)
5392   {
5393     drawChooseTreeScreen_Scores_NotAvailable();
5394
5395     return;
5396   }
5397
5398   drawChooseTreeHead(score_entries);
5399   drawChooseTreeInfo(score_entries);
5400
5401   DrawTextSCentered(ystart, font_title, "Score Information:");
5402   ystart += ystep_title;
5403
5404   DrawTextF(xstart1, ystart, font_head, "Level Set");
5405   lines = DrawTextBufferS(xstart2, ystart, leveldir_current->name, font_text,
5406                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5407                           TRUE, FALSE, FALSE);
5408   ystart += ystep_line + (lines > 0 ? lines - 1 : 0) * font_height;
5409
5410   DrawTextF(xstart1, ystart, font_head, "Level");
5411   lines = DrawTextBufferS(xstart2, ystart, level.name, font_text,
5412                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5413                           TRUE, FALSE, FALSE);
5414   ystart += ystep_para + (lines > 0 ? lines - 1 : 0) * font_height;
5415
5416   select_y1 = SY + ystart;
5417   ystart += graphic_info[IMG_MENU_BUTTON_PREV_SCORE].height;
5418
5419   DrawTextF(xstart1, ystart, font_head, "Rank");
5420   DrawTextF(xstart2, ystart, font_text, pos_text);
5421   ystart += ystep_line;
5422
5423   DrawTextF(xstart1, ystart, font_head, "Player");
5424   DrawTextF(xstart2, ystart, font_text, entry->name);
5425   ystart += ystep_line;
5426
5427   if (level.use_step_counter)
5428   {
5429     DrawTextF(xstart1, ystart, font_head, "Steps");
5430     DrawTextF(xstart2, ystart, font_text, int2str(entry->time, 5));
5431     ystart += ystep_line;
5432   }
5433   else
5434   {
5435     DrawTextF(xstart1, ystart, font_head, "Time");
5436     DrawTextF(xstart2, ystart, font_text, getHallOfFameTimeText(entry_nr));
5437     ystart += ystep_line;
5438   }
5439
5440   if (!level.rate_time_over_score || entry->score > 0)
5441   {
5442     DrawTextF(xstart1, ystart, font_head, "Score");
5443     DrawTextF(xstart2, ystart, font_text, int2str(entry->score, 5));
5444     ystart += ystep_line;
5445   }
5446
5447   ystart += ystep_line;
5448
5449   play_x = SX + xstart2 + tape_date_width + font_width;
5450   play_y = SY + ystart + (font_height - play_height) / 2;
5451
5452   DrawTextF(xstart1, ystart, font_head, "Tape Date");
5453   DrawTextF(xstart2, ystart, font_text, entry->tape_date);
5454   ystart += ystep_line;
5455
5456   DrawTextF(xstart1, ystart, font_head, "Platform");
5457   DrawTextF(xstart2, ystart, font_text, entry->platform);
5458   ystart += ystep_line;
5459
5460   DrawTextF(xstart1, ystart, font_head, "Version");
5461   DrawTextF(xstart2, ystart, font_text, entry->version);
5462   ystart += ystep_line;
5463
5464   DrawTextF(xstart1, ystart, font_head, "Country");
5465   lines = DrawTextBufferS(xstart2, ystart, entry->country_name, font_text,
5466                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5467                           TRUE, FALSE, FALSE);
5468   ystart += ystep_line;
5469
5470   select_y2 = SY + ystart;
5471
5472   DrawTextSCentered(ybottom, font_foot, "Press any key or button to go back");
5473
5474   AdjustScoreInfoButtons_SelectScore(select_x, select_y1, select_y2);
5475   AdjustScoreInfoButtons_PlayTape(play_x, play_y);
5476 }
5477
5478 static void DrawScoreInfo(int entry_nr)
5479 {
5480   scores.last_entry_nr = entry_nr;
5481
5482   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_SCOREINFO);
5483
5484   UnmapAllGadgets();
5485
5486   FadeOut(REDRAW_FIELD);
5487
5488   DrawScoreInfo_Content(entry_nr);
5489
5490   // map gadgets for score info screen
5491   MapScreenMenuGadgets(SCREEN_MASK_SCORES_INFO);
5492
5493   FadeIn(REDRAW_FIELD);
5494 }
5495
5496 static void HandleScoreInfo_SelectScore(int step, int direction)
5497 {
5498   int old_entry_nr = scores.last_entry_nr;
5499   int new_entry_nr = old_entry_nr + step * direction;
5500   int num_nodes = numTreeInfoInGroup(score_entry_current);
5501   int num_entries = num_nodes - 1;      // score nodes only, without back link
5502
5503   if (new_entry_nr < 0)
5504     new_entry_nr = 0;
5505   if (new_entry_nr > num_entries - 1)
5506     new_entry_nr = num_entries - 1;
5507
5508   if (new_entry_nr != old_entry_nr)
5509   {
5510     scores.last_entry_nr = new_entry_nr;
5511
5512     DrawScoreInfo_Content(new_entry_nr);
5513   }
5514 }
5515
5516 static void HandleScoreInfo_PlayTape(void)
5517 {
5518 }
5519
5520 void HandleScoreInfo(int mx, int my, int dx, int dy, int button)
5521 {
5522   boolean button_action = (button == MB_MENU_LEAVE || button == MB_MENU_CHOICE);
5523   boolean button_is_valid = (mx >= 0 && my >= 0);
5524   boolean button_screen_clicked = (button_action && button_is_valid);
5525
5526   if (server_scores.updated)
5527   {
5528     // reload scores, using updated server score cache file
5529     LoadLocalAndServerScore(scores.last_level_nr, FALSE);
5530
5531     server_scores.updated = FALSE;
5532
5533     DrawHallOfFame_setScoreEntries();
5534
5535     DrawScoreInfo_Content(scores.last_entry_nr);
5536   }
5537
5538   if (button_screen_clicked)
5539   {
5540     PlaySound(SND_MENU_ITEM_SELECTING);
5541
5542     SetGameStatus(GAME_MODE_SCORES);
5543
5544     DrawHallOfFame(level_nr);
5545   }
5546   else if (dx)
5547   {
5548     HandleHallOfFame_SelectLevel(1, SIGN(dx) * (ABS(dx) > 1 ? 10 : 1));
5549   }
5550   else if (dy)
5551   {
5552     HandleScoreInfo_SelectScore(1, SIGN(dy) * (ABS(dy) > 1 ? 10 : 1));
5553   }
5554 }
5555
5556
5557 // ============================================================================
5558 // setup screen functions
5559 // ============================================================================
5560
5561 static struct TokenInfo *setup_info;
5562 static int num_setup_info;      // number of setup entries shown on screen
5563 static int max_setup_info;      // total number of setup entries in list
5564
5565 static char *window_size_text;
5566 static char *scaling_type_text;
5567 static char *rendering_mode_text;
5568 static char *vsync_mode_text;
5569 static char *scroll_delay_text;
5570 static char *snapshot_mode_text;
5571 static char *game_speed_text;
5572 static char *scores_type_text;
5573 static char *network_server_text;
5574 static char *graphics_set_name;
5575 static char *sounds_set_name;
5576 static char *music_set_name;
5577 static char *volume_simple_text;
5578 static char *volume_loops_text;
5579 static char *volume_music_text;
5580 static char *touch_controls_text;
5581 static char *move_distance_text;
5582 static char *drop_distance_text;
5583 static char *transparency_text;
5584 static char *grid_size_text[2][2];
5585
5586 static void execSetupMain(void)
5587 {
5588   setup_mode = SETUP_MODE_MAIN;
5589
5590   DrawSetupScreen();
5591 }
5592
5593 static void execSetupGame_setScoresType(void)
5594 {
5595   if (scores_types == NULL)
5596   {
5597     int i;
5598
5599     for (i = 0; scores_types_list[i].value != NULL; i++)
5600     {
5601       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5602       char identifier[32], name[32];
5603       char *value = scores_types_list[i].value;
5604       char *text = scores_types_list[i].text;
5605
5606       ti->node_top = &scores_types;
5607       ti->sort_priority = i;
5608
5609       sprintf(identifier, "%s", value);
5610       sprintf(name, "%s", text);
5611
5612       setString(&ti->identifier, identifier);
5613       setString(&ti->name, name);
5614       setString(&ti->name_sorting, name);
5615       setString(&ti->infotext, STR_SETUP_CHOOSE_SCORES_TYPE);
5616
5617       pushTreeInfo(&scores_types, ti);
5618     }
5619
5620     // sort scores type values to start with lowest scores type value
5621     sortTreeInfo(&scores_types);
5622
5623     // set current scores type value to configured scores type value
5624     scores_type_current =
5625       getTreeInfoFromIdentifier(scores_types, setup.scores_in_highscore_list);
5626
5627     // if that fails, set current scores type to reliable default value
5628     if (scores_type_current == NULL)
5629       scores_type_current =
5630         getTreeInfoFromIdentifier(scores_types, STR_SCORES_TYPE_DEFAULT);
5631
5632     // if that also fails, set current scores type to first available value
5633     if (scores_type_current == NULL)
5634       scores_type_current = scores_types;
5635   }
5636
5637   setup.scores_in_highscore_list = scores_type_current->identifier;
5638
5639   // needed for displaying scores type text instead of identifier
5640   scores_type_text = scores_type_current->name;
5641 }
5642
5643 static void execSetupGame_setGameSpeeds(boolean update_value)
5644 {
5645   if (setup.game_speed_extended)
5646   {
5647     game_speeds_list = game_speeds_list_extended;
5648     game_speeds      = game_speeds_extended;
5649   }
5650   else
5651   {
5652     game_speeds_list = game_speeds_list_normal;
5653     game_speeds      = game_speeds_normal;
5654   }
5655
5656   if (game_speeds == NULL)
5657   {
5658     int i;
5659
5660     for (i = 0; game_speeds_list[i].value != -1; i++)
5661     {
5662       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5663       char identifier[32], name[32];
5664       int value = game_speeds_list[i].value;
5665       char *text = game_speeds_list[i].text;
5666
5667       ti->node_top = &game_speeds;
5668       ti->sort_priority = 10000 - value;
5669
5670       sprintf(identifier, "%d", value);
5671       sprintf(name, "%s", text);
5672
5673       setString(&ti->identifier, identifier);
5674       setString(&ti->name, name);
5675       setString(&ti->name_sorting, name);
5676       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_SPEED);
5677
5678       pushTreeInfo(&game_speeds, ti);
5679     }
5680
5681     // sort game speed values to start with slowest game speed
5682     sortTreeInfo(&game_speeds);
5683
5684     update_value = TRUE;
5685   }
5686
5687   if (update_value)
5688   {
5689     // set current game speed to configured game speed value
5690     game_speed_current =
5691       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
5692
5693     // if that fails, set current game speed to reliable default value
5694     if (game_speed_current == NULL)
5695       game_speed_current =
5696         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
5697
5698     // if that also fails, set current game speed to first available speed
5699     if (game_speed_current == NULL)
5700       game_speed_current = game_speeds;
5701
5702     if (setup.game_speed_extended)
5703       game_speeds_extended = game_speeds;
5704     else
5705       game_speeds_normal = game_speeds;
5706   }
5707
5708   setup.game_frame_delay = atoi(game_speed_current->identifier);
5709
5710   // needed for displaying game speed text instead of identifier
5711   game_speed_text = game_speed_current->name;
5712 }
5713
5714 static void execSetupGame_setScrollDelays(void)
5715 {
5716   if (scroll_delays == NULL)
5717   {
5718     int i;
5719
5720     for (i = 0; scroll_delays_list[i].value != -1; i++)
5721     {
5722       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5723       char identifier[32], name[32];
5724       int value = scroll_delays_list[i].value;
5725       char *text = scroll_delays_list[i].text;
5726
5727       ti->node_top = &scroll_delays;
5728       ti->sort_priority = value;
5729
5730       sprintf(identifier, "%d", value);
5731       sprintf(name, "%s", text);
5732
5733       setString(&ti->identifier, identifier);
5734       setString(&ti->name, name);
5735       setString(&ti->name_sorting, name);
5736       setString(&ti->infotext, STR_SETUP_CHOOSE_SCROLL_DELAY);
5737
5738       pushTreeInfo(&scroll_delays, ti);
5739     }
5740
5741     // sort scroll delay values to start with lowest scroll delay value
5742     sortTreeInfo(&scroll_delays);
5743
5744     // set current scroll delay value to configured scroll delay value
5745     scroll_delay_current =
5746       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
5747
5748     // if that fails, set current scroll delay to reliable default value
5749     if (scroll_delay_current == NULL)
5750       scroll_delay_current =
5751         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
5752
5753     // if that also fails, set current scroll delay to first available value
5754     if (scroll_delay_current == NULL)
5755       scroll_delay_current = scroll_delays;
5756   }
5757
5758   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
5759
5760   // needed for displaying scroll delay text instead of identifier
5761   scroll_delay_text = scroll_delay_current->name;
5762 }
5763
5764 static void execSetupGame_setSnapshotModes(void)
5765 {
5766   if (snapshot_modes == NULL)
5767   {
5768     int i;
5769
5770     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
5771     {
5772       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5773       char identifier[32], name[32];
5774       char *value = snapshot_modes_list[i].value;
5775       char *text = snapshot_modes_list[i].text;
5776
5777       ti->node_top = &snapshot_modes;
5778       ti->sort_priority = i;
5779
5780       sprintf(identifier, "%s", value);
5781       sprintf(name, "%s", text);
5782
5783       setString(&ti->identifier, identifier);
5784       setString(&ti->name, name);
5785       setString(&ti->name_sorting, name);
5786       setString(&ti->infotext, STR_SETUP_CHOOSE_SNAPSHOT_MODE);
5787
5788       pushTreeInfo(&snapshot_modes, ti);
5789     }
5790
5791     // sort snapshot mode values to start with lowest snapshot mode value
5792     sortTreeInfo(&snapshot_modes);
5793
5794     // set current snapshot mode value to configured snapshot mode value
5795     snapshot_mode_current =
5796       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
5797
5798     // if that fails, set current snapshot mode to reliable default value
5799     if (snapshot_mode_current == NULL)
5800       snapshot_mode_current =
5801         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
5802
5803     // if that also fails, set current snapshot mode to first available value
5804     if (snapshot_mode_current == NULL)
5805       snapshot_mode_current = snapshot_modes;
5806   }
5807
5808   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
5809
5810   // needed for displaying snapshot mode text instead of identifier
5811   snapshot_mode_text = snapshot_mode_current->name;
5812 }
5813
5814 static void execSetupGame_setNetworkServerText(void)
5815 {
5816   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
5817   {
5818     strcpy(network_server_hostname, STR_NETWORK_AUTO_DETECT_SETUP);
5819   }
5820   else
5821   {
5822     strncpy(network_server_hostname, setup.network_server_hostname,
5823             MAX_SETUP_TEXT_INPUT_LEN);
5824     network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN] = '\0';
5825   }
5826
5827   // needed for displaying network server text instead of identifier
5828   network_server_text = network_server_hostname;
5829 }
5830
5831 static void execSetupGame(void)
5832 {
5833   boolean check_vsync_mode = (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED);
5834
5835   execSetupGame_setGameSpeeds(FALSE);
5836   execSetupGame_setScoresType();
5837   execSetupGame_setScrollDelays();
5838   execSetupGame_setSnapshotModes();
5839
5840   execSetupGame_setNetworkServerText();
5841
5842   if (!setup.provide_uploading_tapes)
5843     setHideSetupEntry(execOfferUploadTapes);
5844
5845   setup_mode = SETUP_MODE_GAME;
5846
5847   DrawSetupScreen();
5848
5849   // check if vsync needs to be disabled for this game speed to work
5850   if (check_vsync_mode)
5851     DisableVsyncIfNeeded();
5852 }
5853
5854 static void execSetupChooseScoresType(void)
5855 {
5856   setup_mode = SETUP_MODE_CHOOSE_SCORES_TYPE;
5857
5858   DrawSetupScreen();
5859 }
5860
5861 static void execSetupChooseGameSpeed(void)
5862 {
5863   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
5864
5865   DrawSetupScreen();
5866 }
5867
5868 static void execSetupChooseScrollDelay(void)
5869 {
5870   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
5871
5872   DrawSetupScreen();
5873 }
5874
5875 static void execSetupChooseSnapshotMode(void)
5876 {
5877   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
5878
5879   DrawSetupScreen();
5880 }
5881
5882 static void execSetupEngines(void)
5883 {
5884   setup_mode = SETUP_MODE_ENGINES;
5885
5886   DrawSetupScreen();
5887 }
5888
5889 static void execSetupEditor(void)
5890 {
5891   setup_mode = SETUP_MODE_EDITOR;
5892
5893   DrawSetupScreen();
5894 }
5895
5896 static void execSetupGraphics_setWindowSizes(boolean update_list)
5897 {
5898   if (window_sizes != NULL && update_list)
5899   {
5900     freeTreeInfo(window_sizes);
5901
5902     window_sizes = NULL;
5903   }
5904
5905   if (window_sizes == NULL)
5906   {
5907     boolean current_window_size_found = FALSE;
5908     int i;
5909
5910     for (i = 0; window_sizes_list[i].value != -1; i++)
5911     {
5912       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5913       char identifier[32], name[32];
5914       int value = window_sizes_list[i].value;
5915       char *text = window_sizes_list[i].text;
5916
5917       ti->node_top = &window_sizes;
5918       ti->sort_priority = value;
5919
5920       sprintf(identifier, "%d", value);
5921       sprintf(name, "%s", text);
5922
5923       setString(&ti->identifier, identifier);
5924       setString(&ti->name, name);
5925       setString(&ti->name_sorting, name);
5926       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
5927
5928       pushTreeInfo(&window_sizes, ti);
5929
5930       if (value == setup.window_scaling_percent)
5931         current_window_size_found = TRUE;
5932     }
5933
5934     if (!current_window_size_found)
5935     {
5936       // add entry for non-preset window scaling value
5937
5938       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5939       char identifier[32], name[32];
5940       int value = setup.window_scaling_percent;
5941
5942       ti->node_top = &window_sizes;
5943       ti->sort_priority = value;
5944
5945       sprintf(identifier, "%d", value);
5946       sprintf(name, "%d %% (Current)", value);
5947
5948       setString(&ti->identifier, identifier);
5949       setString(&ti->name, name);
5950       setString(&ti->name_sorting, name);
5951       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
5952
5953       pushTreeInfo(&window_sizes, ti);
5954     }
5955
5956     // sort window size values to start with lowest window size value
5957     sortTreeInfo(&window_sizes);
5958
5959     // set current window size value to configured window size value
5960     window_size_current =
5961       getTreeInfoFromIdentifier(window_sizes,
5962                                 i_to_a(setup.window_scaling_percent));
5963
5964     // if that fails, set current window size to reliable default value
5965     if (window_size_current == NULL)
5966       window_size_current =
5967         getTreeInfoFromIdentifier(window_sizes,
5968                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
5969
5970     // if that also fails, set current window size to first available value
5971     if (window_size_current == NULL)
5972       window_size_current = window_sizes;
5973   }
5974
5975   setup.window_scaling_percent = atoi(window_size_current->identifier);
5976
5977   // needed for displaying window size text instead of identifier
5978   window_size_text = window_size_current->name;
5979 }
5980
5981 static void execSetupGraphics_setScalingTypes(void)
5982 {
5983   if (scaling_types == NULL)
5984   {
5985     int i;
5986
5987     for (i = 0; scaling_types_list[i].value != NULL; i++)
5988     {
5989       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5990       char identifier[32], name[32];
5991       char *value = scaling_types_list[i].value;
5992       char *text = scaling_types_list[i].text;
5993
5994       ti->node_top = &scaling_types;
5995       ti->sort_priority = i;
5996
5997       sprintf(identifier, "%s", value);
5998       sprintf(name, "%s", text);
5999
6000       setString(&ti->identifier, identifier);
6001       setString(&ti->name, name);
6002       setString(&ti->name_sorting, name);
6003       setString(&ti->infotext, STR_SETUP_CHOOSE_SCALING_TYPE);
6004
6005       pushTreeInfo(&scaling_types, ti);
6006     }
6007
6008     // sort scaling type values to start with lowest scaling type value
6009     sortTreeInfo(&scaling_types);
6010
6011     // set current scaling type value to configured scaling type value
6012     scaling_type_current =
6013       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
6014
6015     // if that fails, set current scaling type to reliable default value
6016     if (scaling_type_current == NULL)
6017       scaling_type_current =
6018         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
6019
6020     // if that also fails, set current scaling type to first available value
6021     if (scaling_type_current == NULL)
6022       scaling_type_current = scaling_types;
6023   }
6024
6025   setup.window_scaling_quality = scaling_type_current->identifier;
6026
6027   // needed for displaying scaling type text instead of identifier
6028   scaling_type_text = scaling_type_current->name;
6029 }
6030
6031 static void execSetupGraphics_setRenderingModes(void)
6032 {
6033   if (rendering_modes == NULL)
6034   {
6035     int i;
6036
6037     for (i = 0; rendering_modes_list[i].value != NULL; i++)
6038     {
6039       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6040       char identifier[32], name[32];
6041       char *value = rendering_modes_list[i].value;
6042       char *text = rendering_modes_list[i].text;
6043
6044       ti->node_top = &rendering_modes;
6045       ti->sort_priority = i;
6046
6047       sprintf(identifier, "%s", value);
6048       sprintf(name, "%s", text);
6049
6050       setString(&ti->identifier, identifier);
6051       setString(&ti->name, name);
6052       setString(&ti->name_sorting, name);
6053       setString(&ti->infotext, STR_SETUP_CHOOSE_RENDERING);
6054
6055       pushTreeInfo(&rendering_modes, ti);
6056     }
6057
6058     // sort rendering mode values to start with lowest rendering mode value
6059     sortTreeInfo(&rendering_modes);
6060
6061     // set current rendering mode value to configured rendering mode value
6062     rendering_mode_current =
6063       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
6064
6065     // if that fails, set current rendering mode to reliable default value
6066     if (rendering_mode_current == NULL)
6067       rendering_mode_current =
6068         getTreeInfoFromIdentifier(rendering_modes,
6069                                   STR_SPECIAL_RENDERING_DEFAULT);
6070
6071     // if that also fails, set current rendering mode to first available one
6072     if (rendering_mode_current == NULL)
6073       rendering_mode_current = rendering_modes;
6074   }
6075
6076   setup.screen_rendering_mode = rendering_mode_current->identifier;
6077
6078   // needed for displaying rendering mode text instead of identifier
6079   rendering_mode_text = rendering_mode_current->name;
6080 }
6081
6082 static void execSetupGraphics_setVsyncModes(boolean update_value)
6083 {
6084   if (vsync_modes == NULL)
6085   {
6086     int i;
6087
6088     for (i = 0; vsync_modes_list[i].value != NULL; i++)
6089     {
6090       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6091       char identifier[32], name[32];
6092       char *value = vsync_modes_list[i].value;
6093       char *text = vsync_modes_list[i].text;
6094
6095       ti->node_top = &vsync_modes;
6096       ti->sort_priority = i;
6097
6098       sprintf(identifier, "%s", value);
6099       sprintf(name, "%s", text);
6100
6101       setString(&ti->identifier, identifier);
6102       setString(&ti->name, name);
6103       setString(&ti->name_sorting, name);
6104       setString(&ti->infotext, STR_SETUP_CHOOSE_VSYNC);
6105
6106       pushTreeInfo(&vsync_modes, ti);
6107     }
6108
6109     // sort vsync mode values to start with lowest vsync mode value
6110     sortTreeInfo(&vsync_modes);
6111
6112     update_value = TRUE;
6113   }
6114
6115   if (update_value)
6116   {
6117     // set current vsync mode value to configured vsync mode value
6118     vsync_mode_current =
6119       getTreeInfoFromIdentifier(vsync_modes, setup.vsync_mode);
6120
6121     // if that fails, set current vsync mode to reliable default value
6122     if (vsync_mode_current == NULL)
6123       vsync_mode_current =
6124         getTreeInfoFromIdentifier(vsync_modes, STR_VSYNC_MODE_DEFAULT);
6125
6126     // if that also fails, set current vsync mode to first available one
6127     if (vsync_mode_current == NULL)
6128       vsync_mode_current = vsync_modes;
6129   }
6130
6131   setup.vsync_mode = vsync_mode_current->identifier;
6132
6133   // needed for displaying vsync mode text instead of identifier
6134   vsync_mode_text = vsync_mode_current->name;
6135 }
6136
6137 static void execSetupGraphics(void)
6138 {
6139   boolean check_game_speed = (setup_mode == SETUP_MODE_CHOOSE_VSYNC);
6140
6141   // update "setup.window_scaling_percent" from list selection
6142   // (in this case, window scaling was changed on setup screen)
6143   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6144     execSetupGraphics_setWindowSizes(FALSE);
6145
6146   // update "setup.vsync_mode" from list selection
6147   // (in this case, vsync mode was changed on setup screen)
6148   if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
6149     execSetupGraphics_setVsyncModes(FALSE);
6150
6151   // update list selection from "setup.window_scaling_percent"
6152   // (window scaling may have changed by resizing the window)
6153   execSetupGraphics_setWindowSizes(TRUE);
6154
6155   // update list selection from "setup.vsync_mode"
6156   // (vsync_mode may have changed by re-creating the renderer)
6157   execSetupGraphics_setVsyncModes(TRUE);
6158
6159   execSetupGraphics_setScalingTypes();
6160   execSetupGraphics_setRenderingModes();
6161
6162   setup_mode = SETUP_MODE_GRAPHICS;
6163
6164   DrawSetupScreen();
6165
6166   // check if game speed is high enough for 60 Hz vsync to work
6167   if (check_game_speed)
6168     ModifyGameSpeedIfNeeded();
6169
6170   // window scaling may have changed at this point
6171   ChangeWindowScalingIfNeeded();
6172
6173   // window scaling quality may have changed at this point
6174   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
6175     SDLSetWindowScalingQuality(setup.window_scaling_quality);
6176
6177   // screen rendering mode may have changed at this point
6178   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
6179
6180   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
6181   int video_vsync_mode = video.vsync_mode;
6182
6183   // screen vsync mode may have changed at this point
6184   ChangeVsyncModeIfNeeded();
6185
6186   // check if setting vsync mode to selected value failed
6187   if (setup_vsync_mode != video_vsync_mode &&
6188       setup_vsync_mode != video.vsync_mode)
6189   {
6190     // changing vsync mode to selected value failed -- reset displayed value
6191     execSetupGraphics_setVsyncModes(TRUE);
6192
6193     Request("Setting VSync failed!", REQ_CONFIRM);
6194
6195     DrawSetupScreen();
6196   }
6197 }
6198
6199 static void execSetupChooseWindowSize(void)
6200 {
6201   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
6202
6203   DrawSetupScreen();
6204 }
6205
6206 static void execSetupChooseScalingType(void)
6207 {
6208   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
6209
6210   DrawSetupScreen();
6211 }
6212
6213 static void execSetupChooseRenderingMode(void)
6214 {
6215   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
6216
6217   DrawSetupScreen();
6218 }
6219
6220 static void execSetupChooseVsyncMode(void)
6221 {
6222   setup_mode = SETUP_MODE_CHOOSE_VSYNC;
6223
6224   DrawSetupScreen();
6225 }
6226
6227 static void execSetupChooseVolumeSimple(void)
6228 {
6229   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
6230
6231   DrawSetupScreen();
6232 }
6233
6234 static void execSetupChooseVolumeLoops(void)
6235 {
6236   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
6237
6238   DrawSetupScreen();
6239 }
6240
6241 static void execSetupChooseVolumeMusic(void)
6242 {
6243   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
6244
6245   DrawSetupScreen();
6246 }
6247
6248 static void execSetupSound(void)
6249 {
6250   if (volumes_simple == NULL)
6251   {
6252     boolean current_volume_simple_found = FALSE;
6253     int i;
6254
6255     for (i = 0; volumes_list[i].value != -1; i++)
6256     {
6257       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6258       char identifier[32], name[32];
6259       int value = volumes_list[i].value;
6260       char *text = volumes_list[i].text;
6261
6262       ti->node_top = &volumes_simple;
6263       ti->sort_priority = value;
6264
6265       sprintf(identifier, "%d", value);
6266       sprintf(name, "%s", text);
6267
6268       setString(&ti->identifier, identifier);
6269       setString(&ti->name, name);
6270       setString(&ti->name_sorting, name);
6271       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6272
6273       pushTreeInfo(&volumes_simple, ti);
6274
6275       if (value == setup.volume_simple)
6276         current_volume_simple_found = TRUE;
6277     }
6278
6279     if (!current_volume_simple_found)
6280     {
6281       // add entry for non-preset volume value
6282
6283       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6284       char identifier[32], name[32];
6285       int value = setup.volume_simple;
6286
6287       ti->node_top = &volumes_simple;
6288       ti->sort_priority = value;
6289
6290       sprintf(identifier, "%d", value);
6291       sprintf(name, "%d %% (Current)", value);
6292
6293       setString(&ti->identifier, identifier);
6294       setString(&ti->name, name);
6295       setString(&ti->name_sorting, name);
6296       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6297
6298       pushTreeInfo(&volumes_simple, ti);
6299     }
6300
6301     // sort volume values to start with lowest volume value
6302     sortTreeInfo(&volumes_simple);
6303
6304     // set current volume value to configured volume value
6305     volume_simple_current =
6306       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
6307
6308     // if that fails, set current volume to reliable default value
6309     if (volume_simple_current == NULL)
6310       volume_simple_current =
6311         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
6312
6313     // if that also fails, set current volume to first available value
6314     if (volume_simple_current == NULL)
6315       volume_simple_current = volumes_simple;
6316   }
6317
6318   if (volumes_loops == NULL)
6319   {
6320     boolean current_volume_loops_found = FALSE;
6321     int i;
6322
6323     for (i = 0; volumes_list[i].value != -1; i++)
6324     {
6325       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6326       char identifier[32], name[32];
6327       int value = volumes_list[i].value;
6328       char *text = volumes_list[i].text;
6329
6330       ti->node_top = &volumes_loops;
6331       ti->sort_priority = value;
6332
6333       sprintf(identifier, "%d", value);
6334       sprintf(name, "%s", text);
6335
6336       setString(&ti->identifier, identifier);
6337       setString(&ti->name, name);
6338       setString(&ti->name_sorting, name);
6339       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6340
6341       pushTreeInfo(&volumes_loops, ti);
6342
6343       if (value == setup.volume_loops)
6344         current_volume_loops_found = TRUE;
6345     }
6346
6347     if (!current_volume_loops_found)
6348     {
6349       // add entry for non-preset volume value
6350
6351       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6352       char identifier[32], name[32];
6353       int value = setup.volume_loops;
6354
6355       ti->node_top = &volumes_loops;
6356       ti->sort_priority = value;
6357
6358       sprintf(identifier, "%d", value);
6359       sprintf(name, "%d %% (Current)", value);
6360
6361       setString(&ti->identifier, identifier);
6362       setString(&ti->name, name);
6363       setString(&ti->name_sorting, name);
6364       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6365
6366       pushTreeInfo(&volumes_loops, ti);
6367     }
6368
6369     // sort volume values to start with lowest volume value
6370     sortTreeInfo(&volumes_loops);
6371
6372     // set current volume value to configured volume value
6373     volume_loops_current =
6374       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
6375
6376     // if that fails, set current volume to reliable default value
6377     if (volume_loops_current == NULL)
6378       volume_loops_current =
6379         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
6380
6381     // if that also fails, set current volume to first available value
6382     if (volume_loops_current == NULL)
6383       volume_loops_current = volumes_loops;
6384   }
6385
6386   if (volumes_music == NULL)
6387   {
6388     boolean current_volume_music_found = FALSE;
6389     int i;
6390
6391     for (i = 0; volumes_list[i].value != -1; i++)
6392     {
6393       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6394       char identifier[32], name[32];
6395       int value = volumes_list[i].value;
6396       char *text = volumes_list[i].text;
6397
6398       ti->node_top = &volumes_music;
6399       ti->sort_priority = value;
6400
6401       sprintf(identifier, "%d", value);
6402       sprintf(name, "%s", text);
6403
6404       setString(&ti->identifier, identifier);
6405       setString(&ti->name, name);
6406       setString(&ti->name_sorting, name);
6407       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6408
6409       pushTreeInfo(&volumes_music, ti);
6410
6411       if (value == setup.volume_music)
6412         current_volume_music_found = TRUE;
6413     }
6414
6415     if (!current_volume_music_found)
6416     {
6417       // add entry for non-preset volume value
6418
6419       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6420       char identifier[32], name[32];
6421       int value = setup.volume_music;
6422
6423       ti->node_top = &volumes_music;
6424       ti->sort_priority = value;
6425
6426       sprintf(identifier, "%d", value);
6427       sprintf(name, "%d %% (Current)", value);
6428
6429       setString(&ti->identifier, identifier);
6430       setString(&ti->name, name);
6431       setString(&ti->name_sorting, name);
6432       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6433
6434       pushTreeInfo(&volumes_music, ti);
6435     }
6436
6437     // sort volume values to start with lowest volume value
6438     sortTreeInfo(&volumes_music);
6439
6440     // set current volume value to configured volume value
6441     volume_music_current =
6442       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
6443
6444     // if that fails, set current volume to reliable default value
6445     if (volume_music_current == NULL)
6446       volume_music_current =
6447         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
6448
6449     // if that also fails, set current volume to first available value
6450     if (volume_music_current == NULL)
6451       volume_music_current = volumes_music;
6452   }
6453
6454   setup.volume_simple = atoi(volume_simple_current->identifier);
6455   setup.volume_loops  = atoi(volume_loops_current->identifier);
6456   setup.volume_music  = atoi(volume_music_current->identifier);
6457
6458   // needed for displaying volume text instead of identifier
6459   volume_simple_text = volume_simple_current->name;
6460   volume_loops_text = volume_loops_current->name;
6461   volume_music_text = volume_music_current->name;
6462
6463   setup_mode = SETUP_MODE_SOUND;
6464
6465   DrawSetupScreen();
6466 }
6467
6468 static void execSetupChooseTouchControls(void)
6469 {
6470   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
6471
6472   DrawSetupScreen();
6473 }
6474
6475 static void execSetupChooseMoveDistance(void)
6476 {
6477   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
6478
6479   DrawSetupScreen();
6480 }
6481
6482 static void execSetupChooseDropDistance(void)
6483 {
6484   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
6485
6486   DrawSetupScreen();
6487 }
6488
6489 static void execSetupChooseTransparency(void)
6490 {
6491   setup_mode = SETUP_MODE_CHOOSE_TRANSPARENCY;
6492
6493   DrawSetupScreen();
6494 }
6495
6496 static void execSetupChooseGridXSize_0(void)
6497 {
6498   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_0;
6499
6500   DrawSetupScreen();
6501 }
6502
6503 static void execSetupChooseGridYSize_0(void)
6504 {
6505   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_0;
6506
6507   DrawSetupScreen();
6508 }
6509
6510 static void execSetupChooseGridXSize_1(void)
6511 {
6512   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_1;
6513
6514   DrawSetupScreen();
6515 }
6516
6517 static void execSetupChooseGridYSize_1(void)
6518 {
6519   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_1;
6520
6521   DrawSetupScreen();
6522 }
6523
6524 static void execSetupConfigureVirtualButtons(void)
6525 {
6526   setup_mode = SETUP_MODE_CONFIG_VIRT_BUTTONS;
6527
6528   ConfigureVirtualButtons();
6529
6530   setup_mode = SETUP_MODE_TOUCH;
6531
6532   DrawSetupScreen();
6533 }
6534
6535 static void execSetupTouch(void)
6536 {
6537   int i, j, k;
6538
6539   if (touch_controls == NULL)
6540   {
6541     for (i = 0; touch_controls_list[i].value != NULL; i++)
6542     {
6543       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6544       char identifier[32], name[32];
6545       char *value = touch_controls_list[i].value;
6546       char *text = touch_controls_list[i].text;
6547
6548       ti->node_top = &touch_controls;
6549       ti->sort_priority = i;
6550
6551       sprintf(identifier, "%s", value);
6552       sprintf(name, "%s", text);
6553
6554       setString(&ti->identifier, identifier);
6555       setString(&ti->name, name);
6556       setString(&ti->name_sorting, name);
6557       setString(&ti->infotext, STR_SETUP_CHOOSE_TOUCH_CONTROL);
6558
6559       pushTreeInfo(&touch_controls, ti);
6560     }
6561
6562     // sort touch control values to start with lowest touch control value
6563     sortTreeInfo(&touch_controls);
6564
6565     // set current touch control value to configured touch control value
6566     touch_control_current =
6567       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
6568
6569     // if that fails, set current touch control to reliable default value
6570     if (touch_control_current == NULL)
6571       touch_control_current =
6572         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
6573
6574     // if that also fails, set current touch control to first available value
6575     if (touch_control_current == NULL)
6576       touch_control_current = touch_controls;
6577   }
6578
6579   if (move_distances == NULL)
6580   {
6581     for (i = 0; distances_list[i].value != -1; i++)
6582     {
6583       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6584       char identifier[32], name[32];
6585       int value = distances_list[i].value;
6586       char *text = distances_list[i].text;
6587
6588       ti->node_top = &move_distances;
6589       ti->sort_priority = value;
6590
6591       sprintf(identifier, "%d", value);
6592       sprintf(name, "%s", text);
6593
6594       setString(&ti->identifier, identifier);
6595       setString(&ti->name, name);
6596       setString(&ti->name_sorting, name);
6597       setString(&ti->infotext, STR_SETUP_CHOOSE_MOVE_DISTANCE);
6598
6599       pushTreeInfo(&move_distances, ti);
6600     }
6601
6602     // sort distance values to start with lowest distance value
6603     sortTreeInfo(&move_distances);
6604
6605     // set current distance value to configured distance value
6606     move_distance_current =
6607       getTreeInfoFromIdentifier(move_distances,
6608                                 i_to_a(setup.touch.move_distance));
6609
6610     // if that fails, set current distance to reliable default value
6611     if (move_distance_current == NULL)
6612       move_distance_current =
6613         getTreeInfoFromIdentifier(move_distances,
6614                                   i_to_a(TOUCH_MOVE_DISTANCE_DEFAULT));
6615
6616     // if that also fails, set current distance to first available value
6617     if (move_distance_current == NULL)
6618       move_distance_current = move_distances;
6619   }
6620
6621   if (drop_distances == NULL)
6622   {
6623     for (i = 0; distances_list[i].value != -1; i++)
6624     {
6625       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6626       char identifier[32], name[32];
6627       int value = distances_list[i].value;
6628       char *text = distances_list[i].text;
6629
6630       ti->node_top = &drop_distances;
6631       ti->sort_priority = value;
6632
6633       sprintf(identifier, "%d", value);
6634       sprintf(name, "%s", text);
6635
6636       setString(&ti->identifier, identifier);
6637       setString(&ti->name, name);
6638       setString(&ti->name_sorting, name);
6639       setString(&ti->infotext, STR_SETUP_CHOOSE_DROP_DISTANCE);
6640
6641       pushTreeInfo(&drop_distances, ti);
6642     }
6643
6644     // sort distance values to start with lowest distance value
6645     sortTreeInfo(&drop_distances);
6646
6647     // set current distance value to configured distance value
6648     drop_distance_current =
6649       getTreeInfoFromIdentifier(drop_distances,
6650                                 i_to_a(setup.touch.drop_distance));
6651
6652     // if that fails, set current distance to reliable default value
6653     if (drop_distance_current == NULL)
6654       drop_distance_current =
6655         getTreeInfoFromIdentifier(drop_distances,
6656                                   i_to_a(TOUCH_DROP_DISTANCE_DEFAULT));
6657
6658     // if that also fails, set current distance to first available value
6659     if (drop_distance_current == NULL)
6660       drop_distance_current = drop_distances;
6661   }
6662
6663   if (transparencies == NULL)
6664   {
6665     for (i = 0; transparencies_list[i].value != -1; i++)
6666     {
6667       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6668       char identifier[32], name[32];
6669       int value = transparencies_list[i].value;
6670       char *text = transparencies_list[i].text;
6671
6672       ti->node_top = &transparencies;
6673       ti->sort_priority = value;
6674
6675       sprintf(identifier, "%d", value);
6676       sprintf(name, "%s", text);
6677
6678       setString(&ti->identifier, identifier);
6679       setString(&ti->name, name);
6680       setString(&ti->name_sorting, name);
6681       setString(&ti->infotext, STR_SETUP_CHOOSE_TRANSPARENCY);
6682
6683       pushTreeInfo(&transparencies, ti);
6684     }
6685
6686     // sort transparency values to start with lowest transparency value
6687     sortTreeInfo(&transparencies);
6688
6689     // set current transparency value to configured transparency value
6690     transparency_current =
6691       getTreeInfoFromIdentifier(transparencies,
6692                                 i_to_a(setup.touch.transparency));
6693
6694     // if that fails, set current transparency to reliable default value
6695     if (transparency_current == NULL)
6696       transparency_current =
6697         getTreeInfoFromIdentifier(transparencies,
6698                                   i_to_a(TOUCH_TRANSPARENCY_DEFAULT));
6699
6700     // if that also fails, set current transparency to first available value
6701     if (transparency_current == NULL)
6702       transparency_current = transparencies;
6703   }
6704
6705   for (i = 0; i < 2; i++)
6706   {
6707     for (j = 0; j < 2; j++)
6708     {
6709       if (grid_sizes[i][j] == NULL)
6710       {
6711         for (k = 0; grid_sizes_list[k].value != -1; k++)
6712         {
6713           TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6714           char identifier[32], name[32];
6715           int value = grid_sizes_list[k].value;
6716           char *text = grid_sizes_list[k].text;
6717
6718           ti->node_top = &grid_sizes[i][j];
6719           ti->sort_priority = value;
6720
6721           sprintf(identifier, "%d", value);
6722           sprintf(name, "%s", text);
6723
6724           setString(&ti->identifier, identifier);
6725           setString(&ti->name, name);
6726           setString(&ti->name_sorting, name);
6727           setString(&ti->infotext,
6728                     (i == 0 ?
6729                      (j == 0 ?
6730                       STR_SETUP_CHOOSE_GRID_XSIZE_0 :
6731                       STR_SETUP_CHOOSE_GRID_YSIZE_0) :
6732                      (j == 0 ?
6733                       STR_SETUP_CHOOSE_GRID_XSIZE_1 :
6734                       STR_SETUP_CHOOSE_GRID_YSIZE_1)));
6735
6736           pushTreeInfo(&grid_sizes[i][j], ti);
6737         }
6738
6739         // sort grid size values to start with lowest grid size value
6740         sortTreeInfo(&grid_sizes[i][j]);
6741
6742         // set current grid size value to configured grid size value
6743         grid_size_current[i][j] =
6744           getTreeInfoFromIdentifier(grid_sizes[i][j],
6745                                     i_to_a(j == 0 ?
6746                                            setup.touch.grid_xsize[i] :
6747                                            setup.touch.grid_ysize[i]));
6748
6749         // if that fails, set current grid size to reliable default value
6750         if (grid_size_current[i][j] == NULL)
6751           grid_size_current[i][j] =
6752             getTreeInfoFromIdentifier(grid_sizes[i][j],
6753                                       i_to_a(j == 0 ?
6754                                              DEFAULT_GRID_XSIZE(i) :
6755                                              DEFAULT_GRID_YSIZE(i)));
6756
6757         // if that also fails, set current grid size to first available value
6758         if (grid_size_current[i][j] == NULL)
6759           grid_size_current[i][j] = grid_sizes[i][j];
6760       }
6761     }
6762   }
6763
6764   setup.touch.control_type = touch_control_current->identifier;
6765   setup.touch.move_distance = atoi(move_distance_current->identifier);
6766   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
6767   setup.touch.transparency = atoi(transparency_current->identifier);
6768
6769   for (i = 0; i < 2; i++)
6770   {
6771     setup.touch.grid_xsize[i] = atoi(grid_size_current[i][0]->identifier);
6772     setup.touch.grid_ysize[i] = atoi(grid_size_current[i][1]->identifier);
6773
6774     if (i == GRID_ACTIVE_NR())
6775     {
6776       overlay.grid_xsize = setup.touch.grid_xsize[i];
6777       overlay.grid_ysize = setup.touch.grid_ysize[i];
6778     }
6779   }
6780
6781   // needed for displaying value text instead of identifier
6782   touch_controls_text = touch_control_current->name;
6783   move_distance_text = move_distance_current->name;
6784   drop_distance_text = drop_distance_current->name;
6785   transparency_text = transparency_current->name;
6786
6787   for (i = 0; i < 2; i++)
6788     for (j = 0; j < 2; j++)
6789       grid_size_text[i][j] = grid_size_current[i][j]->name;
6790
6791   setup_mode = SETUP_MODE_TOUCH;
6792
6793   DrawSetupScreen();
6794 }
6795
6796 static void execSetupArtwork(void)
6797 {
6798   static ArtworkDirTree *gfx_last_valid = NULL;
6799   static ArtworkDirTree *snd_last_valid = NULL;
6800   static ArtworkDirTree *mus_last_valid = NULL;
6801
6802   // current artwork directory may be invalid (level group, parent link)
6803   if (!validLevelSeries(artwork.gfx_current))
6804     artwork.gfx_current = getFirstValidTreeInfoEntry(gfx_last_valid);
6805   if (!validLevelSeries(artwork.snd_current))
6806     artwork.snd_current = getFirstValidTreeInfoEntry(snd_last_valid);
6807   if (!validLevelSeries(artwork.mus_current))
6808     artwork.mus_current = getFirstValidTreeInfoEntry(mus_last_valid);
6809
6810   // store valid artwork directory information
6811   gfx_last_valid = artwork.gfx_current;
6812   snd_last_valid = artwork.snd_current;
6813   mus_last_valid = artwork.mus_current;
6814
6815 #if 0
6816   Debug("screens:execSetupArtwork", "'%s', '%s', '%s'",
6817         artwork.gfx_current->subdir,
6818         artwork.gfx_current->fullpath,
6819         artwork.gfx_current->basepath);
6820 #endif
6821
6822   setup.graphics_set = artwork.gfx_current->identifier;
6823   setup.sounds_set = artwork.snd_current->identifier;
6824   setup.music_set = artwork.mus_current->identifier;
6825
6826   // needed if last screen (setup choice) changed graphics, sounds or music
6827   ReloadCustomArtwork(0);
6828
6829   // needed for displaying artwork name instead of artwork identifier
6830   graphics_set_name = artwork.gfx_current->name;
6831   sounds_set_name = artwork.snd_current->name;
6832   music_set_name = artwork.mus_current->name;
6833
6834   setup_mode = SETUP_MODE_ARTWORK;
6835
6836   DrawSetupScreen();
6837 }
6838
6839 static void execSetupChooseGraphics(void)
6840 {
6841   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
6842
6843   DrawSetupScreen();
6844 }
6845
6846 static void execSetupChooseSounds(void)
6847 {
6848   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
6849
6850   DrawSetupScreen();
6851 }
6852
6853 static void execSetupChooseMusic(void)
6854 {
6855   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
6856
6857   DrawSetupScreen();
6858 }
6859
6860 static void execSetupInput(void)
6861 {
6862   setup_mode = SETUP_MODE_INPUT;
6863
6864   DrawSetupScreen();
6865 }
6866
6867 static void execSetupShortcuts(void)
6868 {
6869   setup_mode = SETUP_MODE_SHORTCUTS;
6870
6871   DrawSetupScreen();
6872 }
6873
6874 static void execSetupShortcuts1(void)
6875 {
6876   setup_mode = SETUP_MODE_SHORTCUTS_1;
6877
6878   DrawSetupScreen();
6879 }
6880
6881 static void execSetupShortcuts2(void)
6882 {
6883   setup_mode = SETUP_MODE_SHORTCUTS_2;
6884
6885   DrawSetupScreen();
6886 }
6887
6888 static void execSetupShortcuts3(void)
6889 {
6890   setup_mode = SETUP_MODE_SHORTCUTS_3;
6891
6892   DrawSetupScreen();
6893 }
6894
6895 static void execSetupShortcuts4(void)
6896 {
6897   setup_mode = SETUP_MODE_SHORTCUTS_4;
6898
6899   DrawSetupScreen();
6900 }
6901
6902 static void execSetupShortcuts5(void)
6903 {
6904   setup_mode = SETUP_MODE_SHORTCUTS_5;
6905
6906   DrawSetupScreen();
6907 }
6908
6909 static void execExitSetup(void)
6910 {
6911   SetGameStatus(GAME_MODE_MAIN);
6912
6913   DrawMainMenu();
6914 }
6915
6916 static void execSaveAndExitSetup(void)
6917 {
6918   SaveSetup();
6919   execExitSetup();
6920 }
6921
6922 static void execGadgetNetworkServer(void)
6923 {
6924   int gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
6925   struct GadgetInfo *gi = screen_gadget[gadget_id];
6926
6927   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
6928     network_server_hostname[0] = '\0';
6929
6930   ModifyGadget(gi, GDI_TEXT_VALUE, network_server_hostname, GDI_END);
6931
6932   MapGadget(gi);
6933
6934   ClickOnGadget(gi, MB_LEFTBUTTON);
6935 }
6936
6937 static void execOfferUploadTapes(void)
6938 {
6939   OfferUploadTapes();
6940 }
6941
6942 static void ToggleNetworkModeIfNeeded(void)
6943 {
6944   int font_title = FONT_TITLE_1;
6945   int font_foot = FC_BLUE;
6946   int ystart  = mSY - SY + 16;
6947   int ybottom = mSY - SY + SYSIZE - 20;
6948   char *text = (setup.network_mode ? "Start Network" : "Stop Network");
6949
6950   if (setup.network_mode == network.enabled)
6951     return;
6952
6953   network.enabled = setup.network_mode;
6954
6955   FadeOut(REDRAW_ALL);
6956
6957   ClearField();
6958
6959   DrawTextSCentered(ystart, font_title, text);
6960
6961   FadeIn(REDRAW_ALL);
6962
6963   if (network.enabled)
6964     InitNetworkServer();
6965   else
6966     DisconnectFromNetworkServer();
6967
6968   DrawTextSCentered(ybottom, font_foot,
6969                     "Press any key or button for setup menu");
6970
6971   WaitForEventToContinue();
6972
6973   DrawSetupScreen();
6974 }
6975
6976 static void ToggleGameSpeedsListIfNeeded(void)
6977 {
6978   boolean using_game_speeds_extended = (game_speeds == game_speeds_extended);
6979
6980   if (setup.game_speed_extended == using_game_speeds_extended)
6981     return;
6982
6983   // try to match similar values when changing game speeds list
6984   if (setup.game_speed_extended)
6985     setup.game_frame_delay = (setup.game_frame_delay == 15 ? 16 :
6986                               setup.game_frame_delay == 30 ? 29 :
6987                               setup.game_frame_delay);
6988   else
6989     setup.game_frame_delay = (setup.game_frame_delay == 14 ? 15 :
6990                               setup.game_frame_delay == 16 ? 15 :
6991                               setup.game_frame_delay >= 29 ? 30 :
6992                               setup.game_frame_delay <= 10 ? 10 :
6993                               setup.game_frame_delay);
6994
6995   execSetupGame_setGameSpeeds(TRUE);
6996
6997   DrawSetupScreen();
6998 }
6999
7000 static void ToggleUseApiServerIfNeeded(void)
7001 {
7002   if (runtime.use_api_server == setup.use_api_server)
7003     return;
7004
7005   runtime.use_api_server = setup.use_api_server;
7006
7007   if (runtime.use_api_server)
7008     CheckApiServerTasks();
7009 }
7010
7011 static void ModifyGameSpeedIfNeeded(void)
7012 {
7013   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7014       setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY)
7015     return;
7016
7017   char message[100];
7018   char *game_speed_text = "Fast";
7019   int game_speed_value = 15;
7020
7021   if (setup.game_speed_extended)
7022   {
7023     game_speed_text = "60 fps";
7024     game_speed_value = 16;
7025   }
7026
7027   sprintf(message, "Game speed set to %s for VSync to work!", game_speed_text);
7028
7029   // set game speed to existing list value that is fast enough for vsync
7030   setup.game_frame_delay = game_speed_value;
7031
7032   execSetupGame_setGameSpeeds(TRUE);
7033
7034   Request(message, REQ_CONFIRM);
7035 }
7036
7037 static void DisableVsyncIfNeeded(void)
7038 {
7039   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7040       (setup.game_frame_delay >= MIN_VSYNC_FRAME_DELAY &&
7041        setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY))
7042     return;
7043
7044   // disable vsync for the selected game speed to work
7045   setup.vsync_mode = STR_VSYNC_MODE_OFF;
7046
7047   execSetupGraphics_setVsyncModes(TRUE);
7048
7049   Request("VSync disabled for this game speed to work!", REQ_CONFIRM);
7050 }
7051
7052 static struct
7053 {
7054   void *value;
7055   void *related_value;
7056 } hide_related_entry_list[] =
7057 {
7058   { &setup.scores_in_highscore_list,    execSetupChooseScoresType       },
7059   { &setup.scores_in_highscore_list,    &scores_type_text               },
7060
7061   { &setup.game_frame_delay,            execSetupChooseGameSpeed        },
7062   { &setup.game_frame_delay,            &game_speed_text                },
7063
7064   { &setup.scroll_delay_value,          execSetupChooseScrollDelay      },
7065   { &setup.scroll_delay_value,          &scroll_delay_text              },
7066
7067   { &setup.engine_snapshot_mode,        execSetupChooseSnapshotMode     },
7068   { &setup.engine_snapshot_mode,        &snapshot_mode_text             },
7069
7070   { &setup.window_scaling_percent,      execSetupChooseWindowSize       },
7071   { &setup.window_scaling_percent,      &window_size_text               },
7072
7073   { &setup.window_scaling_quality,      execSetupChooseScalingType      },
7074   { &setup.window_scaling_quality,      &scaling_type_text              },
7075
7076   { &setup.screen_rendering_mode,       execSetupChooseRenderingMode    },
7077   { &setup.screen_rendering_mode,       &rendering_mode_text            },
7078
7079   { &setup.vsync_mode,                  execSetupChooseVsyncMode        },
7080   { &setup.vsync_mode,                  &vsync_mode_text                },
7081
7082   { &setup.graphics_set,                execSetupChooseGraphics         },
7083   { &setup.graphics_set,                &graphics_set_name              },
7084
7085   { &setup.sounds_set,                  execSetupChooseSounds           },
7086   { &setup.sounds_set,                  &sounds_set_name                },
7087
7088   { &setup.music_set,                   execSetupChooseMusic            },
7089   { &setup.music_set,                   &music_set_name                 },
7090
7091   { &setup.volume_simple,               execSetupChooseVolumeSimple     },
7092   { &setup.volume_simple,               &volume_simple_text             },
7093
7094   { &setup.volume_loops,                execSetupChooseVolumeLoops      },
7095   { &setup.volume_loops,                &volume_loops_text              },
7096
7097   { &setup.volume_music,                execSetupChooseVolumeMusic      },
7098   { &setup.volume_music,                &volume_music_text              },
7099
7100   { &setup.touch.control_type,          execSetupChooseTouchControls    },
7101   { &setup.touch.control_type,          &touch_controls_text            },
7102
7103   { &setup.touch.move_distance,         execSetupChooseMoveDistance     },
7104   { &setup.touch.move_distance,         &move_distance_text             },
7105
7106   { &setup.touch.drop_distance,         execSetupChooseDropDistance     },
7107   { &setup.touch.drop_distance,         &drop_distance_text             },
7108
7109   { &setup.touch.transparency,          execSetupChooseTransparency     },
7110   { &setup.touch.transparency,          &transparency_text              },
7111
7112   { &setup.touch.grid_xsize[0],         execSetupChooseGridXSize_0      },
7113   { &setup.touch.grid_xsize[0],         &grid_size_text[0][0]           },
7114
7115   { &setup.touch.grid_ysize[0],         execSetupChooseGridYSize_0      },
7116   { &setup.touch.grid_ysize[0],         &grid_size_text[0][1]           },
7117
7118   { &setup.touch.grid_xsize[1],         execSetupChooseGridXSize_1      },
7119   { &setup.touch.grid_xsize[1],         &grid_size_text[1][0]           },
7120
7121   { &setup.touch.grid_ysize[1],         execSetupChooseGridYSize_1      },
7122   { &setup.touch.grid_ysize[1],         &grid_size_text[1][1]           },
7123
7124   { &setup.internal.menu_game,          execSetupGame                   },
7125   { &setup.internal.menu_engines,       execSetupEngines                },
7126   { &setup.internal.menu_editor,        execSetupEditor                 },
7127   { &setup.internal.menu_graphics,      execSetupGraphics               },
7128   { &setup.internal.menu_sound,         execSetupSound                  },
7129   { &setup.internal.menu_artwork,       execSetupArtwork                },
7130   { &setup.internal.menu_input,         execSetupInput                  },
7131   { &setup.internal.menu_touch,         execSetupTouch                  },
7132   { &setup.internal.menu_shortcuts,     execSetupShortcuts              },
7133   { &setup.internal.menu_exit,          execExitSetup                   },
7134   { &setup.internal.menu_save_and_exit, execSaveAndExitSetup            },
7135
7136   { NULL,                               NULL                            }
7137 };
7138
7139 void setHideRelatedSetupEntries(void)
7140 {
7141   int i;
7142
7143   for (i = 0; hide_related_entry_list[i].value != NULL; i++)
7144     if (hideSetupEntry(hide_related_entry_list[i].value))
7145       setHideSetupEntry(hide_related_entry_list[i].related_value);
7146 }
7147
7148 static struct TokenInfo setup_info_main[] =
7149 {
7150   { TYPE_ENTER_MENU,    execSetupGame,          STR_SETUP_GAME          },
7151   { TYPE_ENTER_MENU,    execSetupEngines,       STR_SETUP_ENGINES       },
7152   { TYPE_ENTER_MENU,    execSetupEditor,        STR_SETUP_EDITOR        },
7153   { TYPE_ENTER_MENU,    execSetupGraphics,      STR_SETUP_GRAPHICS      },
7154   { TYPE_ENTER_MENU,    execSetupSound,         STR_SETUP_SOUND         },
7155   { TYPE_ENTER_MENU,    execSetupArtwork,       STR_SETUP_ARTWORK       },
7156   { TYPE_ENTER_MENU,    execSetupInput,         STR_SETUP_INPUT         },
7157   { TYPE_ENTER_MENU,    execSetupTouch,         STR_SETUP_TOUCH         },
7158   { TYPE_ENTER_MENU,    execSetupShortcuts,     STR_SETUP_SHORTCUTS     },
7159   { TYPE_EMPTY,         NULL,                   ""                      },
7160   { TYPE_LEAVE_MENU,    execExitSetup,          STR_SETUP_EXIT          },
7161   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   STR_SETUP_SAVE_AND_EXIT },
7162
7163   { 0,                  NULL,                   NULL                    }
7164 };
7165
7166 static struct TokenInfo setup_info_game[] =
7167 {
7168   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
7169   { TYPE_SWITCH,        &setup.network_mode,    "Network Multi-Player Mode:" },
7170   { TYPE_PLAYER,        &setup.network_player_nr,"Preferred Network Player:" },
7171   { TYPE_TEXT_INPUT,    execGadgetNetworkServer, "Network Server Hostname:" },
7172   { TYPE_STRING,        &network_server_text,   ""                      },
7173   { TYPE_SWITCH,        &setup.use_api_server,  "Use Highscore Server:" },
7174   { TYPE_ENTER_LIST,    execSetupChooseScoresType,"Scores in Highscore List:" },
7175   { TYPE_STRING,        &scores_type_text,      ""                      },
7176   { TYPE_ENTER_LIST,    execOfferUploadTapes,   "Upload Tapes to Server" },
7177   { TYPE_SWITCH,        &setup.multiple_users,  "Multiple Users/Teams:" },
7178   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
7179   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
7180   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
7181   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
7182   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
7183   { TYPE_SWITCH,        &setup.auto_play_next_level,"Auto-play Next Level:" },
7184   { TYPE_SWITCH,        &setup.count_score_after_game,"Count Score After Game:" },
7185   { TYPE_SWITCH,        &setup.show_scores_after_game,"Show Scores After Game:" },
7186   { TYPE_YES_NO,        &setup.ask_on_game_over, "Ask on Game Over:"    },
7187   { TYPE_YES_NO,        &setup.ask_on_quit_game, "Ask on Quit Game:"    },
7188   { TYPE_YES_NO,        &setup.ask_on_quit_program, "Ask on Quit Program:" },
7189   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
7190   { TYPE_SWITCH,        &setup.auto_pause_on_start, "Start Game in Pause Mode:" },
7191   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
7192   { TYPE_STRING,        &game_speed_text,       ""                      },
7193   { TYPE_SWITCH,        &setup.game_speed_extended, "Game Speed Extended List:" },
7194 #if 1
7195   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7196   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7197 #endif
7198   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
7199   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
7200   { TYPE_SWITCH,        &setup.show_load_save_buttons,"Show Load/Save Buttons:" },
7201   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,"Show Undo/Redo Buttons:" },
7202   { TYPE_EMPTY,         NULL,                   ""                      },
7203   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7204
7205   { 0,                  NULL,                   NULL                    }
7206 };
7207
7208 static struct TokenInfo setup_info_engines[] =
7209 {
7210   { TYPE_HEADLINE,      NULL,                   "Emerald Mine"          },
7211   { TYPE_SWITCH,        &setup.forced_scroll_delay, "Scroll Delay:"     },
7212   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics, "Amiga Graphics Chipset:" },
7213   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,"Low-Pass Filter Sounds:" },
7214   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:" },
7215   { TYPE_EMPTY,         NULL,                   ""                      },
7216   { TYPE_HEADLINE,      NULL,                   "Supaplex"              },
7217   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:" },
7218   { TYPE_EMPTY,         NULL,                   ""                      },
7219   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7220
7221   { 0,                  NULL,                   NULL                    }
7222 };
7223
7224 static struct TokenInfo setup_info_editor[] =
7225 {
7226 #if 0
7227   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
7228   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
7229   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
7230   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
7231   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
7232   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
7233   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
7234   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
7235   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
7236   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
7237 #endif
7238   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
7239   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
7240 #if 0
7241   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
7242 #endif
7243   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
7244   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
7245   { TYPE_EMPTY,         NULL,                   ""                      },
7246 #if 0
7247   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
7248   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
7249   { TYPE_EMPTY,         NULL,                   ""                      },
7250 #endif
7251   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
7252   { TYPE_EMPTY,         NULL,                   ""                      },
7253   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:" },
7254   { TYPE_EMPTY,         NULL,                   ""                      },
7255   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7256
7257   { 0,                  NULL,                   NULL                    }
7258 };
7259
7260 static struct TokenInfo setup_info_graphics[] =
7261 {
7262 #if !defined(PLATFORM_ANDROID)
7263   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
7264   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
7265   { TYPE_STRING,        &window_size_text,      ""                      },
7266   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
7267   { TYPE_STRING,        &scaling_type_text,     ""                      },
7268   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
7269   { TYPE_STRING,        &rendering_mode_text,   ""                      },
7270 #endif
7271 #if 0
7272   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7273   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7274 #endif
7275   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode, "Vertical Sync (VSync):" },
7276   { TYPE_STRING,        &vsync_mode_text,       ""                      },
7277   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
7278   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
7279   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
7280   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
7281   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
7282   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
7283   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,  debug_xsn_mode          },
7284   { TYPE_EMPTY,         NULL,                   ""                      },
7285   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7286
7287   { 0,                  NULL,                   NULL                    }
7288 };
7289
7290 static struct TokenInfo setup_info_sound[] =
7291 {
7292   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
7293   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
7294   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
7295   { TYPE_EMPTY,         NULL,                   ""                      },
7296   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
7297   { TYPE_STRING,        &volume_simple_text,    ""                      },
7298   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
7299   { TYPE_STRING,        &volume_loops_text,     ""                      },
7300   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
7301   { TYPE_STRING,        &volume_music_text,     ""                      },
7302   { TYPE_EMPTY,         NULL,                   ""                      },
7303   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7304
7305   { 0,                  NULL,                   NULL                    }
7306 };
7307
7308 static struct TokenInfo setup_info_artwork[] =
7309 {
7310   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
7311   { TYPE_STRING,        &graphics_set_name,     ""                      },
7312   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
7313   { TYPE_STRING,        &sounds_set_name,       ""                      },
7314   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
7315   { TYPE_STRING,        &music_set_name,        ""                      },
7316   { TYPE_EMPTY,         NULL,                   ""                      },
7317   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
7318   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
7319   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
7320   { TYPE_EMPTY,         NULL,                   ""                      },
7321   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7322
7323   { 0,                  NULL,                   NULL                    }
7324 };
7325
7326 static struct TokenInfo setup_info_input[] =
7327 {
7328   { TYPE_SWITCH,        NULL,                   "Player:"               },
7329   { TYPE_SWITCH,        NULL,                   "Device:"               },
7330   { TYPE_SWITCH,        NULL,                   ""                      },
7331   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7332   { TYPE_EMPTY,         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_SKIPPABLE,     NULL,                   ""                      },
7341   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7342
7343   { 0,                  NULL,                   NULL                    }
7344 };
7345
7346 static struct TokenInfo setup_info_touch[] =
7347 {
7348   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7349   { TYPE_STRING,        &touch_controls_text,   ""                      },
7350   { TYPE_EMPTY,         NULL,                   ""                      },
7351   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7352
7353   { 0,                  NULL,                   NULL                    }
7354 };
7355
7356 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
7357 {
7358   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7359   { TYPE_STRING,        &touch_controls_text,   ""                      },
7360   { TYPE_EMPTY,         NULL,                   ""                      },
7361   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0, "Horizontal Buttons (Landscape):"   },
7362   { TYPE_STRING,        &grid_size_text[0][0],  ""                      },
7363   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0, "Vertical Buttons (Landscape):"     },
7364   { TYPE_STRING,        &grid_size_text[0][1],  ""                      },
7365   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7366   { TYPE_STRING,        &transparency_text,     ""                      },
7367   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7368   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7369   { TYPE_EMPTY,         NULL,                   ""                      },
7370   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7371   { TYPE_EMPTY,         NULL,                   ""                      },
7372   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7373
7374   { 0,                  NULL,                   NULL                    }
7375 };
7376
7377 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
7378 {
7379   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7380   { TYPE_STRING,        &touch_controls_text,   ""                      },
7381   { TYPE_EMPTY,         NULL,                   ""                      },
7382   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1, "Horizontal Buttons (Portrait):"    },
7383   { TYPE_STRING,        &grid_size_text[1][0],  ""                      },
7384   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1, "Vertical Buttons (Portrait):"      },
7385   { TYPE_STRING,        &grid_size_text[1][1],  ""                      },
7386   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7387   { TYPE_STRING,        &transparency_text,     ""                      },
7388   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7389   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7390   { TYPE_EMPTY,         NULL,                   ""                      },
7391   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7392   { TYPE_EMPTY,         NULL,                   ""                      },
7393   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7394
7395   { 0,                  NULL,                   NULL                    }
7396 };
7397
7398 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
7399 {
7400   setup_info_touch_virtual_buttons_0,
7401   setup_info_touch_virtual_buttons_1
7402 };
7403
7404 static struct TokenInfo setup_info_touch_wipe_gestures[] =
7405 {
7406   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7407   { TYPE_STRING,        &touch_controls_text,   ""                      },
7408   { TYPE_EMPTY,         NULL,                   ""                      },
7409   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
7410   { TYPE_STRING,        &move_distance_text,    ""                      },
7411   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
7412   { TYPE_STRING,        &drop_distance_text,    ""                      },
7413   { TYPE_EMPTY,         NULL,                   ""                      },
7414   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7415
7416   { 0,                  NULL,                   NULL                    }
7417 };
7418
7419 static struct TokenInfo setup_info_shortcuts[] =
7420 {
7421   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
7422   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
7423   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
7424   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
7425   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
7426   { TYPE_EMPTY,         NULL,                   ""                      },
7427   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7428
7429   { 0,                  NULL,                   NULL                    }
7430 };
7431
7432 static struct TokenInfo setup_info_shortcuts_1[] =
7433 {
7434   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
7435   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
7436   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
7437   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
7438   { TYPE_KEYTEXT,       NULL,           "Restart Game:",                },
7439   { TYPE_KEY,           &setup.shortcut.restart_game, ""                },
7440   { TYPE_KEYTEXT,       NULL,           "Replay & Pause Before End:",   },
7441   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""            },
7442   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
7443   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
7444   { TYPE_EMPTY,         NULL,                   ""                      },
7445   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
7446   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
7447   { TYPE_EMPTY,         NULL,                   ""                      },
7448   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7449
7450   { 0,                  NULL,                   NULL                    }
7451 };
7452
7453 static struct TokenInfo setup_info_shortcuts_2[] =
7454 {
7455   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
7456   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
7457   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
7458   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
7459   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
7460   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
7461   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
7462   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
7463   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
7464   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
7465   { TYPE_EMPTY,         NULL,                   ""                      },
7466   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7467
7468   { 0,                  NULL,                   NULL                    }
7469 };
7470
7471 static struct TokenInfo setup_info_shortcuts_3[] =
7472 {
7473   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
7474   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
7475   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
7476   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
7477   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
7478   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
7479   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
7480   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
7481   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
7482   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
7483   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
7484   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
7485   { TYPE_EMPTY,         NULL,                   ""                      },
7486   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7487
7488   { 0,                  NULL,                   NULL                    }
7489 };
7490
7491 static struct TokenInfo setup_info_shortcuts_4[] =
7492 {
7493   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
7494   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
7495   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
7496   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
7497   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
7498   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
7499   { TYPE_EMPTY,         NULL,                   ""                      },
7500   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7501
7502   { 0,                  NULL,                   NULL                    }
7503 };
7504
7505 static struct TokenInfo setup_info_shortcuts_5[] =
7506 {
7507   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
7508   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
7509   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
7510   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
7511   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
7512   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
7513   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
7514   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
7515   { TYPE_EMPTY,         NULL,                   ""                      },
7516   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7517
7518   { 0,                  NULL,                   NULL                    }
7519 };
7520
7521 static Key getSetupKey(void)
7522 {
7523   Key key = KSYM_UNDEFINED;
7524   boolean got_key_event = FALSE;
7525
7526   while (!got_key_event)
7527   {
7528     Event event;
7529
7530     if (NextValidEvent(&event))
7531     {
7532       switch (event.type)
7533       {
7534         case EVENT_KEYPRESS:
7535           {
7536             key = GetEventKey((KeyEvent *)&event, TRUE);
7537
7538             // press 'Escape' or 'Enter' to keep the existing key binding
7539             if (key == KSYM_Escape || key == KSYM_Return)
7540               key = KSYM_UNDEFINED;     // keep old value
7541
7542             got_key_event = TRUE;
7543           }
7544           break;
7545
7546         case EVENT_KEYRELEASE:
7547           key_joystick_mapping = 0;
7548           break;
7549
7550         default:
7551           HandleOtherEvents(&event);
7552           break;
7553       }
7554     }
7555
7556     BackToFront();
7557   }
7558
7559   return key;
7560 }
7561
7562 static int getSetupValueFont(int type, void *value)
7563 {
7564   if (type & TYPE_GHOSTED)
7565     return FONT_OPTION_OFF;
7566   else if (type & TYPE_KEY)
7567     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
7568   else if (type & TYPE_STRING)
7569     return FONT_VALUE_2;
7570   else if (type & TYPE_ECS_AGA)
7571     return FONT_VALUE_1;
7572   else if (type & TYPE_BOOLEAN_STYLE)
7573     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
7574   else if (type & TYPE_YES_NO_AUTO)
7575     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
7576             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
7577   else if (type & TYPE_PLAYER)
7578     return FONT_VALUE_1;
7579   else
7580     return FONT_VALUE_1;
7581 }
7582
7583 static int getSetupValueFontNarrow(int type, int font_nr)
7584 {
7585   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
7586           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
7587           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
7588           font_nr);
7589 }
7590
7591 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
7592 {
7593   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7594   struct TokenInfo *si = &setup_info[si_pos];
7595   boolean font_draw_xoffset_modified = FALSE;
7596   boolean scrollbar_needed = (num_setup_info < max_setup_info);
7597   int font_draw_xoffset_old = -1;
7598   int xoffset = (scrollbar_needed ? -1 : 0);
7599   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
7600   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
7601   int xpos = menu_screen_value_xpos;
7602   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
7603   int startx = mSX + xpos * 32;
7604   int starty = mSY + ypos * 32;
7605   int type = si->type;
7606   void *value = si->value;
7607   char *value_string = getSetupValue(type, value);
7608   int font_nr_default = getSetupValueFont(type, value);
7609   int font_width_default = getFontWidth(font_nr_default);
7610   int font_nr = font_nr_default;
7611   int i;
7612
7613   if (value_string == NULL)
7614     return;
7615
7616   if (type & TYPE_KEY)
7617   {
7618     xpos = MENU_SCREEN_START_XPOS;
7619
7620     if (type & TYPE_QUERY)
7621       value_string = "<press key>";
7622   }
7623   else if (type & TYPE_STRING)
7624   {
7625     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
7626
7627     xpos = MENU_SCREEN_START_XPOS;
7628
7629     if (strlen(value_string) > max_value_len)
7630       value_string[max_value_len] = '\0';
7631   }
7632   else if (type & TYPE_YES_NO_AUTO)
7633   {
7634     xpos = menu_screen_value_xpos - 1;
7635   }
7636   else if (type & TYPE_PLAYER)
7637   {
7638     int displayed_player_nr = *(int *)value + 1;
7639
7640     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
7641   }
7642
7643   startx = mSX + xpos * 32;
7644   starty = mSY + ypos * 32;
7645
7646   // special check if right-side setup values moved left due to scrollbar
7647   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
7648   {
7649     int max_menu_text_length = 26;      // maximum text length for classic menu
7650     int font_xoffset = getFontDrawOffsetX(font_nr);
7651     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
7652     int text_font_nr = getMenuTextFont(FONT_MENU_2);
7653     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
7654     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
7655
7656     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
7657     {
7658       // when using narrow font, left-shifting text "auto" not needed
7659       if (type & TYPE_YES_NO_AUTO)
7660         xpos += 1;
7661
7662       xpos += 1;
7663       startx = mSX + xpos * 32;
7664
7665       font_nr = getSetupValueFontNarrow(type, font_nr);
7666     }
7667   }
7668
7669   // downward compatibility correction for Juergen Bonhagen's menu settings
7670   if (setup_mode != SETUP_MODE_INPUT)
7671   {
7672     int max_menu_text_length_big = (menu_screen_value_xpos -
7673                                     MENU_SCREEN_START_XPOS);
7674     int max_menu_text_length_medium = max_menu_text_length_big * 2;
7675     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
7676     int font1_xoffset = getFontDrawOffsetX(font_nr);
7677     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
7678     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
7679     int text_font_nr = getMenuTextFont(FONT_MENU_2);
7680     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
7681     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
7682     boolean correct_font_draw_xoffset = FALSE;
7683
7684     if (xpos == MENU_SCREEN_START_XPOS &&
7685         startx + font1_xoffset < text_startx + text_font_xoffset)
7686       correct_font_draw_xoffset = TRUE;
7687
7688     if (xpos == menu_screen_value_xpos &&
7689         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
7690       correct_font_draw_xoffset = TRUE;
7691
7692     // check if setup value would overlap with setup text when printed
7693     // (this can happen for extreme/wrong values for font draw offset)
7694     if (correct_font_draw_xoffset)
7695     {
7696       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
7697       font_draw_xoffset_modified = TRUE;
7698
7699       if (type & TYPE_KEY)
7700         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
7701       else if (!(type & TYPE_STRING))
7702         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
7703           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
7704     }
7705   }
7706
7707   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
7708     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
7709
7710   DrawText(startx, starty, value_string, font_nr);
7711
7712   if (type & TYPE_PLAYER)
7713   {
7714     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
7715     int player_nr = *(int *)value;
7716     int xoff = font->draw_xoffset + getFontWidth(font_nr);
7717     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
7718     int startx2 = startx + xoff;
7719     int starty2 = starty + yoff;
7720
7721     if (DrawingOnBackground(startx2, starty2))
7722       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
7723
7724     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
7725                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
7726   }
7727
7728   if (font_draw_xoffset_modified)
7729     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
7730 }
7731
7732 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
7733 {
7734   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7735   struct TokenInfo *si = &setup_info[si_pos];
7736
7737   if (si->type & TYPE_BOOLEAN_STYLE)
7738   {
7739     *(boolean *)si->value ^= TRUE;
7740   }
7741   else if (si->type & TYPE_YES_NO_AUTO)
7742   {
7743     *(int *)si->value =
7744       (dx == -1 ?
7745        (*(int *)si->value == AUTO ? TRUE :
7746         *(int *)si->value == TRUE ? FALSE : AUTO) :
7747        (*(int *)si->value == TRUE ? AUTO :
7748         *(int *)si->value == AUTO ? FALSE : TRUE));
7749   }
7750   else if (si->type & TYPE_KEY)
7751   {
7752     Key key;
7753
7754     si->type |= TYPE_QUERY;
7755     drawSetupValue(screen_pos, setup_info_pos_raw);
7756     si->type &= ~TYPE_QUERY;
7757
7758     key = getSetupKey();
7759     if (key != KSYM_UNDEFINED)
7760       *(Key *)si->value = key;
7761   }
7762   else if (si->type & TYPE_PLAYER)
7763   {
7764     int player_nr = *(int *)si->value;
7765
7766     if (dx)
7767       player_nr += dx;
7768     else
7769       player_nr = Request("Choose player", REQ_PLAYER) - 1;
7770
7771     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
7772   }
7773
7774   drawSetupValue(screen_pos, setup_info_pos_raw);
7775
7776   // fullscreen state may have changed at this point
7777   if (si->value == &setup.fullscreen)
7778     ToggleFullscreenIfNeeded();
7779
7780   // network mode may have changed at this point
7781   if (si->value == &setup.network_mode)
7782     ToggleNetworkModeIfNeeded();
7783
7784   // API server mode may have changed at this point
7785   if (si->value == &setup.use_api_server)
7786     ToggleUseApiServerIfNeeded();
7787
7788   // game speed list may have changed at this point
7789   if (si->value == &setup.game_speed_extended)
7790     ToggleGameSpeedsListIfNeeded();
7791 }
7792
7793 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
7794 {
7795   static struct TokenInfo *setup_info_final = NULL;
7796   int list_size = 0;
7797   int list_pos = 0;
7798   int i;
7799
7800   // determine maximum list size of target list
7801   while (setup_info_orig[list_size++].type != 0);
7802
7803   // free, allocate and clear memory for target list
7804   checked_free(setup_info_final);
7805   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
7806
7807   // copy setup info list without setup entries marked as hidden
7808   for (i = 0; setup_info_orig[i].type != 0; i++)
7809   {
7810     // skip setup entries configured to be hidden
7811     if (hideSetupEntry(setup_info_orig[i].value))
7812       continue;
7813
7814     // skip skippable setup entries if screen is lower than usual
7815     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
7816         setup_info_orig[i].type == TYPE_SKIPPABLE)
7817       continue;
7818
7819     setup_info_final[list_pos++] = setup_info_orig[i];
7820   }
7821
7822   return setup_info_final;
7823 }
7824
7825 static void DrawSetupScreen_Generic(void)
7826 {
7827   int fade_mask = REDRAW_FIELD;
7828   boolean redraw_all = FALSE;
7829   char *title_string = NULL;
7830   int i;
7831
7832   if (CheckFadeAll())
7833     fade_mask = REDRAW_ALL;
7834
7835   UnmapAllGadgets();
7836   FadeMenuSoundsAndMusic();
7837
7838   FreeScreenGadgets();
7839   CreateScreenGadgets();
7840
7841   if (redraw_mask & REDRAW_ALL)
7842     redraw_all = TRUE;
7843
7844   FadeOut(fade_mask);
7845
7846   // needed if different viewport properties defined for setup screen
7847   ChangeViewportPropertiesIfNeeded();
7848
7849   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
7850
7851   ClearField();
7852
7853   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
7854
7855   if (setup_mode == SETUP_MODE_MAIN)
7856   {
7857     setup_info = setup_info_main;
7858     title_string = STR_SETUP_MAIN;
7859   }
7860   else if (setup_mode == SETUP_MODE_GAME)
7861   {
7862     setup_info = setup_info_game;
7863     title_string = STR_SETUP_GAME;
7864   }
7865   else if (setup_mode == SETUP_MODE_ENGINES)
7866   {
7867     setup_info = setup_info_engines;
7868     title_string = STR_SETUP_ENGINES;
7869   }
7870   else if (setup_mode == SETUP_MODE_EDITOR)
7871   {
7872     setup_info = setup_info_editor;
7873     title_string = STR_SETUP_EDITOR;
7874   }
7875   else if (setup_mode == SETUP_MODE_GRAPHICS)
7876   {
7877     setup_info = setup_info_graphics;
7878     title_string = STR_SETUP_GRAPHICS;
7879   }
7880   else if (setup_mode == SETUP_MODE_SOUND)
7881   {
7882     setup_info = setup_info_sound;
7883     title_string = STR_SETUP_SOUND;
7884   }
7885   else if (setup_mode == SETUP_MODE_ARTWORK)
7886   {
7887     setup_info = setup_info_artwork;
7888     title_string = STR_SETUP_ARTWORK;
7889   }
7890   else if (setup_mode == SETUP_MODE_TOUCH)
7891   {
7892     setup_info = setup_info_touch;
7893     title_string = STR_SETUP_TOUCH;
7894
7895     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
7896       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
7897     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
7898       setup_info = setup_info_touch_wipe_gestures;
7899   }
7900   else if (setup_mode == SETUP_MODE_SHORTCUTS)
7901   {
7902     setup_info = setup_info_shortcuts;
7903     title_string = STR_SETUP_SHORTCUTS;
7904   }
7905   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
7906   {
7907     setup_info = setup_info_shortcuts_1;
7908     title_string = STR_SETUP_SHORTCUTS;
7909   }
7910   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
7911   {
7912     setup_info = setup_info_shortcuts_2;
7913     title_string = STR_SETUP_SHORTCUTS;
7914   }
7915   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
7916   {
7917     setup_info = setup_info_shortcuts_3;
7918     title_string = STR_SETUP_SHORTCUTS;
7919   }
7920   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
7921   {
7922     setup_info = setup_info_shortcuts_4;
7923     title_string = STR_SETUP_SHORTCUTS;
7924   }
7925   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
7926   {
7927     setup_info = setup_info_shortcuts_5;
7928     title_string = STR_SETUP_SHORTCUTS;
7929   }
7930
7931   // use modified setup info without setup entries marked as hidden
7932   setup_info = getSetupInfoFinal(setup_info);
7933
7934   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
7935
7936   // determine maximal number of setup entries that can be displayed on screen
7937   num_setup_info = 0;
7938   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
7939     num_setup_info++;
7940
7941   // determine maximal number of setup entries available for this setup screen
7942   max_setup_info = 0;
7943   for (i = 0; setup_info[i].type != 0; i++)
7944     max_setup_info++;
7945
7946   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
7947
7948   MapScreenGadgets(max_setup_info);
7949
7950   if (redraw_all)
7951     redraw_mask = fade_mask = REDRAW_ALL;
7952
7953   DrawMaskedBorder(fade_mask);
7954
7955   FadeIn(fade_mask);
7956 }
7957
7958 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
7959 {
7960   menu_info = setup_info;
7961
7962   HandleMenuScreen(mx, my, dx, dy, button,
7963                    setup_mode, num_setup_info, max_setup_info);
7964 }
7965
7966 static void DrawSetupScreen_Input(void)
7967 {
7968   int i;
7969
7970   FadeOut(REDRAW_FIELD);
7971
7972   ClearField();
7973
7974   setup_info = getSetupInfoFinal(setup_info_input);
7975
7976   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
7977
7978   for (i = 0; setup_info[i].type != 0; i++)
7979   {
7980     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
7981       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
7982     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
7983       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
7984     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
7985       initCursor(i, IMG_MENU_BUTTON);
7986
7987     DrawCursorAndText_Setup(i, -1, FALSE);
7988   }
7989
7990   // create gadgets for setup input menu screen
7991   FreeScreenGadgets();
7992   CreateScreenGadgets();
7993
7994   // map gadgets for setup input menu screen
7995   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
7996
7997   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
7998
7999   FadeIn(REDRAW_FIELD);
8000 }
8001
8002 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8003 {
8004   if (device_name == NULL)
8005     return;
8006
8007   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8008     device_nr = 0;
8009
8010   if (strlen(device_name) > 1)
8011   {
8012     char c1 = device_name[strlen(device_name) - 1];
8013     char c2 = device_name[strlen(device_name) - 2];
8014
8015     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8016       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8017   }
8018   else
8019     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8020             strlen(device_name));
8021 }
8022
8023 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8024 {
8025   int i;
8026   static struct SetupKeyboardInfo custom_key;
8027   static struct
8028   {
8029     Key *key;
8030     char *text;
8031   } custom[] =
8032   {
8033     { &custom_key.left,  "Axis/Pad Left"  },
8034     { &custom_key.right, "Axis/Pad Right" },
8035     { &custom_key.up,    "Axis/Pad Up"    },
8036     { &custom_key.down,  "Axis/Pad Down"  },
8037     { &custom_key.snap,  "Button 1/A/X"   },
8038     { &custom_key.drop,  "Button 2/B/Y"   }
8039   };
8040   static char *joystick_name[MAX_PLAYERS] =
8041   {
8042     "Joystick1",
8043     "Joystick2",
8044     "Joystick3",
8045     "Joystick4"
8046   };
8047   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8048   int font_nr_info = FONT_MENU_1;
8049   int font_nr_name = FONT_VALUE_OLD;
8050   int font_nr_on   = FONT_VALUE_1;
8051   int font_nr_off  = FONT_VALUE_OLD;
8052   int pos = 4;
8053
8054   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8055   {
8056     font_nr_info = FONT_MENU_2;
8057     font_nr_on   = FONT_VALUE_NARROW;
8058     font_nr_off  = FONT_VALUE_OLD_NARROW;
8059   }
8060
8061   custom_key = setup.input[player_nr].key;
8062
8063   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8064            FONT_INPUT_1_ACTIVE);
8065
8066   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8067                              TILEX, TILEY);
8068   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8069                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8070
8071   if (setup.input[player_nr].use_joystick)
8072   {
8073     char *device_name = setup.input[player_nr].joy.device_name;
8074     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8075     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8076     char *text = joystick_name[joystick_nr];
8077     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8078
8079     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8080     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8081   }
8082   else
8083   {
8084     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8085     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8086   }
8087
8088   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8089     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8090   else
8091     pos = 3;
8092
8093   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8094   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8095   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8096   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8097
8098   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8099   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8100   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8101   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8102   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8103   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8104
8105   for (i = 0; i < 6; i++)
8106   {
8107     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8108
8109     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8110              "              ", font_nr_on);
8111     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8112              (setup.input[player_nr].use_joystick ?
8113               custom[i].text :
8114               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8115   }
8116 }
8117
8118 static int input_player_nr = 0;
8119
8120 static void HandleSetupScreen_Input_Player(int step, int direction)
8121 {
8122   int old_player_nr = input_player_nr;
8123   int new_player_nr;
8124
8125   new_player_nr = old_player_nr + step * direction;
8126   if (new_player_nr < 0)
8127     new_player_nr = 0;
8128   if (new_player_nr > MAX_PLAYERS - 1)
8129     new_player_nr = MAX_PLAYERS - 1;
8130
8131   if (new_player_nr != old_player_nr)
8132   {
8133     input_player_nr = new_player_nr;
8134
8135     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8136   }
8137 }
8138
8139 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8140 {
8141   static int choice = 0;
8142   int x = 0;
8143   int y = choice;
8144   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8145   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8146   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8147   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8148
8149   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8150   {
8151     int i;
8152
8153     for (i = 0; setup_info_input[i].type != 0; i++)
8154     {
8155       // adjust menu structure according to skipped setup entries
8156       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8157       {
8158         pos_empty2--;
8159         pos_end--;
8160       }
8161     }
8162   }
8163
8164   if (button == MB_MENU_INITIALIZE)
8165   {
8166     // input setup menu may have changed size due to graphics configuration
8167     if (choice >= pos_empty1)
8168       choice = pos_end;
8169
8170     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8171
8172     DrawCursorAndText_Setup(choice, -1, TRUE);
8173
8174     return;
8175   }
8176   else if (button == MB_MENU_LEAVE)
8177   {
8178     setup_mode = SETUP_MODE_MAIN;
8179     DrawSetupScreen();
8180     InitJoysticks();
8181
8182     return;
8183   }
8184
8185   if (mx || my)         // mouse input
8186   {
8187     x = (mx - mSX) / 32;
8188     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8189   }
8190   else if (dx || dy)    // keyboard input
8191   {
8192     if (dx && choice == 0)
8193       x = (dx < 0 ? 10 : 12);
8194     else if ((dx && choice == 1) ||
8195              (dx == -1 && choice == pos_end))
8196       button = MB_MENU_CHOICE;
8197     else if (dy)
8198       y = choice + dy;
8199
8200     if (y >= pos_empty1 && y <= pos_empty2)
8201       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
8202   }
8203
8204   if (y == 0 && dx != 0 && button)
8205   {
8206     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
8207   }
8208   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
8209            y >= pos_start && y <= pos_end &&
8210            !(y >= pos_empty1 && y <= pos_empty2))
8211   {
8212     if (button)
8213     {
8214       if (y != choice)
8215       {
8216         DrawCursorAndText_Setup(choice, -1, FALSE);
8217         DrawCursorAndText_Setup(y, -1, TRUE);
8218
8219         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
8220
8221         choice = y;
8222       }
8223     }
8224     else
8225     {
8226       if (y == 1)
8227       {
8228         char *device_name = setup.input[input_player_nr].joy.device_name;
8229
8230         if (!setup.input[input_player_nr].use_joystick)
8231         {
8232           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
8233
8234           setJoystickDeviceToNr(device_name, new_device_nr);
8235           setup.input[input_player_nr].use_joystick = TRUE;
8236         }
8237         else
8238         {
8239           int device_nr = getJoystickNrFromDeviceName(device_name);
8240           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
8241
8242           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
8243             setup.input[input_player_nr].use_joystick = FALSE;
8244           else
8245             setJoystickDeviceToNr(device_name, new_device_nr);
8246         }
8247
8248         drawPlayerSetupInputInfo(input_player_nr, FALSE);
8249       }
8250       else if (y == 2)
8251       {
8252         if (setup.input[input_player_nr].use_joystick)
8253           ConfigureJoystick(input_player_nr);
8254         else
8255           CustomizeKeyboard(input_player_nr);
8256       }
8257       else if (y == pos_end)
8258       {
8259         InitJoysticks();
8260
8261         FadeSetLeaveMenu();
8262
8263         setup_mode = SETUP_MODE_MAIN;
8264         DrawSetupScreen();
8265       }
8266     }
8267   }
8268 }
8269
8270 static boolean CustomizeKeyboardMain(int player_nr)
8271 {
8272   int i;
8273   int step_nr;
8274   boolean finished = FALSE;
8275   static struct SetupKeyboardInfo custom_key;
8276   static struct
8277   {
8278     Key *key;
8279     char *text;
8280   } customize_step[] =
8281   {
8282     { &custom_key.left,  "Move Left"    },
8283     { &custom_key.right, "Move Right"   },
8284     { &custom_key.up,    "Move Up"      },
8285     { &custom_key.down,  "Move Down"    },
8286     { &custom_key.snap,  "Snap Field"   },
8287     { &custom_key.drop,  "Drop Element" }
8288   };
8289   int font_nr_old = FONT_VALUE_OLD;
8290   int font_nr_new = FONT_VALUE_1;
8291   boolean success = FALSE;
8292
8293   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8294   {
8295     font_nr_old = FONT_VALUE_OLD_NARROW;
8296     font_nr_new = FONT_VALUE_NARROW;
8297   }
8298
8299   // read existing key bindings from player setup
8300   custom_key = setup.input[player_nr].key;
8301
8302   FadeSetEnterMenu();
8303   FadeOut(REDRAW_FIELD);
8304
8305   ClearField();
8306
8307   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
8308
8309   step_nr = 0;
8310   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8311            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8312   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8313            "Key:", FONT_INPUT_1_ACTIVE);
8314   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8315            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
8316
8317   FadeIn(REDRAW_FIELD);
8318
8319   while (!finished)
8320   {
8321     Event event;
8322
8323     if (NextValidEvent(&event))
8324     {
8325       switch (event.type)
8326       {
8327         case EVENT_KEYPRESS:
8328           {
8329             Key key = GetEventKey((KeyEvent *)&event, FALSE);
8330
8331             // press 'Escape' to abort and keep the old key bindings
8332             if (key == KSYM_Escape)
8333             {
8334               FadeSkipNextFadeIn();
8335
8336               finished = TRUE;
8337
8338               break;
8339             }
8340
8341             // press 'Enter' to keep the existing key binding
8342             if (key == KSYM_Return)
8343               key = *customize_step[step_nr].key;
8344
8345             // check if key already used
8346             for (i = 0; i < step_nr; i++)
8347               if (*customize_step[i].key == key)
8348                 break;
8349             if (i < step_nr)
8350               break;
8351
8352             // got new key binding
8353             *customize_step[step_nr].key = key;
8354             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8355                      "             ", font_nr_new);
8356             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8357                      getKeyNameFromKey(key), font_nr_new);
8358             step_nr++;
8359
8360             // un-highlight last query
8361             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
8362                      customize_step[step_nr - 1].text, FONT_MENU_1);
8363             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
8364                      "Key:", FONT_MENU_1);
8365
8366             // all keys configured
8367             if (step_nr == 6)
8368             {
8369               finished = TRUE;
8370               success = TRUE;
8371
8372               break;
8373             }
8374
8375             // query next key binding
8376             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8377                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8378             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8379                      "Key:", FONT_INPUT_1_ACTIVE);
8380             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8381                      getKeyNameFromKey(*customize_step[step_nr].key),
8382                      font_nr_old);
8383           }
8384           break;
8385
8386         case EVENT_KEYRELEASE:
8387           key_joystick_mapping = 0;
8388           break;
8389
8390         default:
8391           HandleOtherEvents(&event);
8392           break;
8393       }
8394     }
8395
8396     BackToFront();
8397   }
8398
8399   // write new key bindings back to player setup, if successfully finished
8400   if (success)
8401     setup.input[player_nr].key = custom_key;
8402
8403   return success;
8404 }
8405
8406 void CustomizeKeyboard(int player_nr)
8407 {
8408   boolean success = CustomizeKeyboardMain(player_nr);
8409
8410   if (success)
8411   {
8412     int font_nr = FONT_TITLE_1;
8413     int font_height = getFontHeight(font_nr);
8414     int ypos1 = SYSIZE / 2 - font_height * 2;
8415     int ypos2 = SYSIZE / 2 - font_height * 1;
8416     unsigned int wait_frame_delay = 0;
8417     unsigned int wait_frame_delay_value = 2000;
8418
8419     ResetDelayCounter(&wait_frame_delay);
8420
8421     ClearField();
8422
8423     DrawTextSCentered(ypos1, font_nr, "Keyboard");
8424     DrawTextSCentered(ypos2, font_nr, "configured!");
8425
8426     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8427       BackToFront();
8428
8429     ClearEventQueue();
8430   }
8431
8432   DrawSetupScreen_Input();
8433 }
8434
8435 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
8436
8437 #define MARKER_BUTTON           1
8438 #define MARKER_AXIS_X           2
8439 #define MARKER_AXIS_Y           3
8440
8441 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
8442 {
8443   static boolean bitmaps_initialized = FALSE;
8444   boolean screen_initialized = FALSE;
8445   static Bitmap *controller, *button, *axis_x, *axis_y;
8446   char *name;
8447   boolean success = TRUE;
8448   boolean done = FALSE, next = FALSE;
8449   Event event;
8450   int alpha = 200, alpha_step = -1;
8451   int alpha_ticks = 0;
8452   char mapping[4096], temp[256];
8453   int font_name = MENU_SETUP_FONT_TITLE;
8454   int font_info = MENU_SETUP_FONT_TEXT;
8455   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
8456   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
8457   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
8458   int ystep_name = getMenuTextStep(spacing_name, font_name);
8459   int ystep_line = getMenuTextStep(spacing_line, font_info);
8460   int ystep_para = getMenuTextStep(spacing_para, font_info);
8461   int i, j;
8462
8463   struct
8464   {
8465     int x, y;
8466     int marker;
8467     char *field;
8468     int axis, button, hat, hat_value;
8469     char mapping[4096];
8470   }
8471   *step, *prev_step, steps[] =
8472   {
8473     { 356, 155, MARKER_BUTTON, "a",             },
8474     { 396, 122, MARKER_BUTTON, "b",             },
8475     { 320, 125, MARKER_BUTTON, "x",             },
8476     { 358,  95, MARKER_BUTTON, "y",             },
8477     { 162, 125, MARKER_BUTTON, "back",          },
8478     { 216, 125, MARKER_BUTTON, "guide",         },
8479     { 271, 125, MARKER_BUTTON, "start",         },
8480     { 110, 200, MARKER_BUTTON, "dpleft",        },
8481     { 146, 228, MARKER_BUTTON, "dpdown",        },
8482     { 178, 200, MARKER_BUTTON, "dpright",       },
8483     { 146, 172, MARKER_BUTTON, "dpup",          },
8484     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
8485     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
8486     { 382,  40, MARKER_BUTTON, "rightshoulder", },
8487     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
8488     {  73, 141, MARKER_BUTTON, "leftstick",     },
8489     { 282, 210, MARKER_BUTTON, "rightstick",    },
8490     {  73, 141, MARKER_AXIS_X, "leftx",         },
8491     {  73, 141, MARKER_AXIS_Y, "lefty",         },
8492     { 282, 210, MARKER_AXIS_X, "rightx",        },
8493     { 282, 210, MARKER_AXIS_Y, "righty",        },
8494   };
8495
8496   unsigned int event_frame_delay = 0;
8497   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
8498
8499   ResetDelayCounter(&event_frame_delay);
8500
8501   if (!bitmaps_initialized)
8502   {
8503     controller = LoadCustomImage("joystick/controller.png");
8504     button     = LoadCustomImage("joystick/button.png");
8505     axis_x     = LoadCustomImage("joystick/axis_x.png");
8506     axis_y     = LoadCustomImage("joystick/axis_y.png");
8507
8508     bitmaps_initialized = TRUE;
8509   }
8510
8511   name = getFormattedJoystickName(SDL_JoystickName(joystick));
8512
8513 #if DEBUG_JOYSTICKS
8514   // print info about the joystick we are watching
8515   Debug("joystick", "watching joystick %d: (%s)",
8516         SDL_JoystickInstanceID(joystick), name);
8517   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
8518         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
8519         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
8520 #endif
8521
8522   // initialize mapping with GUID and name
8523   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
8524
8525   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
8526            temp, name, SDL_GetPlatform());
8527
8528   // loop through all steps (buttons and axes), getting joystick events
8529   for (i = 0; i < SDL_arraysize(steps) && !done;)
8530   {
8531     Bitmap *marker = button;    // initialize with reliable default value
8532
8533     step = &steps[i];
8534     strcpy(step->mapping, mapping);
8535     step->axis = -1;
8536     step->button = -1;
8537     step->hat = -1;
8538     step->hat_value = -1;
8539
8540     marker = (step->marker == MARKER_BUTTON ? button :
8541               step->marker == MARKER_AXIS_X ? axis_x :
8542               step->marker == MARKER_AXIS_Y ? axis_y : marker);
8543
8544     next = FALSE;
8545
8546     while (!done && !next)
8547     {
8548       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
8549       alpha_ticks = SDL_GetTicks();
8550
8551       if (alpha >= 255)
8552       {
8553         alpha = 255;
8554         alpha_step = -1;
8555       }
8556       else if (alpha < 128)
8557       {
8558         alpha = 127;
8559         alpha_step = 1;
8560       }
8561
8562       int controller_x = SX + (SXSIZE - controller->width) / 2;
8563       int controller_y = SY + ystep_line;
8564
8565       int marker_x = controller_x + step->x;
8566       int marker_y = controller_y + step->y;
8567
8568       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
8569       int ystart2 = ystart1 + ystep_name + ystep_line;
8570
8571       ClearField();
8572
8573       DrawTextSCentered(ystart1, font_name, name);
8574
8575       DrawTextSCentered(ystart2, font_info,
8576                         "Press buttons and move axes on");
8577       ystart2 += ystep_line;
8578       DrawTextSCentered(ystart2, font_info,
8579                         "your controller when indicated.");
8580       ystart2 += ystep_line;
8581       DrawTextSCentered(ystart2, font_info,
8582                         "(Your controller may look different.)");
8583       ystart2 += ystep_para;
8584
8585 #if defined(PLATFORM_ANDROID)
8586       DrawTextSCentered(ystart2, font_info,
8587                         "To correct a mistake,");
8588       ystart2 += ystep_line;
8589       DrawTextSCentered(ystart2, font_info,
8590                         "press the 'back' button.");
8591       ystart2 += ystep_line;
8592       DrawTextSCentered(ystart2, font_info,
8593                         "To skip a button or axis,");
8594       ystart2 += ystep_line;
8595       DrawTextSCentered(ystart2, font_info,
8596                         "press the 'menu' button.");
8597 #else
8598       DrawTextSCentered(ystart2, font_info,
8599                         "To correct a mistake,");
8600       ystart2 += ystep_line;
8601       DrawTextSCentered(ystart2, font_info,
8602                         "press the 'backspace' key.");
8603       ystart2 += ystep_line;
8604       DrawTextSCentered(ystart2, font_info,
8605                         "To skip a button or axis,");
8606       ystart2 += ystep_line;
8607       DrawTextSCentered(ystart2, font_info,
8608                         "press the 'return' key.");
8609       ystart2 += ystep_line;
8610       DrawTextSCentered(ystart2, font_info,
8611                         "To exit, press the 'escape' key.");
8612 #endif
8613
8614       BlitBitmapMasked(controller, drawto, 0, 0,
8615                        controller->width, controller->height,
8616                        controller_x, controller_y);
8617
8618       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
8619       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
8620
8621       BlitBitmapMasked(marker, drawto, 0, 0,
8622                        marker->width, marker->height,
8623                        marker_x, marker_y);
8624
8625       if (!screen_initialized)
8626         FadeIn(REDRAW_FIELD);
8627       else
8628         BackToFront();
8629
8630       screen_initialized = TRUE;
8631
8632       while (NextValidEvent(&event))
8633       {
8634         switch (event.type)
8635         {
8636           case SDL_JOYAXISMOTION:
8637             if (event.jaxis.value > 20000 ||
8638                 event.jaxis.value < -20000)
8639             {
8640               for (j = 0; j < i; j++)
8641                 if (steps[j].axis == event.jaxis.axis)
8642                   break;
8643
8644               if (j == i)
8645               {
8646                 if (step->marker != MARKER_AXIS_X &&
8647                     step->marker != MARKER_AXIS_Y)
8648                   break;
8649
8650                 step->axis = event.jaxis.axis;
8651                 strcat(mapping, step->field);
8652                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
8653                 strcat(mapping, temp);
8654                 i++;
8655                 next = TRUE;
8656               }
8657             }
8658
8659             break;
8660
8661           case SDL_JOYHATMOTION:
8662             // ignore centering; we're probably just coming back
8663             // to the center from the previous item we set
8664             if (event.jhat.value == SDL_HAT_CENTERED)
8665               break;
8666
8667             for (j = 0; j < i; j++)
8668               if (steps[j].hat == event.jhat.hat &&
8669                   steps[j].hat_value == event.jhat.value)
8670                 break;
8671
8672             if (j == i)
8673             {
8674               step->hat = event.jhat.hat;
8675               step->hat_value = event.jhat.value;
8676               strcat(mapping, step->field);
8677               snprintf(temp, sizeof(temp), ":h%u.%u,",
8678                        event.jhat.hat, event.jhat.value );
8679               strcat(mapping, temp);
8680               i++;
8681               next = TRUE;
8682             }
8683
8684             break;
8685
8686           case SDL_JOYBALLMOTION:
8687             break;
8688
8689           case SDL_JOYBUTTONUP:
8690             for (j = 0; j < i; j++)
8691               if (steps[j].button == event.jbutton.button)
8692                 break;
8693
8694             if (j == i)
8695             {
8696               step->button = event.jbutton.button;
8697               strcat(mapping, step->field);
8698               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
8699               strcat(mapping, temp);
8700               i++;
8701               next = TRUE;
8702             }
8703
8704             break;
8705
8706           case SDL_FINGERDOWN:
8707           case SDL_MOUSEBUTTONDOWN:
8708             // skip this step
8709             i++;
8710             next = TRUE;
8711
8712             break;
8713
8714           case SDL_KEYDOWN:
8715             if (event.key.keysym.sym == KSYM_BackSpace ||
8716                 event.key.keysym.sym == KSYM_Back)
8717             {
8718               if (i == 0)
8719               {
8720                 // leave screen
8721                 success = FALSE;
8722                 done = TRUE;
8723
8724                 break;
8725               }
8726
8727               // undo this step
8728               prev_step = &steps[i - 1];
8729               strcpy(mapping, prev_step->mapping);
8730               i--;
8731               next = TRUE;
8732
8733               break;
8734             }
8735
8736             if (event.key.keysym.sym == KSYM_space ||
8737                 event.key.keysym.sym == KSYM_Return ||
8738                 event.key.keysym.sym == KSYM_Menu)
8739             {
8740               // skip this step
8741               i++;
8742               next = TRUE;
8743
8744               break;
8745             }
8746
8747             if (event.key.keysym.sym == KSYM_Escape)
8748             {
8749               // leave screen
8750               success = FALSE;
8751               done = TRUE;
8752             }
8753
8754             break;
8755
8756           case SDL_QUIT:
8757             program.exit_function(0);
8758             break;
8759
8760           default:
8761             break;
8762         }
8763
8764         // do not handle events for longer than standard frame delay period
8765         if (DelayReached(&event_frame_delay, event_frame_delay_value))
8766           break;
8767       }
8768     }
8769   }
8770
8771   if (success)
8772   {
8773 #if DEBUG_JOYSTICKS
8774     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
8775 #endif
8776
8777     // activate mapping for this game
8778     SDL_GameControllerAddMapping(mapping);
8779
8780     // save mapping to personal mappings
8781     SaveSetup_AddGameControllerMapping(mapping);
8782   }
8783
8784   // wait until the last pending event was removed from event queue
8785   while (NextValidEvent(&event));
8786
8787   return success;
8788 }
8789
8790 static int ConfigureJoystickMain(int player_nr)
8791 {
8792   char *device_name = setup.input[player_nr].joy.device_name;
8793   int joystick_nr = getJoystickNrFromDeviceName(device_name);
8794   boolean joystick_active = CheckJoystickOpened(joystick_nr);
8795   int success = FALSE;
8796   int i;
8797
8798   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
8799     return JOYSTICK_NOT_AVAILABLE;
8800
8801   if (!joystick_active || !setup.input[player_nr].use_joystick)
8802     return JOYSTICK_NOT_AVAILABLE;
8803
8804   FadeSetEnterMenu();
8805   FadeOut(REDRAW_FIELD);
8806
8807   // close all joystick devices (potentially opened as game controllers)
8808   for (i = 0; i < SDL_NumJoysticks(); i++)
8809     SDLCloseJoystick(i);
8810
8811   // open joystick device as plain joystick to configure as game controller
8812   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
8813
8814   // as the joystick was successfully opened before, this should not happen
8815   if (joystick == NULL)
8816     return FALSE;
8817
8818   // create new game controller mapping (buttons and axes) for joystick device
8819   success = ConfigureJoystickMapButtonsAndAxes(joystick);
8820
8821   // close joystick (and maybe re-open as configured game controller later)
8822   SDL_JoystickClose(joystick);
8823
8824   // re-open all joystick devices (potentially as game controllers)
8825   for (i = 0; i < SDL_NumJoysticks(); i++)
8826     SDLOpenJoystick(i);
8827
8828   // clear all joystick input actions for all joystick devices
8829   SDLClearJoystickState();
8830
8831   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
8832 }
8833
8834 void ConfigureJoystick(int player_nr)
8835 {
8836   boolean state = ConfigureJoystickMain(player_nr);
8837
8838   if (state != JOYSTICK_NOT_CONFIGURED)
8839   {
8840     boolean success = (state == JOYSTICK_CONFIGURED);
8841     char message1[MAX_OUTPUT_LINESIZE + 1];
8842     char *message2 = (success ? "configured!" : "not available!");
8843     char *device_name = setup.input[player_nr].joy.device_name;
8844     int nr = getJoystickNrFromDeviceName(device_name) + 1;
8845     int font_nr = FONT_TITLE_1;
8846     int font_height = getFontHeight(font_nr);
8847     int ypos1 = SYSIZE / 2 - font_height * 2;
8848     int ypos2 = SYSIZE / 2 - font_height * 1;
8849     unsigned int wait_frame_delay = 0;
8850     unsigned int wait_frame_delay_value = 2000;
8851
8852     ResetDelayCounter(&wait_frame_delay);
8853
8854     ClearField();
8855
8856     sprintf(message1, "Joystick %d", nr);
8857
8858     DrawTextSCentered(ypos1, font_nr, message1);
8859     DrawTextSCentered(ypos2, font_nr, message2);
8860
8861     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8862       BackToFront();
8863
8864     ClearEventQueue();
8865   }
8866
8867   DrawSetupScreen_Input();
8868 }
8869
8870 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
8871 {
8872   if (y < video.screen_height / 3)
8873   {
8874     // remap touch gadgets to access upper part of the screen
8875     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8876     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
8877   }
8878   else if (y > 2 * video.screen_height / 3)
8879   {
8880     // remap touch gadgets to access lower part of the screen
8881     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8882     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
8883   }
8884 }
8885
8886 static boolean ConfigureVirtualButtonsMain(void)
8887 {
8888   static char *customize_step_text[] =
8889   {
8890     "Move Left",
8891     "Move Right",
8892     "Move Up",
8893     "Move Down",
8894     "Snap Field",
8895     "Drop Element"
8896   };
8897   char grid_button[] =
8898   {
8899     CHAR_GRID_BUTTON_LEFT,
8900     CHAR_GRID_BUTTON_RIGHT,
8901     CHAR_GRID_BUTTON_UP,
8902     CHAR_GRID_BUTTON_DOWN,
8903     CHAR_GRID_BUTTON_SNAP,
8904     CHAR_GRID_BUTTON_DROP
8905   };
8906   enum
8907   {
8908     ACTION_NONE,
8909     ACTION_ESCAPE,
8910     ACTION_BACK,
8911     ACTION_NEXT
8912   };
8913   int font_nr = FONT_INPUT_1_ACTIVE;
8914   int font_height = getFontHeight(font_nr);
8915   int ypos1 = SYSIZE / 2 - font_height * 2;
8916   int ypos2 = SYSIZE / 2 - font_height * 1;
8917   boolean success = FALSE;
8918   boolean finished = FALSE;
8919   int step_nr = 0;
8920   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
8921   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
8922   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
8923   boolean set_grid_button = FALSE;
8924   int nr = GRID_ACTIVE_NR();
8925   int x, y;
8926
8927   for (x = 0; x < MAX_GRID_XSIZE; x++)
8928     for (y = 0; y < MAX_GRID_YSIZE; y++)
8929       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
8930
8931   overlay.grid_button_highlight = grid_button[step_nr];
8932
8933   UnmapAllGadgets();
8934
8935   FadeSetEnterMenu();
8936   FadeOut(REDRAW_FIELD);
8937
8938   ClearField();
8939
8940   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
8941   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
8942   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
8943
8944   FadeIn(REDRAW_FIELD);
8945
8946   SetOverlayShowGrid(TRUE);
8947
8948   // map gadgets for setup touch buttons menu screen
8949   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
8950
8951   while (!finished)
8952   {
8953     Event event;
8954
8955     while (NextValidEvent(&event))
8956     {
8957       int action = ACTION_NONE;
8958
8959       // ---------- handle events and set the resulting action ----------
8960
8961       switch (event.type)
8962       {
8963         case EVENT_USER:
8964           {
8965             UserEvent *user = (UserEvent *)&event;
8966             int id = user->value1;
8967
8968             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
8969                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
8970                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
8971                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
8972                       ACTION_NONE);
8973           }
8974           break;
8975
8976         case EVENT_KEYPRESS:
8977           {
8978             Key key = GetEventKey((KeyEvent *)&event, FALSE);
8979
8980             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
8981                       key == KSYM_BackSpace ||
8982                       key == KSYM_Back ?        ACTION_BACK :
8983                       key == KSYM_Return ||
8984                       key == KSYM_Menu ||
8985                       key == KSYM_space ?       ACTION_NEXT :
8986                       ACTION_NONE);
8987           }
8988           break;
8989
8990         case EVENT_KEYRELEASE:
8991           key_joystick_mapping = 0;
8992           break;
8993
8994         case EVENT_BUTTONPRESS:
8995         case EVENT_BUTTONRELEASE:
8996           {
8997             ButtonEvent *button = (ButtonEvent *)&event;
8998
8999             motion_status = FALSE;
9000
9001             if (button->type == EVENT_BUTTONPRESS)
9002               button_status = button->button;
9003             else
9004               button_status = MB_RELEASED;
9005
9006             if (HandleGadgets(button->x, button->y, button_status))
9007             {
9008               // do not handle this button event anymore
9009               break;
9010             }
9011
9012             button->x += video.screen_xoffset;
9013             button->y += video.screen_yoffset;
9014
9015             x = button->x * overlay.grid_xsize / video.screen_width;
9016             y = button->y * overlay.grid_ysize / video.screen_height;
9017
9018             if (button->type == EVENT_BUTTONPRESS)
9019             {
9020               grid_button_draw =
9021                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9022                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9023
9024               set_grid_button = TRUE;
9025             }
9026
9027             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9028           }
9029           break;
9030
9031         case EVENT_MOTIONNOTIFY:
9032           {
9033             MotionEvent *motion = (MotionEvent *)&event;
9034
9035             motion_status = TRUE;
9036
9037             if (HandleGadgets(motion->x, motion->y, button_status))
9038             {
9039               // do not handle this button event anymore
9040               break;
9041             }
9042
9043             motion->x += video.screen_xoffset;
9044             motion->y += video.screen_yoffset;
9045
9046             x = motion->x * overlay.grid_xsize / video.screen_width;
9047             y = motion->y * overlay.grid_ysize / video.screen_height;
9048
9049             set_grid_button = TRUE;
9050
9051             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9052           }
9053           break;
9054
9055         case SDL_WINDOWEVENT:
9056           HandleWindowEvent((WindowEvent *) &event);
9057
9058           // check if device has been rotated
9059           if (nr != GRID_ACTIVE_NR())
9060           {
9061             nr = GRID_ACTIVE_NR();
9062
9063             for (x = 0; x < MAX_GRID_XSIZE; x++)
9064               for (y = 0; y < MAX_GRID_YSIZE; y++)
9065                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9066                   overlay.grid_button[x][y];
9067           }
9068
9069           break;
9070
9071         case SDL_APP_WILLENTERBACKGROUND:
9072         case SDL_APP_DIDENTERBACKGROUND:
9073         case SDL_APP_WILLENTERFOREGROUND:
9074         case SDL_APP_DIDENTERFOREGROUND:
9075           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9076           break;
9077
9078         default:
9079           HandleOtherEvents(&event);
9080           break;
9081       }
9082
9083       // ---------- perform action set by handling events ----------
9084
9085       if (action == ACTION_ESCAPE)
9086       {
9087         // abort and restore the old key bindings
9088
9089         for (x = 0; x < MAX_GRID_XSIZE; x++)
9090           for (y = 0; y < MAX_GRID_YSIZE; y++)
9091             overlay.grid_button[x][y] = grid_button_old[x][y];
9092
9093         FadeSkipNextFadeIn();
9094
9095         finished = TRUE;
9096       }
9097       else if (action == ACTION_BACK)
9098       {
9099         // keep the configured key bindings and go to previous page
9100
9101         step_nr--;
9102
9103         if (step_nr < 0)
9104         {
9105           FadeSkipNextFadeIn();
9106
9107           finished = TRUE;
9108         }
9109       }
9110       else if (action == ACTION_NEXT)
9111       {
9112         // keep the configured key bindings and go to next page
9113
9114         step_nr++;
9115
9116         // all virtual buttons configured
9117         if (step_nr == 6)
9118         {
9119           finished = TRUE;
9120           success = TRUE;
9121         }
9122       }
9123
9124       if (action != ACTION_NONE && !finished)
9125       {
9126         for (x = 0; x < MAX_GRID_XSIZE; x++)
9127           for (y = 0; y < MAX_GRID_YSIZE; y++)
9128             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9129
9130         overlay.grid_button_highlight = grid_button[step_nr];
9131
9132         // configure next virtual button
9133
9134         ClearField();
9135
9136         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9137         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9138         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9139       }
9140
9141       if (set_grid_button)
9142       {
9143         overlay.grid_button[x][y] =
9144           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9145            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9146            grid_button_tmp[x][y]);
9147
9148         set_grid_button = FALSE;
9149       }
9150     }
9151
9152     BackToFront();
9153   }
9154
9155   for (x = 0; x < MAX_GRID_XSIZE; x++)
9156     for (y = 0; y < MAX_GRID_YSIZE; y++)
9157       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9158
9159   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9160
9161   SetOverlayShowGrid(FALSE);
9162
9163   return success;
9164 }
9165
9166 void ConfigureVirtualButtons(void)
9167 {
9168   boolean success = ConfigureVirtualButtonsMain();
9169
9170   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9171                          SCREEN_MASK_TOUCH2);
9172
9173   if (success)
9174   {
9175     int font_nr = FONT_TITLE_1;
9176     int font_height = getFontHeight(font_nr);
9177     int ypos1 = SYSIZE / 2 - font_height * 2;
9178     int ypos2 = SYSIZE / 2 - font_height * 1;
9179     unsigned int wait_frame_delay = 0;
9180     unsigned int wait_frame_delay_value = 2000;
9181
9182     ResetDelayCounter(&wait_frame_delay);
9183
9184     ClearField();
9185
9186     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9187     DrawTextSCentered(ypos2, font_nr, "configured!");
9188
9189     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9190       BackToFront();
9191
9192     ClearEventQueue();
9193   }
9194 }
9195
9196 void DrawSetupScreen(void)
9197 {
9198   align_xoffset = 0;
9199   align_yoffset = 0;
9200
9201   if (setup_mode == SETUP_MODE_INPUT)
9202     DrawSetupScreen_Input();
9203   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9204     DrawChooseTree(&scores_type_current);
9205   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9206     DrawChooseTree(&game_speed_current);
9207   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9208     DrawChooseTree(&scroll_delay_current);
9209   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9210     DrawChooseTree(&snapshot_mode_current);
9211   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9212     DrawChooseTree(&window_size_current);
9213   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9214     DrawChooseTree(&scaling_type_current);
9215   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9216     DrawChooseTree(&rendering_mode_current);
9217   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9218     DrawChooseTree(&vsync_mode_current);
9219   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9220     DrawChooseTree(&artwork.gfx_current);
9221   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9222     DrawChooseTree(&artwork.snd_current);
9223   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9224     DrawChooseTree(&artwork.mus_current);
9225   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9226     DrawChooseTree(&volume_simple_current);
9227   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9228     DrawChooseTree(&volume_loops_current);
9229   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9230     DrawChooseTree(&volume_music_current);
9231   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9232     DrawChooseTree(&touch_control_current);
9233   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9234     DrawChooseTree(&move_distance_current);
9235   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9236     DrawChooseTree(&drop_distance_current);
9237   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9238     DrawChooseTree(&transparency_current);
9239   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9240     DrawChooseTree(&grid_size_current[0][0]);
9241   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9242     DrawChooseTree(&grid_size_current[0][1]);
9243   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9244     DrawChooseTree(&grid_size_current[1][0]);
9245   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9246     DrawChooseTree(&grid_size_current[1][1]);
9247   else
9248     DrawSetupScreen_Generic();
9249
9250   PlayMenuSoundsAndMusic();
9251 }
9252
9253 void RedrawSetupScreenAfterFullscreenToggle(void)
9254 {
9255   if (setup_mode == SETUP_MODE_GRAPHICS ||
9256       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9257   {
9258     // update list selection from "setup.window_scaling_percent"
9259     execSetupGraphics_setWindowSizes(TRUE);
9260
9261     DrawSetupScreen();
9262   }
9263 }
9264
9265 void RedrawSetupScreenAfterScreenRotation(int nr)
9266 {
9267   int x, y;
9268
9269   if (setup_mode == SETUP_MODE_TOUCH)
9270   {
9271     // update virtual button settings (depending on screen orientation)
9272     DrawSetupScreen();
9273   }
9274   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
9275   {
9276     // save already configured virtual buttons
9277     for (x = 0; x < MAX_GRID_XSIZE; x++)
9278       for (y = 0; y < MAX_GRID_YSIZE; y++)
9279         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9280   }
9281 }
9282
9283 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
9284 {
9285   if (setup_mode == SETUP_MODE_INPUT)
9286     HandleSetupScreen_Input(mx, my, dx, dy, button);
9287   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9288     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
9289   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9290     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
9291   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9292     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
9293   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9294     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
9295   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9296     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
9297   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9298     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
9299   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9300     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
9301   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9302     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
9303   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9304     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
9305   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9306     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
9307   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9308     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
9309   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9310     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
9311   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9312     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
9313   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9314     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
9315   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9316     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
9317   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9318     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
9319   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9320     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
9321   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9322     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
9323   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9324     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
9325   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9326     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
9327   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9328     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
9329   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9330     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
9331   else
9332     HandleSetupScreen_Generic(mx, my, dx, dy, button);
9333 }
9334
9335 void HandleGameActions(void)
9336 {
9337   if (setup.ask_on_game_over)
9338     CheckGameOver();
9339
9340   if (game.restart_game_message != NULL)
9341   {
9342     RequestRestartGame(game.restart_game_message);
9343
9344     return;
9345   }
9346
9347   if (game_status != GAME_MODE_PLAYING)
9348     return;
9349
9350   GameActions();                // main game loop
9351
9352   if (tape.auto_play && !tape.playing)
9353     AutoPlayTapesContinue();    // continue automatically playing next tape
9354 }
9355
9356
9357 // ---------- new screen button stuff --------------------------------------
9358
9359 static struct
9360 {
9361   int gfx_unpressed, gfx_pressed;
9362   struct MenuPosInfo *pos;
9363   boolean *check_value;
9364   int gadget_id;
9365   int screen_mask;
9366   unsigned int event_mask;
9367   boolean is_touch_button;
9368   char *infotext;
9369 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
9370 {
9371   {
9372     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
9373     &menu.main.button.prev_level, NULL,
9374     SCREEN_CTRL_ID_PREV_LEVEL,
9375     SCREEN_MASK_MAIN,
9376     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9377     FALSE, "previous level"
9378   },
9379   {
9380     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
9381     &menu.main.button.next_level, NULL,
9382     SCREEN_CTRL_ID_NEXT_LEVEL,
9383     SCREEN_MASK_MAIN,
9384     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9385     FALSE, "next level"
9386   },
9387   {
9388     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE,
9389     &menu.scores.button.prev_level, NULL,
9390     SCREEN_CTRL_ID_PREV_LEVEL2,
9391     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9392     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9393     FALSE, "previous level"
9394   },
9395   {
9396     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE,
9397     &menu.scores.button.next_level, NULL,
9398     SCREEN_CTRL_ID_NEXT_LEVEL2,
9399     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9400     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9401     FALSE, "next level"
9402   },
9403   {
9404     IMG_MENU_BUTTON_PREV_SCORE, IMG_MENU_BUTTON_PREV_SCORE_ACTIVE,
9405     &menu.scores.button.prev_score, NULL,
9406     SCREEN_CTRL_ID_PREV_SCORE,
9407     SCREEN_MASK_SCORES_INFO,
9408     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9409     FALSE, "previous score"
9410   },
9411   {
9412     IMG_MENU_BUTTON_NEXT_SCORE, IMG_MENU_BUTTON_NEXT_SCORE_ACTIVE,
9413     &menu.scores.button.next_score, NULL,
9414     SCREEN_CTRL_ID_NEXT_SCORE,
9415     SCREEN_MASK_SCORES_INFO,
9416     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9417     FALSE, "next score"
9418   },
9419   {
9420     IMG_MENU_BUTTON_PLAY_TAPE, IMG_MENU_BUTTON_PLAY_TAPE,
9421     &menu.scores.button.play_tape, NULL,
9422     SCREEN_CTRL_ID_PLAY_TAPE,
9423     SCREEN_MASK_SCORES_INFO,
9424     GD_EVENT_RELEASED,
9425     FALSE, "play tape"
9426   },
9427   {
9428     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE,
9429     &menu.main.button.first_level, NULL,
9430     SCREEN_CTRL_ID_FIRST_LEVEL,
9431     SCREEN_MASK_MAIN,
9432     GD_EVENT_RELEASED,
9433     FALSE, "first level"
9434   },
9435   {
9436     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE,
9437     &menu.main.button.last_level, NULL,
9438     SCREEN_CTRL_ID_LAST_LEVEL,
9439     SCREEN_MASK_MAIN,
9440     GD_EVENT_RELEASED,
9441     FALSE, "last level"
9442   },
9443   {
9444     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE,
9445     &menu.main.button.level_number, NULL,
9446     SCREEN_CTRL_ID_LEVEL_NUMBER,
9447     SCREEN_MASK_MAIN,
9448     GD_EVENT_RELEASED,
9449     FALSE, "level number"
9450   },
9451   {
9452     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
9453     &menu.setup.button.prev_player, NULL,
9454     SCREEN_CTRL_ID_PREV_PLAYER,
9455     SCREEN_MASK_INPUT,
9456     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9457     FALSE, "previous player"
9458   },
9459   {
9460     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
9461     &menu.setup.button.next_player, NULL,
9462     SCREEN_CTRL_ID_NEXT_PLAYER,
9463     SCREEN_MASK_INPUT,
9464     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9465     FALSE, "next player"
9466   },
9467   {
9468     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE,
9469     &menu.main.button.insert_solution, NULL,
9470     SCREEN_CTRL_ID_INSERT_SOLUTION,
9471     SCREEN_MASK_MAIN_HAS_SOLUTION,
9472     GD_EVENT_RELEASED,
9473     FALSE, "insert solution tape"
9474   },
9475   {
9476     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE,
9477     &menu.main.button.play_solution, NULL,
9478     SCREEN_CTRL_ID_PLAY_SOLUTION,
9479     SCREEN_MASK_MAIN_HAS_SOLUTION,
9480     GD_EVENT_RELEASED,
9481     FALSE, "play solution tape"
9482   },
9483   {
9484     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE,
9485     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
9486     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
9487     SCREEN_MASK_MAIN,
9488     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
9489     FALSE, "switch ECS/AGA chipset"
9490   },
9491   {
9492     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK,
9493     &menu.setup.button.touch_back, NULL,
9494     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
9495     SCREEN_MASK_TOUCH,
9496     GD_EVENT_RELEASED,
9497     TRUE, "previous page"
9498   },
9499   {
9500     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT,
9501     &menu.setup.button.touch_next, NULL,
9502     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
9503     SCREEN_MASK_TOUCH,
9504     GD_EVENT_RELEASED,
9505     TRUE, "next page"
9506   },
9507   {
9508     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2,
9509     &menu.setup.button.touch_back2, NULL,
9510     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
9511     SCREEN_MASK_TOUCH2,
9512     GD_EVENT_RELEASED,
9513     TRUE, "previous page"
9514   },
9515   {
9516     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2,
9517     &menu.setup.button.touch_next2, NULL,
9518     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
9519     SCREEN_MASK_TOUCH2,
9520     GD_EVENT_RELEASED,
9521     TRUE, "next page"
9522   },
9523 };
9524
9525 static struct
9526 {
9527   int gfx_unpressed, gfx_pressed;
9528   int x, y;
9529   int gadget_id;
9530   char *infotext;
9531 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
9532 {
9533   {
9534     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
9535     -1, -1,     // these values are not constant, but can change at runtime
9536     SCREEN_CTRL_ID_SCROLL_UP,
9537     "scroll up"
9538   },
9539   {
9540     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
9541     -1, -1,     // these values are not constant, but can change at runtime
9542     SCREEN_CTRL_ID_SCROLL_DOWN,
9543     "scroll down"
9544   }
9545 };
9546
9547 static struct
9548 {
9549   int gfx_unpressed, gfx_pressed;
9550   int x, y;
9551   int width, height;
9552   int type;
9553   int gadget_id;
9554   char *infotext;
9555 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
9556 {
9557   {
9558     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
9559     -1, -1,     // these values are not constant, but can change at runtime
9560     -1, -1,     // these values are not constant, but can change at runtime
9561     GD_TYPE_SCROLLBAR_VERTICAL,
9562     SCREEN_CTRL_ID_SCROLL_VERTICAL,
9563     "scroll level series vertically"
9564   }
9565 };
9566
9567 static struct
9568 {
9569   int graphic;
9570   int gadget_id;
9571   int x, y;
9572   int size;
9573   char *value;
9574   char *infotext;
9575 } textinput_info[NUM_SCREEN_TEXTINPUT] =
9576 {
9577   {
9578     IMG_SETUP_INPUT_TEXT,
9579     SCREEN_CTRL_ID_NETWORK_SERVER,
9580     -1, -1,     // these values are not constant, but can change at runtime
9581     MAX_SETUP_TEXT_INPUT_LEN,
9582     network_server_hostname,
9583     "Network Server Hostname / IP"
9584   },
9585 };
9586
9587 static void CreateScreenMenubuttons(void)
9588 {
9589   struct GadgetInfo *gi;
9590   unsigned int event_mask;
9591   int i;
9592
9593   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9594   {
9595     struct MenuPosInfo *pos = menubutton_info[i].pos;
9596     int screen_mask = menubutton_info[i].screen_mask;
9597     boolean is_touch_button = menubutton_info[i].is_touch_button;
9598     boolean is_check_button = menubutton_info[i].check_value != NULL;
9599     boolean is_score_button = (screen_mask & SCREEN_MASK_SCORES_INFO);
9600     boolean has_gfx_pressed = (menubutton_info[i].gfx_pressed ==
9601                                menubutton_info[i].gfx_unpressed);
9602     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9603     int gfx_unpressed, gfx_pressed;
9604     int x, y, width, height;
9605     int gd_x1, gd_x2, gd_y1, gd_y2;
9606     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
9607     int id = menubutton_info[i].gadget_id;
9608     int type = GD_TYPE_NORMAL_BUTTON;
9609     boolean checked = FALSE;
9610
9611     event_mask = menubutton_info[i].event_mask;
9612
9613     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
9614     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
9615
9616     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
9617     height = graphic_info[menubutton_info[i].gfx_pressed].height;
9618
9619     gfx_unpressed = menubutton_info[i].gfx_unpressed;
9620     gfx_pressed   = menubutton_info[i].gfx_pressed;
9621     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9622     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9623     gd_x1 = graphic_info[gfx_unpressed].src_x;
9624     gd_y1 = graphic_info[gfx_unpressed].src_y;
9625     gd_x2 = graphic_info[gfx_pressed].src_x;
9626     gd_y2 = graphic_info[gfx_pressed].src_y;
9627     gd_x1a = gd_x1;
9628     gd_y1a = gd_y1;
9629     gd_x2a = gd_x2;
9630     gd_y2a = gd_y2;
9631
9632     if (has_gfx_pressed)
9633     {
9634       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
9635       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
9636     }
9637
9638     if (is_check_button)
9639     {
9640       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
9641       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
9642       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
9643       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
9644
9645       type = GD_TYPE_CHECK_BUTTON;
9646       checked = *menubutton_info[i].check_value;
9647     }
9648
9649     if (is_score_button)
9650     {
9651       // if x/y set to -1, dynamically place buttons next to title text
9652       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
9653
9654       if (pos->x == -1)
9655         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
9656              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
9657              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
9658              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
9659
9660       if (pos->y == -1)
9661         y = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ||
9662              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ? mSY + MENU_TITLE1_YPOS : 0);
9663     }
9664
9665     gi = CreateGadget(GDI_CUSTOM_ID, id,
9666                       GDI_CUSTOM_TYPE_ID, i,
9667                       GDI_IMAGE_ID, gfx_unpressed,
9668                       GDI_INFO_TEXT, menubutton_info[i].infotext,
9669                       GDI_X, x,
9670                       GDI_Y, y,
9671                       GDI_WIDTH, width,
9672                       GDI_HEIGHT, height,
9673                       GDI_TYPE, type,
9674                       GDI_STATE, GD_BUTTON_UNPRESSED,
9675                       GDI_CHECKED, checked,
9676                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9677                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9678                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1a, gd_y1a,
9679                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2a, gd_y2a,
9680                       GDI_DIRECT_DRAW, FALSE,
9681                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
9682                       GDI_EVENT_MASK, event_mask,
9683                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9684                       GDI_END);
9685
9686     if (gi == NULL)
9687       Fail("cannot create gadget");
9688
9689     screen_gadget[id] = gi;
9690   }
9691 }
9692
9693 static void CreateScreenScrollbuttons(void)
9694 {
9695   struct GadgetInfo *gi;
9696   unsigned int event_mask;
9697   int i;
9698
9699   // these values are not constant, but can change at runtime
9700   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
9701   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
9702   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
9703   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
9704
9705   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
9706   {
9707     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9708     int gfx_unpressed, gfx_pressed;
9709     int x, y, width, height;
9710     int gd_x1, gd_x2, gd_y1, gd_y2;
9711     int id = scrollbutton_info[i].gadget_id;
9712
9713     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
9714
9715     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
9716     y = mSY + scrollbutton_info[i].y;
9717     width = SC_SCROLLBUTTON_XSIZE;
9718     height = SC_SCROLLBUTTON_YSIZE;
9719
9720     // correct scrollbar position if placed outside menu (playfield) area
9721     if (x > SX + SC_SCROLL_UP_XPOS)
9722       x = SX + SC_SCROLL_UP_XPOS;
9723
9724     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
9725       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
9726                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
9727
9728     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
9729     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
9730     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9731     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9732     gd_x1 = graphic_info[gfx_unpressed].src_x;
9733     gd_y1 = graphic_info[gfx_unpressed].src_y;
9734     gd_x2 = graphic_info[gfx_pressed].src_x;
9735     gd_y2 = graphic_info[gfx_pressed].src_y;
9736
9737     gi = CreateGadget(GDI_CUSTOM_ID, id,
9738                       GDI_CUSTOM_TYPE_ID, i,
9739                       GDI_IMAGE_ID, gfx_unpressed,
9740                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
9741                       GDI_X, x,
9742                       GDI_Y, y,
9743                       GDI_WIDTH, width,
9744                       GDI_HEIGHT, height,
9745                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
9746                       GDI_STATE, GD_BUTTON_UNPRESSED,
9747                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9748                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9749                       GDI_DIRECT_DRAW, FALSE,
9750                       GDI_EVENT_MASK, event_mask,
9751                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9752                       GDI_END);
9753
9754     if (gi == NULL)
9755       Fail("cannot create gadget");
9756
9757     screen_gadget[id] = gi;
9758   }
9759 }
9760
9761 static void CreateScreenScrollbars(void)
9762 {
9763   int i;
9764
9765   // these values are not constant, but can change at runtime
9766   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
9767   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
9768   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
9769   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
9770
9771   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
9772   {
9773     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9774     int gfx_unpressed, gfx_pressed;
9775     int x, y, width, height;
9776     int gd_x1, gd_x2, gd_y1, gd_y2;
9777     struct GadgetInfo *gi;
9778     int items_max, items_visible, item_position;
9779     unsigned int event_mask;
9780     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
9781     int id = scrollbar_info[i].gadget_id;
9782
9783     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
9784
9785     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
9786     y = mSY + scrollbar_info[i].y;
9787     width  = scrollbar_info[i].width;
9788     height = scrollbar_info[i].height;
9789
9790     // correct scrollbar position if placed outside menu (playfield) area
9791     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
9792       x = SX + SC_SCROLL_VERTICAL_XPOS;
9793
9794     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
9795       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
9796
9797     items_max = num_page_entries;
9798     items_visible = num_page_entries;
9799     item_position = 0;
9800
9801     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
9802     gfx_pressed   = scrollbar_info[i].gfx_pressed;
9803     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9804     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9805     gd_x1 = graphic_info[gfx_unpressed].src_x;
9806     gd_y1 = graphic_info[gfx_unpressed].src_y;
9807     gd_x2 = graphic_info[gfx_pressed].src_x;
9808     gd_y2 = graphic_info[gfx_pressed].src_y;
9809
9810     gi = CreateGadget(GDI_CUSTOM_ID, id,
9811                       GDI_CUSTOM_TYPE_ID, i,
9812                       GDI_IMAGE_ID, gfx_unpressed,
9813                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
9814                       GDI_X, x,
9815                       GDI_Y, y,
9816                       GDI_WIDTH, width,
9817                       GDI_HEIGHT, height,
9818                       GDI_TYPE, scrollbar_info[i].type,
9819                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
9820                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
9821                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
9822                       GDI_WHEEL_AREA_X, SX,
9823                       GDI_WHEEL_AREA_Y, SY,
9824                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
9825                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
9826                       GDI_STATE, GD_BUTTON_UNPRESSED,
9827                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
9828                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
9829                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
9830                       GDI_DIRECT_DRAW, FALSE,
9831                       GDI_EVENT_MASK, event_mask,
9832                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9833                       GDI_END);
9834
9835     if (gi == NULL)
9836       Fail("cannot create gadget");
9837
9838     screen_gadget[id] = gi;
9839   }
9840 }
9841
9842 static void CreateScreenTextInputGadgets(void)
9843 {
9844   int i;
9845
9846   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
9847   {
9848     int graphic = textinput_info[i].graphic;
9849     struct GraphicInfo *gd = &graphic_info[graphic];
9850     int gd_x1 = gd->src_x;
9851     int gd_y1 = gd->src_y;
9852     int gd_x2 = gd->src_x + gd->active_xoffset;
9853     int gd_y2 = gd->src_y + gd->active_yoffset;
9854     struct GadgetInfo *gi;
9855     unsigned int event_mask;
9856     int id = textinput_info[i].gadget_id;
9857     int x = textinput_info[i].x;
9858     int y = textinput_info[i].y;
9859
9860     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
9861
9862     gi = CreateGadget(GDI_CUSTOM_ID, id,
9863                       GDI_CUSTOM_TYPE_ID, i,
9864                       GDI_INFO_TEXT, textinput_info[i].infotext,
9865                       GDI_X, SX + x,
9866                       GDI_Y, SY + y,
9867                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
9868                       GDI_TEXT_VALUE, textinput_info[i].value,
9869                       GDI_TEXT_SIZE, textinput_info[i].size,
9870                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
9871                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
9872                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
9873                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
9874                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
9875                       GDI_DESIGN_WIDTH, gd->width,
9876                       GDI_EVENT_MASK, event_mask,
9877                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
9878                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
9879                       GDI_END);
9880
9881     if (gi == NULL)
9882       Fail("cannot create gadget");
9883
9884     screen_gadget[id] = gi;
9885   }
9886 }
9887
9888 void CreateScreenGadgets(void)
9889 {
9890   CreateScreenMenubuttons();
9891
9892   CreateScreenScrollbuttons();
9893   CreateScreenScrollbars();
9894
9895   CreateScreenTextInputGadgets();
9896 }
9897
9898 void FreeScreenGadgets(void)
9899 {
9900   int i;
9901
9902   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
9903     FreeGadget(screen_gadget[i]);
9904 }
9905
9906 static void RedrawScreenMenuGadgets(int screen_mask)
9907 {
9908   int i;
9909
9910   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9911     if (screen_mask & menubutton_info[i].screen_mask)
9912       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
9913 }
9914
9915 static void MapScreenMenuGadgets(int screen_mask)
9916 {
9917   int i;
9918
9919   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9920     if (screen_mask & menubutton_info[i].screen_mask)
9921       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
9922 }
9923
9924 static void UnmapScreenMenuGadgets(int screen_mask)
9925 {
9926   int i;
9927
9928   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9929   {
9930     if (screen_mask & menubutton_info[i].screen_mask)
9931     {
9932       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
9933
9934       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
9935         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
9936                        screen_gadget[menubutton_info[i].gadget_id]->y,
9937                        screen_gadget[menubutton_info[i].gadget_id]->width,
9938                        screen_gadget[menubutton_info[i].gadget_id]->height);
9939     }
9940   }
9941 }
9942
9943 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
9944 {
9945   if (map_gadgets)
9946     MapScreenMenuGadgets(screen_mask);
9947   else
9948     UnmapScreenMenuGadgets(screen_mask);
9949 }
9950
9951 static void MapScreenGadgets(int num_entries)
9952 {
9953   int i;
9954
9955   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
9956     return;
9957
9958   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
9959     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
9960
9961   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
9962     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
9963 }
9964
9965 static void UnmapScreenGadgets()
9966 {
9967   int i;
9968
9969   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
9970     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
9971
9972   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
9973     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
9974 }
9975
9976 static void MapScreenTreeGadgets(TreeInfo *ti)
9977 {
9978   MapScreenGadgets(numTreeInfoInGroup(ti));
9979 }
9980
9981 static void UnmapScreenTreeGadgets(void)
9982 {
9983   UnmapScreenGadgets();
9984 }
9985
9986 static void AdjustScoreInfoButtons_SelectScore(int x, int y1, int y2)
9987 {
9988   struct GadgetInfo *gi_1 = screen_gadget[SCREEN_CTRL_ID_PREV_SCORE];
9989   struct GadgetInfo *gi_2 = screen_gadget[SCREEN_CTRL_ID_NEXT_SCORE];
9990   struct MenuPosInfo *pos_1 = menubutton_info[SCREEN_CTRL_ID_PREV_SCORE].pos;
9991   struct MenuPosInfo *pos_2 = menubutton_info[SCREEN_CTRL_ID_NEXT_SCORE].pos;
9992
9993   if (pos_1->x == -1 && pos_1->y == -1)
9994     ModifyGadget(gi_1, GDI_X, x, GDI_Y, y1, GDI_END);
9995
9996   if (pos_2->x == -1 && pos_2->y == -1)
9997     ModifyGadget(gi_2, GDI_X, x, GDI_Y, y2, GDI_END);
9998 }
9999
10000 static void AdjustScoreInfoButtons_PlayTape(int x, int y)
10001 {
10002   struct GadgetInfo *gi = screen_gadget[SCREEN_CTRL_ID_PLAY_TAPE];
10003   struct MenuPosInfo *pos = menubutton_info[SCREEN_CTRL_ID_PLAY_TAPE].pos;
10004
10005   if (pos->x == -1 && pos->y == -1)
10006     ModifyGadget(gi, GDI_X, x, GDI_Y, y, GDI_END);
10007 }
10008
10009 static void HandleScreenGadgets(struct GadgetInfo *gi)
10010 {
10011   int id = gi->custom_id;
10012   int button = gi->event.button;
10013   int step = (button == MB_LEFTBUTTON   ? 1 :
10014               button == MB_MIDDLEBUTTON ? 5 :
10015               button == MB_RIGHTBUTTON  ? 10 : 1);
10016
10017   switch (id)
10018   {
10019     case SCREEN_CTRL_ID_PREV_LEVEL:
10020       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10021       break;
10022
10023     case SCREEN_CTRL_ID_NEXT_LEVEL:
10024       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10025       break;
10026
10027     case SCREEN_CTRL_ID_PREV_LEVEL2:
10028       HandleHallOfFame_SelectLevel(step, -1);
10029       break;
10030
10031     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10032       HandleHallOfFame_SelectLevel(step, +1);
10033       break;
10034
10035     case SCREEN_CTRL_ID_PREV_SCORE:
10036       HandleScoreInfo_SelectScore(step, -1);
10037       break;
10038
10039     case SCREEN_CTRL_ID_NEXT_SCORE:
10040       HandleScoreInfo_SelectScore(step, +1);
10041       break;
10042
10043     case SCREEN_CTRL_ID_PLAY_TAPE:
10044       HandleScoreInfo_PlayTape();
10045       break;
10046
10047     case SCREEN_CTRL_ID_FIRST_LEVEL:
10048       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10049       break;
10050
10051     case SCREEN_CTRL_ID_LAST_LEVEL:
10052       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10053       break;
10054
10055     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10056       CloseDoor(DOOR_CLOSE_2);
10057       SetGameStatus(GAME_MODE_LEVELNR);
10058       DrawChooseLevelNr();
10059       break;
10060
10061     case SCREEN_CTRL_ID_PREV_PLAYER:
10062       HandleSetupScreen_Input_Player(step, -1);
10063       break;
10064
10065     case SCREEN_CTRL_ID_NEXT_PLAYER:
10066       HandleSetupScreen_Input_Player(step, +1);
10067       break;
10068
10069     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10070       InsertSolutionTape();
10071       break;
10072
10073     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10074       PlaySolutionTape();
10075       break;
10076
10077     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10078       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10079       DrawMainMenu();
10080       break;
10081
10082     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10083     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10084     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10085     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10086       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10087       break;
10088
10089     case SCREEN_CTRL_ID_SCROLL_UP:
10090       if (game_status == GAME_MODE_NAMES)
10091         HandleChoosePlayerName(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10092       else if (game_status == GAME_MODE_LEVELS)
10093         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10094       else if (game_status == GAME_MODE_LEVELNR)
10095         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10096       else if (game_status == GAME_MODE_SETUP)
10097         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10098       else if (game_status == GAME_MODE_INFO)
10099         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10100       else if (game_status == GAME_MODE_SCORES)
10101         HandleHallOfFame(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10102       break;
10103
10104     case SCREEN_CTRL_ID_SCROLL_DOWN:
10105       if (game_status == GAME_MODE_NAMES)
10106         HandleChoosePlayerName(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10107       else if (game_status == GAME_MODE_LEVELS)
10108         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10109       else if (game_status == GAME_MODE_LEVELNR)
10110         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10111       else if (game_status == GAME_MODE_SETUP)
10112         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10113       else if (game_status == GAME_MODE_INFO)
10114         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10115       else if (game_status == GAME_MODE_SCORES)
10116         HandleHallOfFame(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10117       break;
10118
10119     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
10120       if (game_status == GAME_MODE_NAMES)
10121         HandleChoosePlayerName(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10122       else if (game_status == GAME_MODE_LEVELS)
10123         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10124       else if (game_status == GAME_MODE_LEVELNR)
10125         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10126       else if (game_status == GAME_MODE_SETUP)
10127         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10128       else if (game_status == GAME_MODE_INFO)
10129         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10130       else if (game_status == GAME_MODE_SCORES)
10131         HandleHallOfFame(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10132       break;
10133
10134     case SCREEN_CTRL_ID_NETWORK_SERVER:
10135     {
10136       if (!strEqual(gi->textinput.value, ""))
10137       {
10138         setString(&setup.network_server_hostname, gi->textinput.value);
10139
10140         network.server_host = setup.network_server_hostname;
10141       }
10142       else
10143       {
10144         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
10145
10146         network.server_host = NULL;
10147       }
10148
10149       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
10150         network.server_host = NULL;
10151
10152       execSetupGame_setNetworkServerText();
10153
10154       DrawSetupScreen();
10155
10156       break;
10157     }
10158
10159     default:
10160       break;
10161   }
10162 }
10163
10164 void DumpScreenIdentifiers(void)
10165 {
10166   int i;
10167
10168   Print("Active screen elements on current screen:\n");
10169
10170   for (i = 0; main_controls[i].nr != -1; i++)
10171   {
10172     struct MainControlInfo *mci = &main_controls[i];
10173
10174     if (mci->button_graphic != -1)
10175     {
10176       char *token = getTokenFromImageID(mci->button_graphic);
10177
10178       Print("- '%s'\n", token);
10179     }
10180   }
10181
10182   Print("Done.\n");
10183 }
10184
10185 boolean DoScreenAction(int image_id)
10186 {
10187   int i;
10188
10189   if (game_status != GAME_MODE_MAIN)
10190     return FALSE;
10191
10192   for (i = 0; main_controls[i].nr != -1; i++)
10193   {
10194     struct MainControlInfo *mci = &main_controls[i];
10195     struct MenuPosInfo *pos = mci->pos_button;
10196
10197     if (mci->button_graphic == image_id)
10198     {
10199       int x = mSX + pos->x;
10200       int y = mSY + pos->y;
10201
10202       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
10203
10204       return TRUE;
10205     }
10206   }
10207
10208   return FALSE;
10209 }
10210
10211 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
10212 {
10213   // get tree info node of newly added level or artwork set
10214   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
10215   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
10216                                                       tree_subdir_new);
10217   if (tree_node_new == NULL)    // should not happen
10218     return;
10219
10220   // if request dialog is active, do nothing
10221   if (game.request_active)
10222     return;
10223
10224   if (game_status == GAME_MODE_MAIN &&
10225       tree_type == TREE_TYPE_LEVEL_DIR)
10226   {
10227     // when adding new level set in main menu, select it as current level set
10228
10229     // change current level set to newly added level set from zip file
10230     leveldir_current = tree_node_new;
10231
10232     // change current level number to first level of newly added level set
10233     level_nr = leveldir_current->first_level;
10234
10235     // redraw screen to reflect changed level set
10236     DrawMainMenu();
10237
10238     // save this level set and level number as last selected level set
10239     SaveLevelSetup_LastSeries();
10240     SaveLevelSetup_SeriesInfo();
10241   }
10242   else if (game_status == GAME_MODE_LEVELS &&
10243            tree_type == TREE_TYPE_LEVEL_DIR)
10244   {
10245     // when adding new level set in level set menu, set cursor and update screen
10246
10247     leveldir_current = tree_node_new;
10248
10249     DrawChooseTree(&leveldir_current);
10250   }
10251   else if (game_status == GAME_MODE_SETUP)
10252   {
10253     // when adding new artwork set in setup menu, set cursor and update screen
10254
10255     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
10256         tree_type == TREE_TYPE_GRAPHICS_DIR)
10257     {
10258       artwork.gfx_current = tree_node_new;
10259
10260       DrawChooseTree(&artwork.gfx_current);
10261     }
10262     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
10263              tree_type == TREE_TYPE_SOUNDS_DIR)
10264     {
10265       artwork.snd_current = tree_node_new;
10266
10267       DrawChooseTree(&artwork.snd_current);
10268     }
10269     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
10270              tree_type == TREE_TYPE_MUSIC_DIR)
10271     {
10272       artwork.mus_current = tree_node_new;
10273
10274       DrawChooseTree(&artwork.mus_current);
10275     }
10276   }
10277 }
10278
10279 static int UploadTapes(void)
10280 {
10281   SetGameStatus(GAME_MODE_LOADING);
10282
10283   FadeSetEnterScreen();
10284   FadeOut(REDRAW_ALL);
10285
10286   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
10287
10288   FadeIn(REDRAW_ALL);
10289
10290   DrawInitTextHead("Uploading tapes");
10291
10292   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
10293   global.autoplay_leveldir = "ALL";
10294   global.autoplay_all = TRUE;
10295
10296   int num_tapes_uploaded = AutoPlayTapes();
10297
10298   global.autoplay_mode = AUTOPLAY_MODE_NONE;
10299   global.autoplay_leveldir = NULL;
10300   global.autoplay_all = FALSE;
10301
10302   SetGameStatus(GAME_MODE_MAIN);
10303
10304   DrawMainMenu();
10305
10306   return num_tapes_uploaded;
10307 }
10308
10309 static boolean OfferUploadTapes(void)
10310 {
10311   if (!Request(setup.has_remaining_tapes ?
10312                "Upload missing tapes to the high score server now?" :
10313                "Upload all your tapes to the high score server now?", REQ_ASK))
10314     return FALSE;
10315
10316   int num_tapes_uploaded = UploadTapes();
10317   char message[100];
10318
10319   if (num_tapes_uploaded < 0)
10320   {
10321     num_tapes_uploaded = -num_tapes_uploaded - 1;
10322
10323     if (num_tapes_uploaded == 0)
10324       sprintf(message, "Upload failed! No tapes uploaded!");
10325     else if (num_tapes_uploaded == 1)
10326       sprintf(message, "Upload failed! Only 1 tape uploaded!");
10327     else
10328       sprintf(message, "Upload failed! Only %d tapes uploaded!",
10329               num_tapes_uploaded);
10330
10331     Request(message, REQ_CONFIRM);
10332
10333     // if uploading tapes failed, add tape upload entry to setup menu
10334     setup.provide_uploading_tapes = TRUE;
10335     setup.has_remaining_tapes = TRUE;
10336
10337     SaveSetup_ServerSetup();
10338
10339     return FALSE;
10340   }
10341
10342   if (num_tapes_uploaded == 0)
10343     sprintf(message, "No tapes uploaded!");
10344   else if (num_tapes_uploaded == 1)
10345     sprintf(message, "1 tape uploaded!");
10346   else
10347     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
10348
10349   Request(message, REQ_CONFIRM);
10350
10351   if (num_tapes_uploaded > 0)
10352     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
10353
10354   // after all tapes have been uploaded, remove entry from setup menu
10355   setup.provide_uploading_tapes = FALSE;
10356   setup.has_remaining_tapes = FALSE;
10357
10358   SaveSetup_ServerSetup();
10359
10360   return TRUE;
10361 }
10362
10363 static void CheckUploadTapes(void)
10364 {
10365   if (!setup.ask_for_uploading_tapes)
10366     return;
10367
10368   // after asking for uploading tapes, do not ask again
10369   setup.ask_for_uploading_tapes = FALSE;
10370   setup.ask_for_remaining_tapes = FALSE;
10371
10372   if (directoryExists(getTapeDir(NULL)))
10373   {
10374     boolean tapes_uploaded = OfferUploadTapes();
10375
10376     if (!tapes_uploaded)
10377     {
10378       Request(setup.has_remaining_tapes ?
10379               "You can upload missing tapes from the setup menu later!" :
10380               "You can upload your tapes from the setup menu later!",
10381               REQ_CONFIRM);
10382     }
10383   }
10384   else
10385   {
10386     // if tapes directory does not exist yet, never offer uploading all tapes
10387     setup.provide_uploading_tapes = FALSE;
10388   }
10389
10390   SaveSetup_ServerSetup();
10391 }
10392
10393 static void UpgradePlayerUUID(void)
10394 {
10395   ApiResetUUIDAsThread(getUUID());
10396 }
10397
10398 static void CheckUpgradePlayerUUID(void)
10399 {
10400   if (setup.player_version > 1)
10401     return;
10402
10403   UpgradePlayerUUID();
10404 }
10405
10406 void CheckApiServerTasks(void)
10407 {
10408   // check if the player's UUID has to be upgraded
10409   CheckUpgradePlayerUUID();
10410
10411   // check if there are any tapes to be uploaded
10412   CheckUploadTapes();
10413 }