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