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