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