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