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