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