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