added score selection buttons for score info page (not used yet)
[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 DrawInfoScreen(void);
272 static void DrawSetupScreen(void);
273 static void DrawTypeName(void);
274
275 static void DrawInfoScreen_NotAvailable(char *, char *);
276 static void DrawInfoScreen_HelpAnim(int, int, boolean);
277 static void DrawInfoScreen_HelpText(int, int, int, int);
278 static void HandleInfoScreen_Main(int, int, int, int, int);
279 static void HandleInfoScreen_TitleScreen(int);
280 static void HandleInfoScreen_Elements(int);
281 static void HandleInfoScreen_Music(int);
282 static void HandleInfoScreen_Credits(int);
283 static void HandleInfoScreen_Program(int);
284 static void HandleInfoScreen_Version(int);
285
286 static void ModifyGameSpeedIfNeeded(void);
287 static void DisableVsyncIfNeeded(void);
288
289 static void RedrawScreenMenuGadgets(int);
290 static void MapScreenMenuGadgets(int);
291 static void UnmapScreenMenuGadgets(int);
292 static void MapScreenGadgets(int);
293 static void UnmapScreenGadgets(void);
294 static void MapScreenTreeGadgets(TreeInfo *);
295 static void UnmapScreenTreeGadgets(void);
296
297 static void UpdateScreenMenuGadgets(int, boolean);
298
299 static boolean OfferUploadTapes(void);
300 static void execOfferUploadTapes(void);
301
302 static void DrawHallOfFame_setScoreEntries(void);
303 static void HandleHallOfFame_SelectLevel(int, int);
304 static void HandleHallOfFame_SelectLevelOrScore(int, int);
305 static char *getHallOfFameRankText(int, int);
306 static char *getHallOfFameScoreText(int, int);
307
308 static struct GadgetInfo *screen_gadget[NUM_SCREEN_GADGETS];
309
310 static int info_mode = INFO_MODE_MAIN;
311 static int setup_mode = SETUP_MODE_MAIN;
312
313 static TreeInfo *window_sizes = NULL;
314 static TreeInfo *window_size_current = NULL;
315
316 static TreeInfo *scaling_types = NULL;
317 static TreeInfo *scaling_type_current = NULL;
318
319 static TreeInfo *rendering_modes = NULL;
320 static TreeInfo *rendering_mode_current = NULL;
321
322 static TreeInfo *vsync_modes = NULL;
323 static TreeInfo *vsync_mode_current = NULL;
324
325 static TreeInfo *scroll_delays = NULL;
326 static TreeInfo *scroll_delay_current = NULL;
327
328 static TreeInfo *snapshot_modes = NULL;
329 static TreeInfo *snapshot_mode_current = NULL;
330
331 static TreeInfo *scores_types = NULL;
332 static TreeInfo *scores_type_current = NULL;
333
334 static TreeInfo *game_speeds_normal = NULL;
335 static TreeInfo *game_speeds_extended = NULL;
336 static TreeInfo *game_speeds = NULL;
337 static TreeInfo *game_speed_current = NULL;
338
339 static TreeInfo *volumes_simple = NULL;
340 static TreeInfo *volume_simple_current = NULL;
341
342 static TreeInfo *volumes_loops = NULL;
343 static TreeInfo *volume_loops_current = NULL;
344
345 static TreeInfo *volumes_music = NULL;
346 static TreeInfo *volume_music_current = NULL;
347
348 static TreeInfo *touch_controls = NULL;
349 static TreeInfo *touch_control_current = NULL;
350
351 static TreeInfo *move_distances = NULL;
352 static TreeInfo *move_distance_current = NULL;
353
354 static TreeInfo *drop_distances = NULL;
355 static TreeInfo *drop_distance_current = NULL;
356
357 static TreeInfo *transparencies = NULL;
358 static TreeInfo *transparency_current = NULL;
359
360 static TreeInfo *grid_sizes[2][2] = { { NULL, NULL }, { NULL, NULL } };
361 static TreeInfo *grid_size_current[2][2] = { { NULL, NULL }, { NULL, NULL } };
362
363 static TreeInfo *player_name = NULL;
364 static TreeInfo *player_name_current = NULL;
365
366 static TreeInfo *level_number = NULL;
367 static TreeInfo *level_number_current = NULL;
368
369 static TreeInfo *score_entries = NULL;
370 static TreeInfo *score_entry_current = NULL;
371
372 static struct ValueTextInfo window_sizes_list[] =
373 {
374   {     50,     "50 %"                          },
375   {     80,     "80 %"                          },
376   {     90,     "90 %"                          },
377   {     100,    "100 % (Default)"               },
378   {     110,    "110 %"                         },
379   {     120,    "120 %"                         },
380   {     130,    "130 %"                         },
381   {     140,    "140 %"                         },
382   {     150,    "150 %"                         },
383   {     200,    "200 %"                         },
384   {     250,    "250 %"                         },
385   {     300,    "300 %"                         },
386
387   {     -1,     NULL                            },
388 };
389
390 static struct StringValueTextInfo scaling_types_list[] =
391 {
392   {     SCALING_QUALITY_NEAREST, "Off"          },
393   {     SCALING_QUALITY_LINEAR,  "Linear"       },
394   {     SCALING_QUALITY_BEST,    "Anisotropic"  },
395
396   {     NULL,                    NULL           },
397 };
398
399 static struct StringValueTextInfo rendering_modes_list[] =
400 {
401   {     STR_SPECIAL_RENDERING_OFF,      "Off (May show artifacts, fast)" },
402   {     STR_SPECIAL_RENDERING_BITMAP,   "Bitmap/Texture mode (slower)"   },
403 #if DEBUG
404   // this mode may work under certain conditions, but does not work on Windows
405   {     STR_SPECIAL_RENDERING_TARGET,   "Target Texture mode (slower)"   },
406 #endif
407   {     STR_SPECIAL_RENDERING_DOUBLE,   "Double Texture mode (slower)"   },
408
409   {     NULL,                            NULL                            },
410 };
411
412 static struct StringValueTextInfo vsync_modes_list[] =
413 {
414   {     STR_VSYNC_MODE_OFF,             "Off"           },
415   {     STR_VSYNC_MODE_NORMAL,          "Normal"        },
416   {     STR_VSYNC_MODE_ADAPTIVE,        "Adaptive"      },
417
418   {     NULL,                            NULL           },
419 };
420
421 static struct StringValueTextInfo scores_types_list[] =
422 {
423   {     STR_SCORES_TYPE_LOCAL_ONLY,         "Local scores only"         },
424   {     STR_SCORES_TYPE_SERVER_ONLY,        "Server scores only"        },
425   {     STR_SCORES_TYPE_LOCAL_AND_SERVER,   "Local and server scores"   },
426
427   {     NULL,                           NULL            },
428 };
429
430 static struct ValueTextInfo game_speeds_list_normal[] =
431 {
432   {     30,     "Very Slow"                     },
433   {     25,     "Slow"                          },
434   {     20,     "Normal"                        },
435   {     15,     "Fast"                          },
436   {     10,     "Very Fast"                     },
437
438   {     -1,     NULL                            },
439 };
440
441 static struct ValueTextInfo game_speeds_list_extended[] =
442 {
443   {     1000,   "1 fps (Extremely Slow)"        },
444   {     500,    "2 fps"                         },
445   {     200,    "5 fps"                         },
446   {     100,    "10 fps"                        },
447   {     50,     "20 fps"                        },
448   {     29,     "35 fps (Original Supaplex)"    },
449   {     25,     "40 fps"                        },
450   {     20,     "50 fps (=== Normal Speed ===)" },
451   {     16,     "60 fps (60 Hz VSync Speed)"    },
452   {     14,     "70 fps (Maximum Supaplex)"     },
453   {     10,     "100 fps"                       },
454   {     5,      "200 fps"                       },
455   {     2,      "500 fps"                       },
456   {     1,      "1000 fps (Extremely Fast)"     },
457
458   {     -1,     NULL                            },
459 };
460
461 static struct ValueTextInfo *game_speeds_list;
462
463 static struct ValueTextInfo scroll_delays_list[] =
464 {
465   {     0,      "0 Tiles (No Scroll Delay)"     },
466   {     1,      "1 Tile"                        },
467   {     2,      "2 Tiles"                       },
468   {     3,      "3 Tiles (Default)"             },
469   {     4,      "4 Tiles"                       },
470   {     5,      "5 Tiles"                       },
471   {     6,      "6 Tiles"                       },
472   {     7,      "7 Tiles"                       },
473   {     8,      "8 Tiles (Maximum Scroll Delay)"},
474
475   {     -1,     NULL                            },
476 };
477
478 static struct StringValueTextInfo snapshot_modes_list[] =
479 {
480   {     STR_SNAPSHOT_MODE_OFF,                  "Off"           },
481   {     STR_SNAPSHOT_MODE_EVERY_STEP,           "Every Step"    },
482   {     STR_SNAPSHOT_MODE_EVERY_MOVE,           "Every Move"    },
483   {     STR_SNAPSHOT_MODE_EVERY_COLLECT,        "Every Collect" },
484
485   {     NULL,                                   NULL            },
486 };
487
488 static struct ValueTextInfo volumes_list[] =
489 {
490   {     0,      "0 %"                           },
491   {     1,      "1 %"                           },
492   {     2,      "2 %"                           },
493   {     5,      "5 %"                           },
494   {     10,     "10 %"                          },
495   {     20,     "20 %"                          },
496   {     30,     "30 %"                          },
497   {     40,     "40 %"                          },
498   {     50,     "50 %"                          },
499   {     60,     "60 %"                          },
500   {     70,     "70 %"                          },
501   {     80,     "80 %"                          },
502   {     90,     "90 %"                          },
503   {     100,    "100 %"                         },
504
505   {     -1,     NULL                            },
506 };
507
508 static struct StringValueTextInfo touch_controls_list[] =
509 {
510   {     TOUCH_CONTROL_OFF,              "Off"                   },
511   {     TOUCH_CONTROL_VIRTUAL_BUTTONS,  "Virtual Buttons"       },
512   {     TOUCH_CONTROL_WIPE_GESTURES,    "Wipe Gestures"         },
513   {     TOUCH_CONTROL_FOLLOW_FINGER,    "Follow Finger"         },
514
515   {     NULL,                           NULL                    },
516 };
517
518 static struct ValueTextInfo distances_list[] =
519 {
520   {     1,      "1 %"                           },
521   {     2,      "2 %"                           },
522   {     3,      "3 %"                           },
523   {     4,      "4 %"                           },
524   {     5,      "5 %"                           },
525   {     10,     "10 %"                          },
526   {     15,     "15 %"                          },
527   {     20,     "20 %"                          },
528   {     25,     "25 %"                          },
529
530   {     -1,     NULL                            },
531 };
532
533 static struct ValueTextInfo transparencies_list[] =
534 {
535   {     0,      "0 % (Opaque)"                  },
536   {     10,     "10 %"                          },
537   {     20,     "20 %"                          },
538   {     30,     "30 %"                          },
539   {     40,     "40 %"                          },
540   {     50,     "50 %"                          },
541   {     60,     "60 %"                          },
542   {     70,     "70 %"                          },
543   {     80,     "80 %"                          },
544   {     90,     "90 %"                          },
545   {     100,    "100 % (Invisible)"             },
546
547   {     -1,     NULL                            },
548 };
549
550 static struct ValueTextInfo grid_sizes_list[] =
551 {
552   {     3,      "3"                             },
553   {     4,      "4"                             },
554   {     5,      "5"                             },
555   {     6,      "6"                             },
556   {     7,      "7"                             },
557   {     8,      "8"                             },
558   {     9,      "9"                             },
559   {     10,     "10"                            },
560   {     11,     "11"                            },
561   {     12,     "12"                            },
562   {     13,     "13"                            },
563   {     14,     "14"                            },
564   {     15,     "15"                            },
565   {     16,     "16"                            },
566   {     17,     "17"                            },
567   {     18,     "18"                            },
568   {     19,     "19"                            },
569   {     20,     "20"                            },
570   {     21,     "21"                            },
571   {     22,     "22"                            },
572   {     23,     "23"                            },
573   {     24,     "24"                            },
574   {     25,     "25"                            },
575   {     26,     "26"                            },
576   {     27,     "27"                            },
577   {     28,     "28"                            },
578   {     29,     "29"                            },
579   {     30,     "30"                            },
580   {     31,     "31"                            },
581   {     32,     "32"                            },
582
583   {     -1,     NULL                            },
584 };
585
586 static int align_xoffset = 0;
587 static int align_yoffset = 0;
588
589 #define DRAW_MODE(s)            ((s) >= GAME_MODE_MAIN &&               \
590                                  (s) <= GAME_MODE_SETUP ? (s) :         \
591                                  (s) == GAME_MODE_PSEUDO_TYPENAME ?     \
592                                  GAME_MODE_MAIN :                       \
593                                  (s) == GAME_MODE_PSEUDO_TYPENAMES ?    \
594                                  GAME_MODE_NAMES : GAME_MODE_DEFAULT)
595
596 // (there are no draw offset definitions needed for INFO_MODE_TITLE)
597 #define DRAW_MODE_INFO(i)       ((i) >= INFO_MODE_TITLE &&              \
598                                  (i) <= INFO_MODE_LEVELSET ? (i) :      \
599                                  INFO_MODE_MAIN)
600
601 #define DRAW_MODE_SETUP(i)      ((i) >= SETUP_MODE_MAIN &&              \
602                                  (i) <= SETUP_MODE_SHORTCUTS_5 ? (i) :  \
603                                  (i) >= SETUP_MODE_CHOOSE_GRAPHICS &&   \
604                                  (i) <= SETUP_MODE_CHOOSE_MUSIC ?       \
605                                  SETUP_MODE_CHOOSE_ARTWORK :            \
606                                  SETUP_MODE_CHOOSE_OTHER)
607
608 #define DRAW_XOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?  \
609                                  menu.draw_xoffset[GAME_MODE_INFO] :    \
610                                  menu.draw_xoffset_info[DRAW_MODE_INFO(i)])
611 #define DRAW_YOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?  \
612                                  menu.draw_yoffset[GAME_MODE_INFO] :    \
613                                  menu.draw_yoffset_info[DRAW_MODE_INFO(i)])
614 #define EXTRA_SPACING_INFO(i)   (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ? \
615                                  menu.extra_spacing[GAME_MODE_INFO] :   \
616                                  menu.extra_spacing_info[DRAW_MODE_INFO(i)])
617
618 #define DRAW_XOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
619                                  menu.draw_xoffset[GAME_MODE_SETUP] :   \
620                                  menu.draw_xoffset_setup[DRAW_MODE_SETUP(i)])
621 #define DRAW_YOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
622                                  menu.draw_yoffset[GAME_MODE_SETUP] :   \
623                                  menu.draw_yoffset_setup[DRAW_MODE_SETUP(i)])
624 #define EXTRA_SPACING_SETUP(i)  (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
625                                  menu.extra_spacing[GAME_MODE_SETUP] :  \
626                                  menu.extra_spacing_setup[DRAW_MODE_SETUP(i)])
627
628 #define EXTRA_SPACING_SCORES(i) (EXTRA_SPACING_INFO(i))
629
630 #define EXTRA_SPACING_SCOREINFO(i) (menu.extra_spacing[GAME_MODE_SCOREINFO])
631
632 #define DRAW_XOFFSET(s)         ((s) == GAME_MODE_INFO ?                \
633                                  DRAW_XOFFSET_INFO(info_mode) :         \
634                                  (s) == GAME_MODE_SETUP ?               \
635                                  DRAW_XOFFSET_SETUP(setup_mode) :       \
636                                  menu.draw_xoffset[DRAW_MODE(s)])
637 #define DRAW_YOFFSET(s)         ((s) == GAME_MODE_INFO ?                \
638                                  DRAW_YOFFSET_INFO(info_mode) :         \
639                                  (s) == GAME_MODE_SETUP ?               \
640                                  DRAW_YOFFSET_SETUP(setup_mode) :       \
641                                  menu.draw_yoffset[DRAW_MODE(s)])
642 #define EXTRA_SPACING(s)        ((s) == GAME_MODE_INFO ?                \
643                                  EXTRA_SPACING_INFO(info_mode) :        \
644                                  (s) == GAME_MODE_SETUP ?               \
645                                  EXTRA_SPACING_SETUP(setup_mode) :      \
646                                  (s) == GAME_MODE_SCORES ?              \
647                                  EXTRA_SPACING_SCORES(info_mode) :      \
648                                  menu.extra_spacing[DRAW_MODE(s)])
649
650 #define mSX                     (SX + DRAW_XOFFSET(game_status))
651 #define mSY                     (SY + DRAW_YOFFSET(game_status))
652
653 #define amSX                    (mSX + align_xoffset)
654 #define amSY                    (mSY + align_yoffset)
655
656 #define NUM_MENU_ENTRIES_ON_SCREEN (menu.list_size[game_status] > 2 ?   \
657                                     menu.list_size[game_status] :       \
658                                     MAX_MENU_ENTRIES_ON_SCREEN)
659
660 #define IN_VIS_MENU(x, y)       IN_FIELD(x, y, SCR_FIELDX,              \
661                                          NUM_MENU_ENTRIES_ON_SCREEN)
662
663
664 // title display and control definitions
665
666 #define MAX_NUM_TITLE_SCREENS   (2 * MAX_NUM_TITLE_IMAGES +             \
667                                  2 * MAX_NUM_TITLE_MESSAGES)
668
669 #define NO_DIRECT_LEVEL_SELECT  (-1)
670
671
672 static int num_title_screens = 0;
673
674 struct TitleControlInfo
675 {
676   boolean is_image;
677   boolean initial;
678   boolean first;
679   int local_nr;
680   int sort_priority;
681 };
682
683 struct TitleControlInfo title_controls[MAX_NUM_TITLE_SCREENS];
684
685 // main menu display and control definitions
686
687 #define MAIN_CONTROL_NAME                       0
688 #define MAIN_CONTROL_LEVELS                     1
689 #define MAIN_CONTROL_SCORES                     2
690 #define MAIN_CONTROL_EDITOR                     3
691 #define MAIN_CONTROL_INFO                       4
692 #define MAIN_CONTROL_GAME                       5
693 #define MAIN_CONTROL_SETUP                      6
694 #define MAIN_CONTROL_QUIT                       7
695 #define MAIN_CONTROL_PREV_LEVEL                 8
696 #define MAIN_CONTROL_NEXT_LEVEL                 9
697 #define MAIN_CONTROL_FIRST_LEVEL                10
698 #define MAIN_CONTROL_LAST_LEVEL                 11
699 #define MAIN_CONTROL_LEVEL_NUMBER               12
700 #define MAIN_CONTROL_LEVEL_INFO_1               13
701 #define MAIN_CONTROL_LEVEL_INFO_2               14
702 #define MAIN_CONTROL_LEVEL_NAME                 15
703 #define MAIN_CONTROL_LEVEL_AUTHOR               16
704 #define MAIN_CONTROL_LEVEL_YEAR                 17
705 #define MAIN_CONTROL_LEVEL_IMPORTED_FROM        18
706 #define MAIN_CONTROL_LEVEL_IMPORTED_BY          19
707 #define MAIN_CONTROL_LEVEL_TESTED_BY            20
708 #define MAIN_CONTROL_TITLE_1                    21
709 #define MAIN_CONTROL_TITLE_2                    22
710 #define MAIN_CONTROL_TITLE_3                    23
711
712 static char str_main_text_name[10];
713 static char str_main_text_first_level[10];
714 static char str_main_text_last_level[10];
715 static char str_main_text_level_number[10];
716
717 static char network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN + 1];
718
719 static char *main_text_name                     = str_main_text_name;
720 static char *main_text_first_level              = str_main_text_first_level;
721 static char *main_text_last_level               = str_main_text_last_level;
722 static char *main_text_level_number             = str_main_text_level_number;
723 static char *main_text_levels                   = "Levelset";
724 static char *main_text_scores                   = "Hall Of Fame";
725 static char *main_text_editor                   = "Level Creator";
726 static char *main_text_info                     = "Info Screen";
727 static char *main_text_game                     = "Start Game";
728 static char *main_text_setup                    = "Setup";
729 static char *main_text_quit                     = "Quit";
730 static char *main_text_level_name               = level.name;
731 static char *main_text_level_author             = level.author;
732 static char *main_text_level_year               = NULL;
733 static char *main_text_level_imported_from      = NULL;
734 static char *main_text_level_imported_by        = NULL;
735 static char *main_text_level_tested_by          = NULL;
736 static char *main_text_title_1                  = NULL;
737 static char *main_text_title_2                  = NULL;
738 static char *main_text_title_3                  = NULL;
739
740 extern char debug_xsn_mode[];
741
742 struct MainControlInfo
743 {
744   int nr;
745
746   struct MenuPosInfo *pos_button;
747   int button_graphic;
748
749   struct TextPosInfo *pos_text;
750   char **text;
751
752   struct TextPosInfo *pos_input;
753   char **input;
754 };
755
756 static struct MainControlInfo main_controls[] =
757 {
758   {
759     MAIN_CONTROL_NAME,
760     &menu.main.button.name,             IMG_MENU_BUTTON_NAME,
761     &menu.main.text.name,               &main_text_name,
762     &menu.main.input.name,              &setup.player_name,
763   },
764   {
765     MAIN_CONTROL_LEVELS,
766     &menu.main.button.levels,           IMG_MENU_BUTTON_LEVELS,
767     &menu.main.text.levels,             &main_text_levels,
768     NULL,                               NULL,
769   },
770   {
771     MAIN_CONTROL_SCORES,
772     &menu.main.button.scores,           IMG_MENU_BUTTON_SCORES,
773     &menu.main.text.scores,             &main_text_scores,
774     NULL,                               NULL,
775   },
776   {
777     MAIN_CONTROL_EDITOR,
778     &menu.main.button.editor,           IMG_MENU_BUTTON_EDITOR,
779     &menu.main.text.editor,             &main_text_editor,
780     NULL,                               NULL,
781   },
782   {
783     MAIN_CONTROL_INFO,
784     &menu.main.button.info,             IMG_MENU_BUTTON_INFO,
785     &menu.main.text.info,               &main_text_info,
786     NULL,                               NULL,
787   },
788   {
789     MAIN_CONTROL_GAME,
790     &menu.main.button.game,             IMG_MENU_BUTTON_GAME,
791     &menu.main.text.game,               &main_text_game,
792     NULL,                               NULL,
793   },
794   {
795     MAIN_CONTROL_SETUP,
796     &menu.main.button.setup,            IMG_MENU_BUTTON_SETUP,
797     &menu.main.text.setup,              &main_text_setup,
798     NULL,                               NULL,
799   },
800   {
801     MAIN_CONTROL_QUIT,
802     &menu.main.button.quit,             IMG_MENU_BUTTON_QUIT,
803     &menu.main.text.quit,               &main_text_quit,
804     NULL,                               NULL,
805   },
806   {
807     MAIN_CONTROL_PREV_LEVEL,
808     NULL,                               -1,
809     NULL,                               NULL,
810     NULL,                               NULL,
811   },
812   {
813     MAIN_CONTROL_NEXT_LEVEL,
814     NULL,                               -1,
815     NULL,                               NULL,
816     NULL,                               NULL,
817   },
818   {
819     MAIN_CONTROL_FIRST_LEVEL,
820     NULL,                               -1,
821     &menu.main.text.first_level,        &main_text_first_level,
822     NULL,                               NULL,
823   },
824   {
825     MAIN_CONTROL_LAST_LEVEL,
826     NULL,                               -1,
827     &menu.main.text.last_level,         &main_text_last_level,
828     NULL,                               NULL,
829   },
830   {
831     MAIN_CONTROL_LEVEL_NUMBER,
832     NULL,                               -1,
833     &menu.main.text.level_number,       &main_text_level_number,
834     NULL,                               NULL,
835   },
836   {
837     MAIN_CONTROL_LEVEL_INFO_1,
838     NULL,                               -1,
839     &menu.main.text.level_info_1,       NULL,
840     NULL,                               NULL,
841   },
842   {
843     MAIN_CONTROL_LEVEL_INFO_2,
844     NULL,                               -1,
845     &menu.main.text.level_info_2,       NULL,
846     NULL,                               NULL,
847   },
848   {
849     MAIN_CONTROL_LEVEL_NAME,
850     NULL,                               -1,
851     &menu.main.text.level_name,         &main_text_level_name,
852     NULL,                               NULL,
853   },
854   {
855     MAIN_CONTROL_LEVEL_AUTHOR,
856     NULL,                               -1,
857     &menu.main.text.level_author,       &main_text_level_author,
858     NULL,                               NULL,
859   },
860   {
861     MAIN_CONTROL_LEVEL_YEAR,
862     NULL,                               -1,
863     &menu.main.text.level_year,         &main_text_level_year,
864     NULL,                               NULL,
865   },
866   {
867     MAIN_CONTROL_LEVEL_IMPORTED_FROM,
868     NULL,                               -1,
869     &menu.main.text.level_imported_from, &main_text_level_imported_from,
870     NULL,                               NULL,
871   },
872   {
873     MAIN_CONTROL_LEVEL_IMPORTED_BY,
874     NULL,                               -1,
875     &menu.main.text.level_imported_by,  &main_text_level_imported_by,
876     NULL,                               NULL,
877   },
878   {
879     MAIN_CONTROL_LEVEL_TESTED_BY,
880     NULL,                               -1,
881     &menu.main.text.level_tested_by,    &main_text_level_tested_by,
882     NULL,                               NULL,
883   },
884   {
885     MAIN_CONTROL_TITLE_1,
886     NULL,                               -1,
887     &menu.main.text.title_1,            &main_text_title_1,
888     NULL,                               NULL,
889   },
890   {
891     MAIN_CONTROL_TITLE_2,
892     NULL,                               -1,
893     &menu.main.text.title_2,            &main_text_title_2,
894     NULL,                               NULL,
895   },
896   {
897     MAIN_CONTROL_TITLE_3,
898     NULL,                               -1,
899     &menu.main.text.title_3,            &main_text_title_3,
900     NULL,                               NULL,
901   },
902
903   {
904     -1,
905     NULL,                               -1,
906     NULL,                               NULL,
907     NULL,                               NULL,
908   }
909 };
910
911
912 static int getTitleScreenGraphic(int nr, boolean initial)
913 {
914   return (initial ? IMG_TITLESCREEN_INITIAL_1 : IMG_TITLESCREEN_1) + nr;
915 }
916
917 static struct TitleMessageInfo *getTitleMessageInfo(int nr, boolean initial)
918 {
919   return (initial ? &titlemessage_initial[nr] : &titlemessage[nr]);
920 }
921
922 #if 0
923 static int getTitleScreenGameMode(boolean initial)
924 {
925   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
926 }
927 #endif
928
929 static int getTitleMessageGameMode(boolean initial)
930 {
931   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
932 }
933
934 static int getTitleAnimMode(struct TitleControlInfo *tci)
935 {
936   int base = (tci->initial ? GAME_MODE_TITLE_INITIAL_1 : GAME_MODE_TITLE_1);
937
938   return base + tci->local_nr;
939 }
940
941 #if 0
942 static int getTitleScreenBackground(boolean initial)
943 {
944   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
945 }
946 #endif
947
948 #if 0
949 static int getTitleMessageBackground(int nr, boolean initial)
950 {
951   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
952 }
953 #endif
954
955 static int getTitleBackground(int nr, boolean initial, boolean is_image)
956 {
957   int base = (is_image ?
958               (initial ? IMG_BACKGROUND_TITLESCREEN_INITIAL_1 :
959                          IMG_BACKGROUND_TITLESCREEN_1) :
960               (initial ? IMG_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
961                          IMG_BACKGROUND_TITLEMESSAGE_1));
962   int graphic_global = (initial ? IMG_BACKGROUND_TITLE_INITIAL :
963                                   IMG_BACKGROUND_TITLE);
964   int graphic_local = base + nr;
965
966   if (graphic_info[graphic_local].bitmap != NULL)
967     return graphic_local;
968
969   if (graphic_info[graphic_global].bitmap != NULL)
970     return graphic_global;
971
972   return IMG_UNDEFINED;
973 }
974
975 static int getTitleSound(struct TitleControlInfo *tci)
976 {
977   boolean is_image = tci->is_image;
978   int initial = tci->initial;
979   int nr = tci->local_nr;
980   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
981   int base = (is_image ?
982               (initial ? SND_BACKGROUND_TITLESCREEN_INITIAL_1 :
983                          SND_BACKGROUND_TITLESCREEN_1) :
984               (initial ? SND_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
985                          SND_BACKGROUND_TITLEMESSAGE_1));
986   int sound_global = menu.sound[mode];
987   int sound_local = base + nr;
988
989 #if 0
990   Debug("screens:getTitleSound", "%d, %d, %d: %d ['%s'], %d ['%s']",
991         nr, initial, is_image,
992         sound_global, getSoundListEntry(sound_global)->filename,
993         sound_local, getSoundListEntry(sound_local)->filename);
994 #endif
995
996   if (!strEqual(getSoundListEntry(sound_local)->filename, UNDEFINED_FILENAME))
997     return sound_local;
998
999   if (!strEqual(getSoundListEntry(sound_global)->filename, UNDEFINED_FILENAME))
1000     return sound_global;
1001
1002   return SND_UNDEFINED;
1003 }
1004
1005 static int getTitleMusic(struct TitleControlInfo *tci)
1006 {
1007   boolean is_image = tci->is_image;
1008   int initial = tci->initial;
1009   int nr = tci->local_nr;
1010   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
1011   int base = (is_image ?
1012               (initial ? MUS_BACKGROUND_TITLESCREEN_INITIAL_1 :
1013                          MUS_BACKGROUND_TITLESCREEN_1) :
1014               (initial ? MUS_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
1015                          MUS_BACKGROUND_TITLEMESSAGE_1));
1016   int music_global = menu.music[mode];
1017   int music_local = base + nr;
1018
1019 #if 0
1020   Debug("screens:getTitleMusic", "%d, %d, %d: %d ['%s'], %d ['%s']",
1021         nr, initial, is_image,
1022         music_global, getMusicListEntry(music_global)->filename,
1023         music_local, getMusicListEntry(music_local)->filename);
1024 #endif
1025
1026   if (!strEqual(getMusicListEntry(music_local)->filename, UNDEFINED_FILENAME))
1027     return music_local;
1028
1029   if (!strEqual(getMusicListEntry(music_global)->filename, UNDEFINED_FILENAME))
1030     return music_global;
1031
1032   return MUS_UNDEFINED;
1033 }
1034
1035 static struct TitleFadingInfo getTitleFading(struct TitleControlInfo *tci)
1036 {
1037   boolean is_image = tci->is_image;
1038   boolean initial = tci->initial;
1039   boolean first = tci->first;
1040   int nr = tci->local_nr;
1041   struct TitleMessageInfo tmi;
1042   struct TitleFadingInfo ti;
1043
1044   tmi = (is_image ? (initial ? (first ?
1045                                 titlescreen_initial_first[nr] :
1046                                 titlescreen_initial[nr])
1047                              : (first ?
1048                                 titlescreen_first[nr] :
1049                                 titlescreen[nr]))
1050                   : (initial ? (first ?
1051                                 titlemessage_initial_first[nr] :
1052                                 titlemessage_initial[nr])
1053                              : (first ?
1054                                 titlemessage_first[nr] :
1055                                 titlemessage[nr])));
1056
1057   ti.fade_mode  = tmi.fade_mode;
1058   ti.fade_delay = tmi.fade_delay;
1059   ti.post_delay = tmi.post_delay;
1060   ti.auto_delay = tmi.auto_delay;
1061   ti.auto_delay_unit = tmi.auto_delay_unit;
1062
1063   return ti;
1064 }
1065
1066 static int compareTitleControlInfo(const void *object1, const void *object2)
1067 {
1068   const struct TitleControlInfo *tci1 = (struct TitleControlInfo *)object1;
1069   const struct TitleControlInfo *tci2 = (struct TitleControlInfo *)object2;
1070   int compare_result;
1071
1072   if (tci1->initial != tci2->initial)
1073     compare_result = (tci1->initial ? -1 : +1);
1074   else if (tci1->sort_priority != tci2->sort_priority)
1075     compare_result = tci1->sort_priority - tci2->sort_priority;
1076   else if (tci1->is_image != tci2->is_image)
1077     compare_result = (tci1->is_image ? -1 : +1);
1078   else
1079     compare_result = tci1->local_nr - tci2->local_nr;
1080
1081   return compare_result;
1082 }
1083
1084 static void InitializeTitleControlsExt_AddTitleInfo(boolean is_image,
1085                                                     boolean initial,
1086                                                     int nr, int sort_priority)
1087 {
1088   title_controls[num_title_screens].is_image = is_image;
1089   title_controls[num_title_screens].initial = initial;
1090   title_controls[num_title_screens].local_nr = nr;
1091   title_controls[num_title_screens].sort_priority = sort_priority;
1092
1093   title_controls[num_title_screens].first = FALSE;      // will be set later
1094
1095   num_title_screens++;
1096 }
1097
1098 static void InitializeTitleControls_CheckTitleInfo(boolean initial)
1099 {
1100   int i;
1101
1102   for (i = 0; i < MAX_NUM_TITLE_IMAGES; i++)
1103   {
1104     int graphic = getTitleScreenGraphic(i, initial);
1105     Bitmap *bitmap = graphic_info[graphic].bitmap;
1106     int sort_priority = graphic_info[graphic].sort_priority;
1107
1108     if (bitmap != NULL)
1109       InitializeTitleControlsExt_AddTitleInfo(TRUE, initial, i, sort_priority);
1110   }
1111
1112   for (i = 0; i < MAX_NUM_TITLE_MESSAGES; i++)
1113   {
1114     struct TitleMessageInfo *tmi = getTitleMessageInfo(i, initial);
1115     char *filename = getLevelSetTitleMessageFilename(i, initial);
1116     int sort_priority = tmi->sort_priority;
1117
1118     if (filename != NULL)
1119       InitializeTitleControlsExt_AddTitleInfo(FALSE, initial, i, sort_priority);
1120   }
1121 }
1122
1123 static void InitializeTitleControls(boolean show_title_initial)
1124 {
1125   num_title_screens = 0;
1126
1127   // 1st step: initialize title screens for game start (only when starting)
1128   if (show_title_initial)
1129     InitializeTitleControls_CheckTitleInfo(TRUE);
1130
1131   // 2nd step: initialize title screens for current level set
1132   InitializeTitleControls_CheckTitleInfo(FALSE);
1133
1134   // sort title screens according to sort_priority and title number
1135   qsort(title_controls, num_title_screens, sizeof(struct TitleControlInfo),
1136         compareTitleControlInfo);
1137
1138   // mark first title screen
1139   title_controls[0].first = TRUE;
1140 }
1141
1142 static boolean visibleMenuPos(struct MenuPosInfo *pos)
1143 {
1144   return (pos != NULL && pos->x != -1 && pos->y != -1);
1145 }
1146
1147 static boolean visibleTextPos(struct TextPosInfo *pos)
1148 {
1149   return (pos != NULL && pos->x != -1 && pos->y != -1);
1150 }
1151
1152 static void InitializeMainControls(void)
1153 {
1154   boolean local_team_mode = (!network.enabled && setup.team_mode);
1155   int i;
1156
1157   // set main control text values to dynamically determined values
1158   sprintf(main_text_name,         "%s",   local_team_mode ? "Team:" : "Name:");
1159
1160   strcpy(main_text_first_level,  int2str(leveldir_current->first_level,
1161                                          menu.main.text.first_level.size));
1162   strcpy(main_text_last_level,   int2str(leveldir_current->last_level,
1163                                          menu.main.text.last_level.size));
1164   strcpy(main_text_level_number, int2str(level_nr,
1165                                          menu.main.text.level_number.size));
1166
1167   main_text_level_year          = leveldir_current->year;
1168   main_text_level_imported_from = leveldir_current->imported_from;
1169   main_text_level_imported_by   = leveldir_current->imported_by;
1170   main_text_level_tested_by     = leveldir_current->tested_by;
1171
1172   main_text_title_1 = getConfigProgramTitleString();
1173   main_text_title_2 = getConfigProgramCopyrightString();
1174   main_text_title_3 = getConfigProgramCompanyString();
1175
1176   // set main control screen positions to dynamically determined values
1177   for (i = 0; main_controls[i].nr != -1; i++)
1178   {
1179     struct MainControlInfo *mci = &main_controls[i];
1180     int nr                         = mci->nr;
1181     struct MenuPosInfo *pos_button = mci->pos_button;
1182     struct TextPosInfo *pos_text   = mci->pos_text;
1183     struct TextPosInfo *pos_input  = mci->pos_input;
1184     char *text                     = (mci->text  ? *mci->text  : NULL);
1185     char *input                    = (mci->input ? *mci->input : NULL);
1186     int button_graphic             = mci->button_graphic;
1187     int font_text                  = (pos_text  ? pos_text->font  : -1);
1188     int font_input                 = (pos_input ? pos_input->font : -1);
1189
1190     int font_text_width   = (font_text  != -1 ? getFontWidth(font_text)   : 0);
1191     int font_text_height  = (font_text  != -1 ? getFontHeight(font_text)  : 0);
1192     int font_input_width  = (font_input != -1 ? getFontWidth(font_input)  : 0);
1193     int font_input_height = (font_input != -1 ? getFontHeight(font_input) : 0);
1194     int text_chars  = (text  != NULL ? strlen(text)  : 0);
1195     int input_chars = (input != NULL ? strlen(input) : 0);
1196
1197     int button_width =
1198       (button_graphic != -1 ? graphic_info[button_graphic].width  : 0);
1199     int button_height =
1200       (button_graphic != -1 ? graphic_info[button_graphic].height : 0);
1201     int text_width   = font_text_width * text_chars;
1202     int text_height  = font_text_height;
1203     int input_width  = font_input_width * input_chars;
1204     int input_height = font_input_height;
1205
1206     if (nr == MAIN_CONTROL_NAME)
1207     {
1208       menu.main.input.name.width  = input_width;
1209       menu.main.input.name.height = input_height;
1210     }
1211
1212     if (pos_button != NULL)             // (x/y may be -1/-1 here)
1213     {
1214       pos_button->width  = button_width;
1215       pos_button->height = button_height;
1216     }
1217
1218     if (pos_text != NULL)               // (x/y may be -1/-1 here)
1219     {
1220       // calculate text size -- needed for text alignment
1221       boolean calculate_text_size = (text != NULL);
1222
1223       if (pos_text->width == -1 || calculate_text_size)
1224         pos_text->width = text_width;
1225       if (pos_text->height == -1 || calculate_text_size)
1226         pos_text->height = text_height;
1227
1228       if (visibleMenuPos(pos_button))
1229       {
1230         if (pos_text->x == -1)
1231           pos_text->x = pos_button->x + pos_button->width;
1232         if (pos_text->y == -1)
1233           pos_text->y =
1234             pos_button->y + (pos_button->height - pos_text->height) / 2;
1235       }
1236     }
1237
1238     if (pos_input != NULL)              // (x/y may be -1/-1 here)
1239     {
1240       if (visibleTextPos(pos_text))
1241       {
1242         if (pos_input->x == -1)
1243           pos_input->x = pos_text->x + pos_text->width;
1244         if (pos_input->y == -1)
1245           pos_input->y = pos_text->y;
1246       }
1247
1248       if (pos_input->width == -1)
1249         pos_input->width = input_width;
1250       if (pos_input->height == -1)
1251         pos_input->height = input_height;
1252     }
1253   }
1254 }
1255
1256 static void DrawPressedGraphicThruMask(int dst_x, int dst_y,
1257                                        int graphic, boolean pressed)
1258 {
1259   struct GraphicInfo *g = &graphic_info[graphic];
1260   Bitmap *src_bitmap;
1261   int src_x, src_y;
1262   int xoffset = (pressed ? g->pressed_xoffset : 0);
1263   int yoffset = (pressed ? g->pressed_yoffset : 0);
1264
1265   getFixedGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
1266
1267   BlitBitmapMasked(src_bitmap, drawto, src_x + xoffset, src_y + yoffset,
1268                    g->width, g->height, dst_x, dst_y);
1269 }
1270
1271 static void DrawCursorAndText_Main_Ext(int nr, boolean active_text,
1272                                        boolean active_input,
1273                                        boolean pressed_button)
1274 {
1275   int i;
1276
1277   for (i = 0; main_controls[i].nr != -1; i++)
1278   {
1279     struct MainControlInfo *mci = &main_controls[i];
1280
1281     if (mci->nr == nr || nr == -1)
1282     {
1283       struct MenuPosInfo *pos_button = mci->pos_button;
1284       struct TextPosInfo *pos_text   = mci->pos_text;
1285       struct TextPosInfo *pos_input  = mci->pos_input;
1286       char *text                     = (mci->text  ? *mci->text  : NULL);
1287       char *input                    = (mci->input ? *mci->input : NULL);
1288       int button_graphic             = mci->button_graphic;
1289       int font_text                  = (pos_text  ? pos_text->font  : -1);
1290       int font_input                 = (pos_input ? pos_input->font : -1);
1291
1292       if (active_text)
1293       {
1294         button_graphic = BUTTON_ACTIVE(button_graphic);
1295         font_text = FONT_ACTIVE(font_text);
1296       }
1297
1298       if (active_input)
1299       {
1300         font_input = FONT_ACTIVE(font_input);
1301       }
1302
1303       if (visibleMenuPos(pos_button))
1304       {
1305         struct MenuPosInfo *pos = pos_button;
1306         int x = mSX + pos->x;
1307         int y = mSY + pos->y;
1308
1309         DrawBackgroundForGraphic(x, y, pos->width, pos->height, button_graphic);
1310         DrawPressedGraphicThruMask(x, y, button_graphic, pressed_button);
1311       }
1312
1313       if (visibleTextPos(pos_text) && text != NULL)
1314       {
1315         struct TextPosInfo *pos = pos_text;
1316         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1317         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1318
1319 #if 1
1320         // (check why/if this is needed)
1321         DrawBackgroundForFont(x, y, pos->width, pos->height, font_text);
1322 #endif
1323         DrawText(x, y, text, font_text);
1324       }
1325
1326       if (visibleTextPos(pos_input) && input != NULL)
1327       {
1328         struct TextPosInfo *pos = pos_input;
1329         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1330         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1331
1332 #if 1
1333         // (check why/if this is needed)
1334         DrawBackgroundForFont(x, y, pos->width, pos->height, font_input);
1335 #endif
1336         DrawText(x, y, input, font_input);
1337       }
1338     }
1339   }
1340 }
1341
1342 static void DrawCursorAndText_Main(int nr, boolean active_text,
1343                                    boolean pressed_button)
1344 {
1345   DrawCursorAndText_Main_Ext(nr, active_text, FALSE, pressed_button);
1346 }
1347
1348 #if 0
1349 static void DrawCursorAndText_Main_Input(int nr, boolean active_text,
1350                                          boolean pressed_button)
1351 {
1352   DrawCursorAndText_Main_Ext(nr, active_text, TRUE, pressed_button);
1353 }
1354 #endif
1355
1356 static struct MainControlInfo *getMainControlInfo(int nr)
1357 {
1358   int i;
1359
1360   for (i = 0; main_controls[i].nr != -1; i++)
1361     if (main_controls[i].nr == nr)
1362       return &main_controls[i];
1363
1364   return NULL;
1365 }
1366
1367 static boolean insideMenuPosRect(struct MenuPosInfo *rect, int x, int y)
1368 {
1369   if (rect == NULL)
1370     return FALSE;
1371
1372   int rect_x = ALIGNED_TEXT_XPOS(rect);
1373   int rect_y = ALIGNED_TEXT_YPOS(rect);
1374
1375   return (x >= rect_x && x < rect_x + rect->width &&
1376           y >= rect_y && y < rect_y + rect->height);
1377 }
1378
1379 static boolean insideTextPosRect(struct TextPosInfo *rect, int x, int y)
1380 {
1381   if (rect == NULL)
1382     return FALSE;
1383
1384   int rect_x = ALIGNED_TEXT_XPOS(rect);
1385   int rect_y = ALIGNED_TEXT_YPOS(rect);
1386
1387 #if 0
1388   Debug("screens:insideTextPosRect",
1389         "(%d, %d), (%d, %d) [%d, %d] (%d, %d) => %d",
1390         x, y, rect_x, rect_y, rect->x, rect->y, rect->width, rect->height,
1391         (x >= rect_x && x < rect_x + rect->width &&
1392          y >= rect_y && y < rect_y + rect->height));
1393 #endif
1394
1395   return (x >= rect_x && x < rect_x + rect->width &&
1396           y >= rect_y && y < rect_y + rect->height);
1397 }
1398
1399 static boolean insidePreviewRect(struct PreviewInfo *preview, int x, int y)
1400 {
1401   int rect_width  = preview->xsize * preview->tile_size;
1402   int rect_height = preview->ysize * preview->tile_size;
1403   int rect_x = ALIGNED_XPOS(preview->x, rect_width,  preview->align);
1404   int rect_y = ALIGNED_YPOS(preview->y, rect_height, preview->valign);
1405
1406   return (x >= rect_x && x < rect_x + rect_width &&
1407           y >= rect_y && y < rect_y + rect_height);
1408 }
1409
1410 static void AdjustScrollbar(int id, int items_max, int items_visible,
1411                             int item_position)
1412 {
1413   struct GadgetInfo *gi = screen_gadget[id];
1414
1415   if (item_position > items_max - items_visible)
1416     item_position = items_max - items_visible;
1417
1418   ModifyGadget(gi, GDI_SCROLLBAR_ITEMS_MAX, items_max,
1419                GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
1420                GDI_SCROLLBAR_ITEM_POSITION, item_position, GDI_END);
1421 }
1422
1423 static void AdjustChooseTreeScrollbar(TreeInfo *ti, int id)
1424 {
1425   AdjustScrollbar(id, numTreeInfoInGroup(ti), NUM_MENU_ENTRIES_ON_SCREEN,
1426                   ti->cl_first);
1427 }
1428
1429 static void clearMenuListArea(void)
1430 {
1431   int scrollbar_xpos = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
1432
1433   // correct scrollbar position if placed outside menu (playfield) area
1434   if (scrollbar_xpos > SX + SC_SCROLLBAR_XPOS)
1435     scrollbar_xpos = SX + SC_SCROLLBAR_XPOS;
1436
1437   // clear menu list area, but not title or scrollbar
1438   DrawBackground(mSX, mSY + MENU_SCREEN_START_YPOS * 32,
1439                  scrollbar_xpos - mSX, NUM_MENU_ENTRIES_ON_SCREEN * 32);
1440 }
1441
1442 static void drawCursorExt(int xpos, int ypos, boolean active, int graphic)
1443 {
1444   static int cursor_array[MAX_LEV_FIELDY];
1445   int x = amSX + TILEX * xpos;
1446   int y = amSY + TILEY * (MENU_SCREEN_START_YPOS + ypos);
1447
1448   if (xpos == 0)
1449   {
1450     if (graphic != -1)
1451       cursor_array[ypos] = graphic;
1452     else
1453       graphic = cursor_array[ypos];
1454   }
1455
1456   if (active)
1457     graphic = BUTTON_ACTIVE(graphic);
1458
1459   DrawBackgroundForGraphic(x, y, TILEX, TILEY, graphic);
1460   DrawFixedGraphicThruMaskExt(drawto, x, y, graphic, 0);
1461 }
1462
1463 static void initCursor(int ypos, int graphic)
1464 {
1465   drawCursorExt(0, ypos, FALSE, graphic);
1466 }
1467
1468 static void drawCursor(int ypos, boolean active)
1469 {
1470   drawCursorExt(0, ypos, active, -1);
1471 }
1472
1473 static void drawCursorXY(int xpos, int ypos, int graphic)
1474 {
1475   drawCursorExt(xpos, ypos, FALSE, graphic);
1476 }
1477
1478 static void drawChooseTreeCursor(int ypos, boolean active)
1479 {
1480   drawCursorExt(0, ypos, active, -1);
1481 }
1482
1483 static int getChooseTreeEditFont(boolean active)
1484 {
1485   return (active ? FONT_MENU_2_ACTIVE : FONT_MENU_2);
1486 }
1487
1488 static int getChooseTreeEditXPos(int pos)
1489 {
1490   boolean has_scrollbar = screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->mapped;
1491   int xoffset = (has_scrollbar ? -1 : 0);
1492   int xpos = MENU_SCREEN_TEXT2_XPOS + xoffset;
1493   int sx = amSX + xpos * TILEX;
1494   int font_nr = getChooseTreeEditFont(FALSE);
1495   int width = getTextWidth(STR_CHOOSE_TREE_EDIT, font_nr);
1496
1497   return (pos == POS_RIGHT ? sx + width - 1 : sx);
1498 }
1499
1500 static int getChooseTreeEditYPos(int ypos_raw)
1501 {
1502   int ypos = MENU_SCREEN_START_YPOS + ypos_raw;
1503   int sy = amSY + ypos * TILEY;
1504
1505   return sy;
1506 }
1507
1508 static void drawChooseTreeEdit(int ypos_raw, boolean active)
1509 {
1510   int sx = getChooseTreeEditXPos(POS_LEFT);
1511   int sy = getChooseTreeEditYPos(ypos_raw);
1512   int font_nr = getChooseTreeEditFont(active);
1513
1514   DrawText(sx, sy, STR_CHOOSE_TREE_EDIT, font_nr);
1515 }
1516
1517 static void DrawHeadline(void)
1518 {
1519   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, main_text_title_1);
1520   DrawTextSCentered(MENU_TITLE2_YPOS, FONT_TITLE_2, main_text_title_2);
1521 }
1522
1523 static void DrawTitleScreenImage(int nr, boolean initial)
1524 {
1525   int graphic = getTitleScreenGraphic(nr, initial);
1526   Bitmap *bitmap = graphic_info[graphic].bitmap;
1527   int width  = graphic_info[graphic].width;
1528   int height = graphic_info[graphic].height;
1529   int src_x = graphic_info[graphic].src_x;
1530   int src_y = graphic_info[graphic].src_y;
1531   int dst_x, dst_y;
1532
1533   if (bitmap == NULL)
1534     return;
1535
1536   if (width > WIN_XSIZE)
1537   {
1538     // image width too large for window => center image horizontally
1539     src_x = (width - WIN_XSIZE) / 2;
1540     width = WIN_XSIZE;
1541   }
1542
1543   if (height > WIN_YSIZE)
1544   {
1545     // image height too large for window => center image vertically
1546     src_y = (height - WIN_YSIZE) / 2;
1547     height = WIN_YSIZE;
1548   }
1549
1550   // always display title screens centered
1551   dst_x = (WIN_XSIZE - width) / 2;
1552   dst_y = (WIN_YSIZE - height) / 2;
1553
1554   SetDrawBackgroundMask(REDRAW_ALL);
1555   SetWindowBackgroundImage(getTitleBackground(nr, initial, TRUE));
1556
1557   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1558
1559   if (DrawingOnBackground(dst_x, dst_y))
1560     BlitBitmapMasked(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1561   else
1562     BlitBitmap(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1563
1564   redraw_mask = REDRAW_ALL;
1565 }
1566
1567 static void DrawTitleScreenMessage(int nr, boolean initial)
1568 {
1569   char *filename = getLevelSetTitleMessageFilename(nr, initial);
1570   struct TitleMessageInfo *tmi = getTitleMessageInfo(nr, initial);
1571
1572   if (filename == NULL)
1573     return;
1574
1575   // force TITLE font on title message screen
1576   SetFontStatus(getTitleMessageGameMode(initial));
1577
1578   // if chars *and* width set to "-1", automatically determine width
1579   if (tmi->chars == -1 && tmi->width == -1)
1580     tmi->width = viewport.window[game_status].width;
1581
1582   // if lines *and* height set to "-1", automatically determine height
1583   if (tmi->lines == -1 && tmi->height == -1)
1584     tmi->height = viewport.window[game_status].height;
1585
1586   // if chars set to "-1", automatically determine by text and font width
1587   if (tmi->chars == -1)
1588     tmi->chars = tmi->width / getFontWidth(tmi->font);
1589   else
1590     tmi->width = tmi->chars * getFontWidth(tmi->font);
1591
1592   // if lines set to "-1", automatically determine by text and font height
1593   if (tmi->lines == -1)
1594     tmi->lines = tmi->height / getFontHeight(tmi->font);
1595   else
1596     tmi->height = tmi->lines * getFontHeight(tmi->font);
1597
1598   // if x set to "-1", automatically determine by width and alignment
1599   if (tmi->x == -1)
1600     tmi->x = -1 * ALIGNED_XPOS(0, tmi->width, tmi->align);
1601
1602   // if y set to "-1", automatically determine by height and alignment
1603   if (tmi->y == -1)
1604     tmi->y = -1 * ALIGNED_YPOS(0, tmi->height, tmi->valign);
1605
1606   SetDrawBackgroundMask(REDRAW_ALL);
1607   SetWindowBackgroundImage(getTitleBackground(nr, initial, FALSE));
1608
1609   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1610
1611   DrawTextFile(ALIGNED_TEXT_XPOS(tmi), ALIGNED_TEXT_YPOS(tmi),
1612                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
1613                tmi->autowrap, tmi->centered, tmi->parse_comments);
1614
1615   ResetFontStatus();
1616 }
1617
1618 static void DrawTitleScreen(void)
1619 {
1620   KeyboardAutoRepeatOff();
1621
1622   HandleTitleScreen(0, 0, 0, 0, MB_MENU_INITIALIZE);
1623 }
1624
1625 static boolean CheckTitleScreen(boolean levelset_has_changed)
1626 {
1627   static boolean show_title_initial = TRUE;
1628   boolean show_titlescreen = FALSE;
1629
1630   // needed to be able to skip title screen, if no image or message defined
1631   InitializeTitleControls(show_title_initial);
1632
1633   if (setup.show_titlescreen && (show_title_initial || levelset_has_changed))
1634     show_titlescreen = TRUE;
1635
1636   // show initial title images and messages only once at program start
1637   show_title_initial = FALSE;
1638
1639   return (show_titlescreen && num_title_screens > 0);
1640 }
1641
1642 void DrawMainMenu(void)
1643 {
1644   static LevelDirTree *leveldir_last_valid = NULL;
1645   boolean levelset_has_changed = FALSE;
1646   int fade_mask = REDRAW_FIELD;
1647
1648   LimitScreenUpdates(FALSE);
1649
1650   FadeSetLeaveScreen();
1651
1652   // do not fade out here -- function may continue and fade on editor screen
1653
1654   UnmapAllGadgets();
1655   FadeMenuSoundsAndMusic();
1656
1657   ExpireSoundLoops(FALSE);
1658
1659   KeyboardAutoRepeatOn();
1660
1661   audio.sound_deactivated = FALSE;
1662
1663   GetPlayerConfig();
1664
1665   // needed if last screen was the playing screen, invoked from level editor
1666   if (level_editor_test_game)
1667   {
1668     CloseDoor(DOOR_CLOSE_ALL);
1669
1670     SetGameStatus(GAME_MODE_EDITOR);
1671
1672     DrawLevelEd();
1673
1674     return;
1675   }
1676
1677   // leveldir_current may be invalid (level group, parent link, node copy)
1678   leveldir_current = getValidLevelSeries(leveldir_current, leveldir_last_valid);
1679
1680   if (leveldir_current != leveldir_last_valid)
1681   {
1682     UpdateLastPlayedLevels_TreeInfo();
1683
1684     levelset_has_changed = TRUE;
1685   }
1686
1687   // store valid level series information
1688   leveldir_last_valid = leveldir_current;
1689
1690   init_last = init;                     // switch to new busy animation
1691
1692   // needed if last screen (level choice) changed graphics, sounds or music
1693   ReloadCustomArtwork(0);
1694
1695   if (CheckTitleScreen(levelset_has_changed))
1696   {
1697     SetGameStatus(GAME_MODE_TITLE);
1698
1699     DrawTitleScreen();
1700
1701     return;
1702   }
1703
1704   if (redraw_mask & REDRAW_ALL)
1705     fade_mask = REDRAW_ALL;
1706
1707   if (CheckFadeAll())
1708     fade_mask = REDRAW_ALL;
1709
1710   FadeOut(fade_mask);
1711
1712   // needed if different viewport properties defined for menues
1713   ChangeViewportPropertiesIfNeeded();
1714
1715   SetDrawtoField(DRAW_TO_BACKBUFFER);
1716
1717   // level_nr may have been set to value over handicap with level editor
1718   if (setup.handicap && level_nr > leveldir_current->handicap_level)
1719     level_nr = leveldir_current->handicap_level;
1720
1721   LoadLevel(level_nr);
1722   LoadScore(level_nr);
1723
1724   SaveLevelSetup_SeriesInfo();
1725
1726   // set this after "ChangeViewportPropertiesIfNeeded()" (which may reset it)
1727   SetDrawDeactivationMask(REDRAW_NONE);
1728   SetDrawBackgroundMask(REDRAW_FIELD);
1729
1730   SetMainBackgroundImage(IMG_BACKGROUND_MAIN);
1731
1732 #if 0
1733   if (fade_mask == REDRAW_ALL)
1734     RedrawGlobalBorder();
1735 #endif
1736
1737   ClearField();
1738
1739   InitializeMainControls();
1740
1741   DrawCursorAndText_Main(-1, FALSE, FALSE);
1742   DrawPreviewLevelInitial();
1743   DrawNetworkPlayers();
1744
1745   HandleMainMenu(0, 0, 0, 0, MB_MENU_INITIALIZE);
1746
1747   TapeStop();
1748   if (TAPE_IS_EMPTY(tape))
1749     LoadTape(level_nr);
1750   DrawCompleteVideoDisplay();
1751
1752   PlayMenuSoundsAndMusic();
1753
1754   // create gadgets for main menu screen
1755   FreeScreenGadgets();
1756   CreateScreenGadgets();
1757
1758   // may be required if audio buttons shown on tape and changed in setup menu
1759   FreeGameButtons();
1760   CreateGameButtons();
1761
1762   // map gadgets for main menu screen
1763   MapTapeButtons();
1764   MapScreenMenuGadgets(SCREEN_MASK_MAIN);
1765   UpdateScreenMenuGadgets(SCREEN_MASK_MAIN_HAS_SOLUTION, hasSolutionTape());
1766
1767   // copy actual game door content to door double buffer for OpenDoor()
1768   BlitBitmap(drawto, bitmap_db_door_1, DX, DY, DXSIZE, DYSIZE, 0, 0);
1769   BlitBitmap(drawto, bitmap_db_door_2, VX, VY, VXSIZE, VYSIZE, 0, 0);
1770
1771   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
1772
1773   DrawMaskedBorder(fade_mask);
1774
1775   FadeIn(fade_mask);
1776   FadeSetEnterMenu();
1777
1778   // update screen area with special editor door
1779   redraw_mask |= REDRAW_ALL;
1780   BackToFront();
1781
1782   SetMouseCursor(CURSOR_DEFAULT);
1783
1784   OpenDoor(DOOR_CLOSE_1 | DOOR_OPEN_2);
1785
1786   SyncEmscriptenFilesystem();
1787
1788   // needed once after program start or after user change
1789   CheckApiServerTasks();
1790 }
1791
1792 static void gotoTopLevelDir(void)
1793 {
1794   // move upwards until inside (but not above) top level directory
1795   while (leveldir_current->node_parent &&
1796          !strEqual(leveldir_current->node_parent->subdir, STRING_TOP_DIRECTORY))
1797   {
1798     // write a "path" into level tree for easy navigation to last level
1799     if (leveldir_current->node_parent->node_group->cl_first == -1)
1800     {
1801       int num_leveldirs = numTreeInfoInGroup(leveldir_current);
1802       int leveldir_pos = getPosFromTreeInfo(leveldir_current);
1803       int num_page_entries = MIN(num_leveldirs, NUM_MENU_ENTRIES_ON_SCREEN);
1804       int cl_first, cl_cursor;
1805
1806       cl_first = MAX(0, leveldir_pos - num_page_entries + 1);
1807       cl_cursor = leveldir_pos - cl_first;
1808
1809       leveldir_current->node_parent->node_group->cl_first = cl_first;
1810       leveldir_current->node_parent->node_group->cl_cursor = cl_cursor;
1811     }
1812
1813     leveldir_current = leveldir_current->node_parent;
1814   }
1815 }
1816
1817 static unsigned int getAutoDelayCounter(struct TitleFadingInfo *fi)
1818 {
1819   boolean use_frame_counter = (fi->auto_delay_unit == AUTO_DELAY_UNIT_FRAMES);
1820
1821   return (use_frame_counter ? video.frame_counter : Counter());
1822 }
1823
1824 static boolean TitleAutoDelayReached(unsigned int *counter_var,
1825                                      struct TitleFadingInfo *fi)
1826 {
1827   return DelayReachedExt(counter_var, fi->auto_delay, getAutoDelayCounter(fi));
1828 }
1829
1830 static void ResetTitleAutoDelay(unsigned int *counter_var,
1831                                 struct TitleFadingInfo *fi)
1832 {
1833   *counter_var = getAutoDelayCounter(fi);
1834 }
1835
1836 void HandleTitleScreen(int mx, int my, int dx, int dy, int button)
1837 {
1838   static unsigned int title_delay = 0;
1839   static int title_screen_nr = 0;
1840   static int last_sound = -1, last_music = -1;
1841   boolean return_to_main_menu = FALSE;
1842   struct TitleControlInfo *tci;
1843   int sound, music;
1844
1845   if (button == MB_MENU_INITIALIZE)
1846   {
1847     title_delay = 0;
1848     title_screen_nr = 0;
1849     tci = &title_controls[title_screen_nr];
1850
1851     SetAnimStatus(getTitleAnimMode(tci));
1852
1853     last_sound = SND_UNDEFINED;
1854     last_music = MUS_UNDEFINED;
1855
1856     if (num_title_screens != 0)
1857     {
1858       FadeSetEnterScreen();
1859
1860       // use individual title fading instead of global "enter screen" fading
1861       fading = getTitleFading(tci);
1862     }
1863
1864     if (game_status_last_screen == GAME_MODE_INFO)
1865     {
1866       if (num_title_screens == 0)
1867       {
1868         // switch game mode from title screen mode back to info screen mode
1869         SetGameStatus(GAME_MODE_INFO);
1870
1871         // store that last screen was info screen, not main menu screen
1872         game_status_last_screen = GAME_MODE_INFO;
1873
1874         DrawInfoScreen_NotAvailable("Title screen information:",
1875                                     "No title screen for this level set.");
1876         return;
1877       }
1878     }
1879
1880     FadeMenuSoundsAndMusic();
1881
1882     FadeOut(REDRAW_ALL);
1883
1884     // title screens may have different window size
1885     ChangeViewportPropertiesIfNeeded();
1886
1887     // only required to update logic for redrawing global border
1888     ClearField();
1889
1890     if (tci->is_image)
1891       DrawTitleScreenImage(tci->local_nr, tci->initial);
1892     else
1893       DrawTitleScreenMessage(tci->local_nr, tci->initial);
1894
1895     sound = getTitleSound(tci);
1896     music = getTitleMusic(tci);
1897
1898     if (sound != last_sound)
1899       PlayMenuSoundExt(sound);
1900     if (music != last_music)
1901       PlayMenuMusicExt(music);
1902
1903     last_sound = sound;
1904     last_music = music;
1905
1906     SetMouseCursor(CURSOR_NONE);
1907
1908     FadeIn(REDRAW_ALL);
1909
1910     ResetTitleAutoDelay(&title_delay, &fading);
1911
1912     return;
1913   }
1914
1915   if (fading.auto_delay > 0 && TitleAutoDelayReached(&title_delay, &fading))
1916     button = MB_MENU_CHOICE;
1917
1918   if (button == MB_MENU_LEAVE)
1919   {
1920     return_to_main_menu = TRUE;
1921   }
1922   else if (button == MB_MENU_CHOICE)
1923   {
1924     if (game_status_last_screen == GAME_MODE_INFO && num_title_screens == 0)
1925     {
1926       SetGameStatus(GAME_MODE_INFO);
1927
1928       info_mode = INFO_MODE_MAIN;
1929
1930       DrawInfoScreen();
1931
1932       return;
1933     }
1934
1935     title_screen_nr++;
1936
1937     if (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 button)
3095 {
3096   HandleTitleScreen(0, 0, 0, 0, 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(MB_MENU_INITIALIZE);
3109
3110   FadeIn(REDRAW_FIELD);
3111 }
3112
3113 void HandleInfoScreen_Elements(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)
3153   {
3154     if (button != MB_MENU_INITIALIZE)
3155     {
3156       PlaySound(SND_MENU_ITEM_SELECTING);
3157
3158       page++;
3159     }
3160
3161     if (page >= num_pages)
3162     {
3163       FadeMenuSoundsAndMusic();
3164
3165       info_mode = INFO_MODE_MAIN;
3166       DrawInfoScreen();
3167
3168       return;
3169     }
3170
3171     if (page > 0)
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(MB_MENU_INITIALIZE);
3204
3205   FadeIn(REDRAW_FIELD);
3206 }
3207
3208 void HandleInfoScreen_Music(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)
3255   {
3256     if (button != MB_MENU_INITIALIZE)
3257     {
3258       PlaySound(SND_MENU_ITEM_SELECTING);
3259
3260       if (list != NULL)
3261         list = 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(MB_MENU_INITIALIZE);
3612
3613   FadeIn(REDRAW_FIELD);
3614 }
3615
3616 void HandleInfoScreen_Credits(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
3628   if (button == MB_MENU_LEAVE)
3629   {
3630     PlaySound(SND_MENU_ITEM_SELECTING);
3631
3632     info_mode = INFO_MODE_MAIN;
3633     DrawInfoScreen();
3634
3635     return;
3636   }
3637   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
3638   {
3639     if (button != MB_MENU_INITIALIZE)
3640     {
3641       PlaySound(SND_MENU_ITEM_SELECTING);
3642
3643       screen_nr++;
3644     }
3645
3646     if (screen_nr >= num_screens)
3647     {
3648       FadeMenuSoundsAndMusic();
3649
3650       info_mode = INFO_MODE_MAIN;
3651       DrawInfoScreen();
3652
3653       return;
3654     }
3655
3656     if (screen_nr > 0)
3657       FadeSetNextScreen();
3658
3659     if (button != MB_MENU_INITIALIZE)
3660       FadeOut(REDRAW_FIELD);
3661
3662     DrawInfoScreen_CreditsScreen(screen_nr);
3663
3664     if (button != MB_MENU_INITIALIZE)
3665       FadeIn(REDRAW_FIELD);
3666   }
3667   else
3668   {
3669     PlayMenuSoundIfLoop();
3670   }
3671 }
3672
3673 static void DrawInfoScreen_Program(void)
3674 {
3675   int font_title = MENU_INFO_FONT_TITLE;
3676   int font_head  = MENU_INFO_FONT_HEAD;
3677   int font_text  = MENU_INFO_FONT_TEXT;
3678   int font_foot  = MENU_INFO_FONT_FOOT;
3679   int spacing_title = menu.headline1_spacing_info[info_mode];
3680   int spacing_head  = menu.headline2_spacing_info[info_mode];
3681   int spacing_para  = menu.paragraph_spacing_info[info_mode];
3682   int spacing_line  = menu.line_spacing_info[info_mode];
3683   int ystep_title = getMenuTextStep(spacing_title, font_title);
3684   int ystep_head  = getMenuTextStep(spacing_head,  font_head);
3685   int ystep_para  = getMenuTextStep(spacing_para,  font_text);
3686   int ystep_line  = getMenuTextStep(spacing_line,  font_text);
3687   int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART1;
3688   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3689
3690   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_PROGRAM);
3691
3692   FadeOut(REDRAW_FIELD);
3693
3694   ClearField();
3695   DrawHeadline();
3696
3697   DrawTextSCentered(ystart, font_title, "Program Information:");
3698   ystart += ystep_title;
3699
3700   DrawTextSCentered(ystart, font_head,
3701                     "This game is Freeware!");
3702   ystart += ystep_head;
3703   DrawTextSCentered(ystart, font_head,
3704                     "If you like it, send e-mail to:");
3705   ystart += ystep_head;
3706   DrawTextSCentered(ystart, font_text,
3707                     setup.internal.program_email);
3708   ystart += ystep_para;
3709
3710   DrawTextSCentered(ystart, font_head,
3711                     "More information and levels:");
3712   ystart += ystep_head;
3713   DrawTextSCentered(ystart, font_text,
3714                     setup.internal.program_website);
3715   ystart += ystep_para;
3716
3717   DrawTextSCentered(ystart, font_head,
3718                     "If you have created new levels,");
3719   ystart += ystep_line;
3720   DrawTextSCentered(ystart, font_head,
3721                     "send them to me to include them!");
3722   ystart += ystep_head;
3723   DrawTextSCentered(ystart, font_head,
3724                     ":-)");
3725
3726   DrawTextSCentered(ybottom, font_foot,
3727                     "Press any key or button for info menu");
3728
3729   FadeIn(REDRAW_FIELD);
3730 }
3731
3732 void HandleInfoScreen_Program(int button)
3733 {
3734   if (button == MB_MENU_LEAVE)
3735   {
3736     PlaySound(SND_MENU_ITEM_SELECTING);
3737
3738     info_mode = INFO_MODE_MAIN;
3739     DrawInfoScreen();
3740
3741     return;
3742   }
3743   else if (button == MB_MENU_CHOICE)
3744   {
3745     PlaySound(SND_MENU_ITEM_SELECTING);
3746
3747     FadeMenuSoundsAndMusic();
3748
3749     info_mode = INFO_MODE_MAIN;
3750     DrawInfoScreen();
3751   }
3752   else
3753   {
3754     PlayMenuSoundIfLoop();
3755   }
3756 }
3757
3758 static void DrawInfoScreen_Version(void)
3759 {
3760   int font_title = MENU_INFO_FONT_TITLE;
3761   int font_head  = MENU_INFO_FONT_HEAD;
3762   int font_text  = MENU_INFO_FONT_TEXT;
3763   int font_foot  = MENU_INFO_FONT_FOOT;
3764   int spacing_title = menu.headline1_spacing_info[info_mode];
3765   int spacing_head  = menu.headline2_spacing_info[info_mode];
3766   int spacing_para  = menu.paragraph_spacing_info[info_mode];
3767   int spacing_line  = menu.line_spacing_info[info_mode];
3768   int xstep = getFontWidth(font_text);
3769   int ystep_title = getMenuTextStep(spacing_title, font_title);
3770   int ystep_head  = getMenuTextStep(spacing_head,  font_head);
3771   int ystep_para  = getMenuTextStep(spacing_para,  font_text);
3772   int ystep_line  = getMenuTextStep(spacing_line,  font_text);
3773   int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART1;
3774   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3775   int xstart1 = mSX - SX + 2 * xstep;
3776   int xstart2 = mSX - SX + 18 * xstep;
3777   int xstart3 = mSX - SX + 28 * xstep;
3778   SDL_version sdl_version_compiled;
3779   const SDL_version *sdl_version_linked;
3780   int driver_name_len = 10;
3781   SDL_version sdl_version_linked_ext;
3782   const char *driver_name = NULL;
3783
3784   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_VERSION);
3785
3786   FadeOut(REDRAW_FIELD);
3787
3788   ClearField();
3789   DrawHeadline();
3790
3791   DrawTextSCentered(ystart, font_title, "Version Information:");
3792   ystart += ystep_title;
3793
3794   DrawTextF(xstart1, ystart, font_head, "Name");
3795   DrawTextF(xstart2, ystart, font_text, getProgramTitleString());
3796   ystart += ystep_line;
3797
3798   if (!strEqual(getProgramVersionString(), getProgramRealVersionString()))
3799   {
3800     DrawTextF(xstart1, ystart, font_head, "Version (fake)");
3801     DrawTextF(xstart2, ystart, font_text, getProgramVersionString());
3802     ystart += ystep_line;
3803
3804     DrawTextF(xstart1, ystart, font_head, "Version (real)");
3805     DrawTextF(xstart2, ystart, font_text, getProgramRealVersionString());
3806     ystart += ystep_line;
3807   }
3808   else
3809   {
3810     DrawTextF(xstart1, ystart, font_head, "Version");
3811     DrawTextF(xstart2, ystart, font_text, getProgramVersionString());
3812     ystart += ystep_line;
3813   }
3814
3815   DrawTextF(xstart1, ystart, font_head, "Platform");
3816   DrawTextF(xstart2, ystart, font_text, "%s (%s)",
3817             PLATFORM_STRING,
3818             PLATFORM_XX_BIT_STRING);
3819   ystart += ystep_line;
3820
3821   DrawTextF(xstart1, ystart, font_head, "Target");
3822   DrawTextF(xstart2, ystart, font_text, TARGET_STRING);
3823   ystart += ystep_line;
3824
3825   DrawTextF(xstart1, ystart, font_head, "Source date");
3826   DrawTextF(xstart2, ystart, font_text, getSourceDateString());
3827   ystart += ystep_line;
3828
3829   DrawTextF(xstart1, ystart, font_head, "Commit hash");
3830   DrawTextF(xstart2, ystart, font_text, getSourceHashString());
3831   ystart += ystep_para;
3832
3833   DrawTextF(xstart1, ystart, font_head, "Library");
3834   DrawTextF(xstart2, ystart, font_head, "compiled");
3835   DrawTextF(xstart3, ystart, font_head, "linked");
3836   ystart += ystep_head;
3837
3838   SDL_VERSION(&sdl_version_compiled);
3839   SDL_GetVersion(&sdl_version_linked_ext);
3840   sdl_version_linked = &sdl_version_linked_ext;
3841
3842   DrawTextF(xstart1, ystart, font_text, "SDL");
3843   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3844             sdl_version_compiled.major,
3845             sdl_version_compiled.minor,
3846             sdl_version_compiled.patch);
3847   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3848             sdl_version_linked->major,
3849             sdl_version_linked->minor,
3850             sdl_version_linked->patch);
3851   ystart += ystep_line;
3852
3853   SDL_IMAGE_VERSION(&sdl_version_compiled);
3854   sdl_version_linked = IMG_Linked_Version();
3855
3856   DrawTextF(xstart1, ystart, font_text, "SDL_image");
3857   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3858             sdl_version_compiled.major,
3859             sdl_version_compiled.minor,
3860             sdl_version_compiled.patch);
3861   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3862             sdl_version_linked->major,
3863             sdl_version_linked->minor,
3864             sdl_version_linked->patch);
3865   ystart += ystep_line;
3866
3867   SDL_MIXER_VERSION(&sdl_version_compiled);
3868   sdl_version_linked = Mix_Linked_Version();
3869
3870   DrawTextF(xstart1, ystart, font_text, "SDL_mixer");
3871   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3872             sdl_version_compiled.major,
3873             sdl_version_compiled.minor,
3874             sdl_version_compiled.patch);
3875   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3876             sdl_version_linked->major,
3877             sdl_version_linked->minor,
3878             sdl_version_linked->patch);
3879   ystart += ystep_line;
3880
3881   SDL_NET_VERSION(&sdl_version_compiled);
3882   sdl_version_linked = SDLNet_Linked_Version();
3883
3884   DrawTextF(xstart1, ystart, font_text, "SDL_net");
3885   DrawTextF(xstart2, ystart, font_text, "%d.%d.%d",
3886             sdl_version_compiled.major,
3887             sdl_version_compiled.minor,
3888             sdl_version_compiled.patch);
3889   DrawTextF(xstart3, ystart, font_text, "%d.%d.%d",
3890             sdl_version_linked->major,
3891             sdl_version_linked->minor,
3892             sdl_version_linked->patch);
3893   ystart += ystep_para;
3894
3895   DrawTextF(xstart1, ystart, font_head, "Driver");
3896   DrawTextF(xstart2, ystart, font_head, "Requested");
3897   DrawTextF(xstart3, ystart, font_head, "Used");
3898   ystart += ystep_head;
3899
3900   driver_name =
3901     getStringCopyNStatic(SDLGetRendererName(), driver_name_len);
3902
3903   DrawTextF(xstart1, ystart, font_text, "Render Driver");
3904   DrawTextF(xstart2, ystart, font_text, "%s", setup.system.sdl_renderdriver);
3905   DrawTextF(xstart3, ystart, font_text, "%s", driver_name);
3906   ystart += ystep_line;
3907
3908   driver_name =
3909     getStringCopyNStatic(SDL_GetCurrentVideoDriver(), driver_name_len);
3910
3911   DrawTextF(xstart1, ystart, font_text, "Video Driver");
3912   DrawTextF(xstart2, ystart, font_text, "%s", setup.system.sdl_videodriver);
3913   DrawTextF(xstart3, ystart, font_text, "%s", driver_name);
3914   ystart += ystep_line;
3915
3916   driver_name =
3917     getStringCopyNStatic(SDL_GetCurrentAudioDriver(), driver_name_len);
3918
3919   DrawTextF(xstart1, ystart, font_text, "Audio Driver");
3920   DrawTextF(xstart2, ystart, font_text, "%s", setup.system.sdl_audiodriver);
3921   DrawTextF(xstart3, ystart, font_text, "%s", driver_name);
3922
3923   DrawTextSCentered(ybottom, font_foot,
3924                     "Press any key or button for info menu");
3925
3926   FadeIn(REDRAW_FIELD);
3927 }
3928
3929 void HandleInfoScreen_Version(int button)
3930 {
3931   if (button == MB_MENU_LEAVE)
3932   {
3933     PlaySound(SND_MENU_ITEM_SELECTING);
3934
3935     info_mode = INFO_MODE_MAIN;
3936     DrawInfoScreen();
3937
3938     return;
3939   }
3940   else if (button == MB_MENU_CHOICE)
3941   {
3942     PlaySound(SND_MENU_ITEM_SELECTING);
3943
3944     FadeMenuSoundsAndMusic();
3945
3946     info_mode = INFO_MODE_MAIN;
3947     DrawInfoScreen();
3948   }
3949   else
3950   {
3951     PlayMenuSoundIfLoop();
3952   }
3953 }
3954
3955 static void DrawInfoScreen_LevelSet(void)
3956 {
3957   struct TitleMessageInfo *tmi = &readme;
3958   char *filename = getLevelSetInfoFilename();
3959   char *title = "Level Set Information:";
3960   int ystart  = mSY - SY + MENU_SCREEN_INFO_YSTART1;
3961   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
3962
3963   if (filename == NULL)
3964   {
3965     DrawInfoScreen_NotAvailable(title, "No information for this level set.");
3966
3967     return;
3968   }
3969
3970   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_LEVELSET);
3971
3972   FadeOut(REDRAW_FIELD);
3973
3974   ClearField();
3975   DrawHeadline();
3976
3977   DrawTextSCentered(ystart, FONT_TEXT_1, title);
3978
3979   // if x position set to "-1", automatically determine by playfield width
3980   if (tmi->x == -1)
3981     tmi->x = SXSIZE / 2;
3982
3983   // if y position set to "-1", use static default value
3984   if (tmi->y == -1)
3985     tmi->y = 150;
3986
3987   // if width set to "-1", automatically determine by playfield width
3988   if (tmi->width == -1)
3989     tmi->width = SXSIZE - 2 * TILEX;
3990
3991   // if height set to "-1", automatically determine by playfield height
3992   if (tmi->height == -1)
3993     tmi->height = MENU_SCREEN_INFO_YBOTTOM - tmi->y - 10;
3994
3995   // if chars set to "-1", automatically determine by text and font width
3996   if (tmi->chars == -1)
3997     tmi->chars = tmi->width / getFontWidth(tmi->font);
3998   else
3999     tmi->width = tmi->chars * getFontWidth(tmi->font);
4000
4001   // if lines set to "-1", automatically determine by text and font height
4002   if (tmi->lines == -1)
4003     tmi->lines = tmi->height / getFontHeight(tmi->font);
4004   else
4005     tmi->height = tmi->lines * getFontHeight(tmi->font);
4006
4007   DrawTextFile(mSX + ALIGNED_TEXT_XPOS(tmi), mSY + ALIGNED_TEXT_YPOS(tmi),
4008                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
4009                tmi->autowrap, tmi->centered, tmi->parse_comments);
4010
4011   DrawTextSCentered(ybottom, FONT_TEXT_4,
4012                     "Press any key or button for info menu");
4013
4014   FadeIn(REDRAW_FIELD);
4015 }
4016
4017 static void HandleInfoScreen_LevelSet(int button)
4018 {
4019   if (button == MB_MENU_LEAVE)
4020   {
4021     PlaySound(SND_MENU_ITEM_SELECTING);
4022
4023     info_mode = INFO_MODE_MAIN;
4024     DrawInfoScreen();
4025
4026     return;
4027   }
4028   else if (button == MB_MENU_CHOICE)
4029   {
4030     PlaySound(SND_MENU_ITEM_SELECTING);
4031
4032     FadeMenuSoundsAndMusic();
4033
4034     info_mode = INFO_MODE_MAIN;
4035     DrawInfoScreen();
4036   }
4037   else
4038   {
4039     PlayMenuSoundIfLoop();
4040   }
4041 }
4042
4043 static void DrawInfoScreen(void)
4044 {
4045   if (info_mode == INFO_MODE_TITLE)
4046     DrawInfoScreen_TitleScreen();
4047   else if (info_mode == INFO_MODE_ELEMENTS)
4048     DrawInfoScreen_Elements();
4049   else if (info_mode == INFO_MODE_MUSIC)
4050     DrawInfoScreen_Music();
4051   else if (info_mode == INFO_MODE_CREDITS)
4052     DrawInfoScreen_Credits();
4053   else if (info_mode == INFO_MODE_PROGRAM)
4054     DrawInfoScreen_Program();
4055   else if (info_mode == INFO_MODE_VERSION)
4056     DrawInfoScreen_Version();
4057   else if (info_mode == INFO_MODE_LEVELSET)
4058     DrawInfoScreen_LevelSet();
4059   else
4060     DrawInfoScreen_Main();
4061
4062   if (info_mode != INFO_MODE_MAIN &&
4063       info_mode != INFO_MODE_TITLE &&
4064       info_mode != INFO_MODE_MUSIC)
4065     PlayMenuSoundsAndMusic();
4066 }
4067
4068 void HandleInfoScreen(int mx, int my, int dx, int dy, int button)
4069 {
4070   if (info_mode == INFO_MODE_TITLE)
4071     HandleInfoScreen_TitleScreen(button);
4072   else if (info_mode == INFO_MODE_ELEMENTS)
4073     HandleInfoScreen_Elements(button);
4074   else if (info_mode == INFO_MODE_MUSIC)
4075     HandleInfoScreen_Music(button);
4076   else if (info_mode == INFO_MODE_CREDITS)
4077     HandleInfoScreen_Credits(button);
4078   else if (info_mode == INFO_MODE_PROGRAM)
4079     HandleInfoScreen_Program(button);
4080   else if (info_mode == INFO_MODE_VERSION)
4081     HandleInfoScreen_Version(button);
4082   else if (info_mode == INFO_MODE_LEVELSET)
4083     HandleInfoScreen_LevelSet(button);
4084   else
4085     HandleInfoScreen_Main(mx, my, dx, dy, button);
4086 }
4087
4088
4089 // ============================================================================
4090 // rename player API functions
4091 // ============================================================================
4092
4093 struct ApiRenamePlayerThreadData
4094 {
4095   char *player_name;
4096   char *player_uuid;
4097 };
4098
4099 static void *CreateThreadData_ApiRenamePlayer(void)
4100 {
4101   struct ApiRenamePlayerThreadData *data =
4102     checked_malloc(sizeof(struct ApiRenamePlayerThreadData));
4103
4104   data->player_name = getStringCopy(setup.player_name);
4105   data->player_uuid = getStringCopy(setup.player_uuid);
4106
4107   return data;
4108 }
4109
4110 static void FreeThreadData_ApiRenamePlayer(void *data_raw)
4111 {
4112   struct ApiRenamePlayerThreadData *data = data_raw;
4113
4114   checked_free(data->player_name);
4115   checked_free(data->player_uuid);
4116   checked_free(data);
4117 }
4118
4119 static boolean SetRequest_ApiRenamePlayer(struct HttpRequest *request,
4120                                           void *data_raw)
4121 {
4122   struct ApiRenamePlayerThreadData *data = data_raw;
4123   char *player_name_raw = data->player_name;
4124   char *player_uuid_raw = data->player_uuid;
4125
4126   request->hostname = setup.api_server_hostname;
4127   request->port     = API_SERVER_PORT;
4128   request->method   = API_SERVER_METHOD;
4129   request->uri      = API_SERVER_URI_RENAME;
4130
4131   char *player_name = getEscapedJSON(player_name_raw);
4132   char *player_uuid = getEscapedJSON(player_uuid_raw);
4133
4134   snprintf(request->body, MAX_HTTP_BODY_SIZE,
4135            "{\n"
4136            "%s"
4137            "  \"game_version\":         \"%s\",\n"
4138            "  \"game_platform\":        \"%s\",\n"
4139            "  \"name\":                 \"%s\",\n"
4140            "  \"uuid\":                 \"%s\"\n"
4141            "}\n",
4142            getPasswordJSON(setup.api_server_password),
4143            getProgramRealVersionString(),
4144            getProgramPlatformString(),
4145            player_name,
4146            player_uuid);
4147
4148   checked_free(player_name);
4149   checked_free(player_uuid);
4150
4151   ConvertHttpRequestBodyToServerEncoding(request);
4152
4153   return TRUE;
4154 }
4155
4156 static void HandleResponse_ApiRenamePlayer(struct HttpResponse *response,
4157                                            void *data_raw)
4158 {
4159   // nothing to do here
4160 }
4161
4162 #if defined(PLATFORM_EMSCRIPTEN)
4163 static void Emscripten_ApiRenamePlayer_Loaded(unsigned handle, void *data_raw,
4164                                               void *buffer, unsigned int size)
4165 {
4166   struct HttpResponse *response = GetHttpResponseFromBuffer(buffer, size);
4167
4168   if (response != NULL)
4169   {
4170     HandleResponse_ApiRenamePlayer(response, data_raw);
4171
4172     checked_free(response);
4173   }
4174   else
4175   {
4176     Error("server response too large to handle (%d bytes)", size);
4177   }
4178
4179   FreeThreadData_ApiRenamePlayer(data_raw);
4180 }
4181
4182 static void Emscripten_ApiRenamePlayer_Failed(unsigned handle, void *data_raw,
4183                                               int code, const char *status)
4184 {
4185   Error("server failed to handle request: %d %s", code, status);
4186
4187   FreeThreadData_ApiRenamePlayer(data_raw);
4188 }
4189
4190 static void Emscripten_ApiRenamePlayer_Progress(unsigned handle, void *data_raw,
4191                                                 int bytes, int size)
4192 {
4193   // nothing to do here
4194 }
4195
4196 static void Emscripten_ApiRenamePlayer_HttpRequest(struct HttpRequest *request,
4197                                                    void *data_raw)
4198 {
4199   if (!SetRequest_ApiRenamePlayer(request, data_raw))
4200   {
4201     FreeThreadData_ApiRenamePlayer(data_raw);
4202
4203     return;
4204   }
4205
4206   emscripten_async_wget2_data(request->uri,
4207                               request->method,
4208                               request->body,
4209                               data_raw,
4210                               TRUE,
4211                               Emscripten_ApiRenamePlayer_Loaded,
4212                               Emscripten_ApiRenamePlayer_Failed,
4213                               Emscripten_ApiRenamePlayer_Progress);
4214 }
4215
4216 #else
4217
4218 static void ApiRenamePlayer_HttpRequestExt(struct HttpRequest *request,
4219                                            struct HttpResponse *response,
4220                                            void *data_raw)
4221 {
4222   if (!SetRequest_ApiRenamePlayer(request, data_raw))
4223     return;
4224
4225   if (!DoHttpRequest(request, response))
4226   {
4227     Error("HTTP request failed: %s", GetHttpError());
4228
4229     return;
4230   }
4231
4232   if (!HTTP_SUCCESS(response->status_code))
4233   {
4234     Error("server failed to handle request: %d %s",
4235           response->status_code,
4236           response->status_text);
4237
4238     return;
4239   }
4240
4241   HandleResponse_ApiRenamePlayer(response, data_raw);
4242 }
4243
4244 static void ApiRenamePlayer_HttpRequest(struct HttpRequest *request,
4245                                     struct HttpResponse *response,
4246                                     void *data_raw)
4247 {
4248   ApiRenamePlayer_HttpRequestExt(request, response, data_raw);
4249
4250   FreeThreadData_ApiRenamePlayer(data_raw);
4251 }
4252 #endif
4253
4254 static int ApiRenamePlayerThread(void *data_raw)
4255 {
4256   struct HttpRequest *request = checked_calloc(sizeof(struct HttpRequest));
4257   struct HttpResponse *response = checked_calloc(sizeof(struct HttpResponse));
4258
4259   program.api_thread_count++;
4260
4261 #if defined(PLATFORM_EMSCRIPTEN)
4262   Emscripten_ApiRenamePlayer_HttpRequest(request, data_raw);
4263 #else
4264   ApiRenamePlayer_HttpRequest(request, response, data_raw);
4265 #endif
4266
4267   program.api_thread_count--;
4268
4269   checked_free(request);
4270   checked_free(response);
4271
4272   return 0;
4273 }
4274
4275 static void ApiRenamePlayerAsThread(void)
4276 {
4277   struct ApiRenamePlayerThreadData *data = CreateThreadData_ApiRenamePlayer();
4278
4279   ExecuteAsThread(ApiRenamePlayerThread,
4280                   "ApiRenamePlayer", data,
4281                   "rename player on server");
4282 }
4283
4284
4285 // ============================================================================
4286 // reset player UUID API functions
4287 // ============================================================================
4288
4289 struct ApiResetUUIDThreadData
4290 {
4291   char *player_name;
4292   char *player_uuid_old;
4293   char *player_uuid_new;
4294 };
4295
4296 static void *CreateThreadData_ApiResetUUID(char *uuid_new)
4297 {
4298   struct ApiResetUUIDThreadData *data =
4299     checked_malloc(sizeof(struct ApiResetUUIDThreadData));
4300
4301   data->player_name     = getStringCopy(setup.player_name);
4302   data->player_uuid_old = getStringCopy(setup.player_uuid);
4303   data->player_uuid_new = getStringCopy(uuid_new);
4304
4305   return data;
4306 }
4307
4308 static void FreeThreadData_ApiResetUUID(void *data_raw)
4309 {
4310   struct ApiResetUUIDThreadData *data = data_raw;
4311
4312   checked_free(data->player_name);
4313   checked_free(data->player_uuid_old);
4314   checked_free(data->player_uuid_new);
4315   checked_free(data);
4316 }
4317
4318 static boolean SetRequest_ApiResetUUID(struct HttpRequest *request,
4319                                        void *data_raw)
4320 {
4321   struct ApiResetUUIDThreadData *data = data_raw;
4322   char *player_name_raw = data->player_name;
4323   char *player_uuid_old_raw = data->player_uuid_old;
4324   char *player_uuid_new_raw = data->player_uuid_new;
4325
4326   request->hostname = setup.api_server_hostname;
4327   request->port     = API_SERVER_PORT;
4328   request->method   = API_SERVER_METHOD;
4329   request->uri      = API_SERVER_URI_RESETUUID;
4330
4331   char *player_name = getEscapedJSON(player_name_raw);
4332   char *player_uuid_old = getEscapedJSON(player_uuid_old_raw);
4333   char *player_uuid_new = getEscapedJSON(player_uuid_new_raw);
4334
4335   snprintf(request->body, MAX_HTTP_BODY_SIZE,
4336            "{\n"
4337            "%s"
4338            "  \"game_version\":         \"%s\",\n"
4339            "  \"game_platform\":        \"%s\",\n"
4340            "  \"name\":                 \"%s\",\n"
4341            "  \"uuid_old\":             \"%s\",\n"
4342            "  \"uuid_new\":             \"%s\"\n"
4343            "}\n",
4344            getPasswordJSON(setup.api_server_password),
4345            getProgramRealVersionString(),
4346            getProgramPlatformString(),
4347            player_name,
4348            player_uuid_old,
4349            player_uuid_new);
4350
4351   checked_free(player_name);
4352   checked_free(player_uuid_old);
4353   checked_free(player_uuid_new);
4354
4355   ConvertHttpRequestBodyToServerEncoding(request);
4356
4357   return TRUE;
4358 }
4359
4360 static void HandleResponse_ApiResetUUID(struct HttpResponse *response,
4361                                         void *data_raw)
4362 {
4363   struct ApiResetUUIDThreadData *data = data_raw;
4364
4365   // upgrade player UUID in server setup file
4366   setup.player_uuid = getStringCopy(data->player_uuid_new);
4367   setup.player_version = 2;
4368
4369   SaveSetup_ServerSetup();
4370 }
4371
4372 #if defined(PLATFORM_EMSCRIPTEN)
4373 static void Emscripten_ApiResetUUID_Loaded(unsigned handle, void *data_raw,
4374                                            void *buffer, unsigned int size)
4375 {
4376   struct HttpResponse *response = GetHttpResponseFromBuffer(buffer, size);
4377
4378   if (response != NULL)
4379   {
4380     HandleResponse_ApiResetUUID(response, data_raw);
4381
4382     checked_free(response);
4383   }
4384   else
4385   {
4386     Error("server response too large to handle (%d bytes)", size);
4387   }
4388
4389   FreeThreadData_ApiResetUUID(data_raw);
4390 }
4391
4392 static void Emscripten_ApiResetUUID_Failed(unsigned handle, void *data_raw,
4393                                            int code, const char *status)
4394 {
4395   Error("server failed to handle request: %d %s", code, status);
4396
4397   FreeThreadData_ApiResetUUID(data_raw);
4398 }
4399
4400 static void Emscripten_ApiResetUUID_Progress(unsigned handle, void *data_raw,
4401                                              int bytes, int size)
4402 {
4403   // nothing to do here
4404 }
4405
4406 static void Emscripten_ApiResetUUID_HttpRequest(struct HttpRequest *request,
4407                                                 void *data_raw)
4408 {
4409   if (!SetRequest_ApiResetUUID(request, data_raw))
4410   {
4411     FreeThreadData_ApiResetUUID(data_raw);
4412
4413     return;
4414   }
4415
4416   emscripten_async_wget2_data(request->uri,
4417                               request->method,
4418                               request->body,
4419                               data_raw,
4420                               TRUE,
4421                               Emscripten_ApiResetUUID_Loaded,
4422                               Emscripten_ApiResetUUID_Failed,
4423                               Emscripten_ApiResetUUID_Progress);
4424 }
4425
4426 #else
4427
4428 static void ApiResetUUID_HttpRequestExt(struct HttpRequest *request,
4429                                         struct HttpResponse *response,
4430                                         void *data_raw)
4431 {
4432   if (!SetRequest_ApiResetUUID(request, data_raw))
4433     return;
4434
4435   if (!DoHttpRequest(request, response))
4436   {
4437     Error("HTTP request failed: %s", GetHttpError());
4438
4439     return;
4440   }
4441
4442   if (!HTTP_SUCCESS(response->status_code))
4443   {
4444     Error("server failed to handle request: %d %s",
4445           response->status_code,
4446           response->status_text);
4447
4448     return;
4449   }
4450
4451   HandleResponse_ApiResetUUID(response, data_raw);
4452 }
4453
4454 static void ApiResetUUID_HttpRequest(struct HttpRequest *request,
4455                                      struct HttpResponse *response,
4456                                      void *data_raw)
4457 {
4458   ApiResetUUID_HttpRequestExt(request, response, data_raw);
4459
4460   FreeThreadData_ApiResetUUID(data_raw);
4461 }
4462 #endif
4463
4464 static int ApiResetUUIDThread(void *data_raw)
4465 {
4466   struct HttpRequest *request = checked_calloc(sizeof(struct HttpRequest));
4467   struct HttpResponse *response = checked_calloc(sizeof(struct HttpResponse));
4468
4469   program.api_thread_count++;
4470
4471 #if defined(PLATFORM_EMSCRIPTEN)
4472   Emscripten_ApiResetUUID_HttpRequest(request, data_raw);
4473 #else
4474   ApiResetUUID_HttpRequest(request, response, data_raw);
4475 #endif
4476
4477   program.api_thread_count--;
4478
4479   checked_free(request);
4480   checked_free(response);
4481
4482   return 0;
4483 }
4484
4485 static void ApiResetUUIDAsThread(char *uuid_new)
4486 {
4487   struct ApiResetUUIDThreadData *data = CreateThreadData_ApiResetUUID(uuid_new);
4488
4489   ExecuteAsThread(ApiResetUUIDThread,
4490                   "ApiResetUUID", data,
4491                   "reset UUID on server");
4492 }
4493
4494
4495 // ============================================================================
4496 // type name functions
4497 // ============================================================================
4498
4499 static TreeInfo *type_name_node = NULL;
4500 static char type_name_last[MAX_PLAYER_NAME_LEN + 1] = { 0 };
4501 static int type_name_nr = 0;
4502
4503 static int getPlayerNameColor(char *name)
4504 {
4505   return (strEqual(name, EMPTY_PLAYER_NAME) ? FC_BLUE : FC_RED);
4506 }
4507
4508 static void drawTypeNameText(char *name, struct TextPosInfo *pos,
4509                               boolean active)
4510 {
4511   char text[MAX_PLAYER_NAME_LEN + 2] = { 0 };
4512   boolean multiple_users = (game_status == GAME_MODE_PSEUDO_TYPENAMES);
4513   int sx = (multiple_users ? amSX + pos->x : mSX + ALIGNED_TEXT_XPOS(pos));
4514   int sy = (multiple_users ? amSY + pos->y : mSY + ALIGNED_TEXT_YPOS(pos));
4515   int font_nr = (active ? FONT_ACTIVE(pos->font) : pos->font);
4516   int font_width = getFontWidth(font_nr);
4517
4518   DrawBackgroundForFont(sx, sy, pos->width, pos->height, font_nr);
4519
4520   sprintf(text, "%s%c", name, (active ? '_' : '\0'));
4521
4522   pos->width = strlen(text) * font_width;
4523   sx = (multiple_users ? amSX + pos->x : mSX + ALIGNED_TEXT_XPOS(pos));
4524
4525   DrawText(sx, sy, text, font_nr);
4526 }
4527
4528 static void getTypeNameValues(char *name, struct TextPosInfo *pos, int *xpos)
4529 {
4530   struct MainControlInfo *mci = getMainControlInfo(MAIN_CONTROL_NAME);
4531
4532   *pos = *mci->pos_input;
4533
4534   if (game_status == GAME_MODE_PSEUDO_TYPENAMES)
4535   {
4536     TreeInfo *ti = player_name_current;
4537     int first_entry = ti->cl_first;
4538     int entry_pos = first_entry + ti->cl_cursor;
4539     TreeInfo *node_first = getTreeInfoFirstGroupEntry(ti);
4540     int xpos = MENU_SCREEN_START_XPOS;
4541     int ypos = MENU_SCREEN_START_YPOS + ti->cl_cursor;
4542
4543     type_name_node = getTreeInfoFromPos(node_first, entry_pos);
4544     type_name_nr = entry_pos;
4545
4546     strcpy(name, type_name_node->name);
4547
4548     pos->x = xpos * 32;
4549     pos->y = ypos * 32;
4550     pos->width = MAX_PLAYER_NAME_LEN * 32;
4551   }
4552   else
4553   {
4554     type_name_nr = user.nr;
4555
4556     strcpy(name, setup.player_name);
4557   }
4558
4559   strcpy(type_name_last, name);
4560
4561   if (strEqual(name, EMPTY_PLAYER_NAME))
4562     strcpy(name, "");
4563
4564   *xpos = strlen(name);
4565 }
4566
4567 static void setTypeNameValues_Name(char *name, struct TextPosInfo *pos)
4568 {
4569   // change name of edited user in global list of user names
4570   setString(&global.user_names[type_name_nr], name);
4571
4572   if (game_status == GAME_MODE_PSEUDO_TYPENAMES)
4573   {
4574     TreeInfo *node = type_name_node;
4575
4576     // change name of edited user in local menu tree structure
4577     setString(&node->name, name);
4578     setString(&node->name_sorting, name);
4579
4580     node->color = getPlayerNameColor(name);
4581     pos->font = MENU_CHOOSE_TREE_FONT(node->color);
4582   }
4583 }
4584
4585 static void setTypeNameValues(char *name, struct TextPosInfo *pos,
4586                               boolean changed)
4587 {
4588   boolean reset_setup = strEqual(name, "");
4589   boolean remove_user = strEqual(name, EMPTY_PLAYER_NAME);
4590   boolean create_user = strEqual(type_name_last, EMPTY_PLAYER_NAME);
4591
4592   if (!changed)
4593     strcpy(name, type_name_last);
4594
4595   if (strEqual(name, ""))
4596     strcpy(name, EMPTY_PLAYER_NAME);
4597
4598   setTypeNameValues_Name(name, pos);
4599
4600   // if player name not changed, no further action required
4601   if (strEqual(name, type_name_last))
4602     return;
4603
4604   // redraw player name before (possibly) opening request dialogs
4605   drawTypeNameText(name, pos, FALSE);
4606
4607   int last_user_nr = user.nr;
4608
4609   if (game_status == GAME_MODE_PSEUDO_TYPENAMES)
4610   {
4611     // save setup of currently active user (may differ from edited user)
4612     SaveSetup();
4613
4614     // temporarily change active user to edited user
4615     user.nr = type_name_nr;
4616
4617     if (create_user &&
4618         Request("Use current setup values for the new player?", REQ_ASK))
4619     {
4620       // use current setup values for new user, but create new player UUID
4621       setup.player_uuid = getStringCopy(getUUID());
4622     }
4623     else
4624     {
4625       // load setup for existing user (or start with defaults for new user)
4626       LoadSetup();
4627     }
4628   }
4629
4630   char *setup_filename = getSetupFilename();
4631   boolean setup_exists = fileExists(setup_filename);
4632
4633   // change name of edited user in setup structure
4634   strcpy(setup.player_name, name);
4635
4636   // save setup of edited user
4637   SaveSetup();
4638
4639   // change name of edited user on score server
4640   ApiRenamePlayerAsThread();
4641
4642   if (game_status == GAME_MODE_PSEUDO_TYPENAMES || reset_setup)
4643   {
4644     if (reset_setup)
4645     {
4646       if (Request("Reset setup values for this player?", REQ_ASK))
4647       {
4648         // remove setup config file
4649         unlink(setup_filename);
4650
4651         // set player name to default player name
4652         LoadSetup();
4653
4654         // update player name used by name typing functions
4655         strcpy(name, setup.player_name);
4656
4657         setTypeNameValues_Name(name, pos);
4658       }
4659     }
4660     else if (remove_user && type_name_nr != 0)
4661     {
4662       if (Request("Remove settings and tapes for deleted player?", REQ_ASK))
4663       {
4664         char *user_dir = getUserGameDataDir();
4665         char *user_dir_removed =
4666           getStringCat3WithSeparator(user_dir, "REMOVED",
4667                                      getCurrentTimestamp(), ".");
4668
4669         if (rename(user_dir, user_dir_removed) != 0)
4670           Request("Removing settings and tapes failed!", REQ_CONFIRM);
4671
4672         checked_free(user_dir_removed);
4673       }
4674     }
4675     else if (create_user && type_name_nr != 0 && !setup_exists)
4676     {
4677       if (Request("Create empty level set for the new player?", REQ_ASK))
4678       {
4679         char *levelset_subdir = getNewUserLevelSubdir();
4680
4681         if (CreateUserLevelSet(levelset_subdir, name, name, 100, FALSE))
4682         {
4683           AddUserLevelSetToLevelInfo(levelset_subdir);
4684
4685           LevelDirTree *leveldir_current_last = leveldir_current;
4686
4687           leveldir_current = getTreeInfoFromIdentifier(leveldir_first,
4688                                                        levelset_subdir);
4689
4690           // set level number of newly created level set to default value
4691           LoadLevelSetup_SeriesInfo();
4692
4693           // set newly created level set as current level set for new user
4694           SaveLevelSetup_LastSeries();
4695           SaveLevelSetup_SeriesInfo();
4696
4697           leveldir_current = leveldir_current_last;
4698         }
4699         else
4700         {
4701           Request("Creating new level set failed!", REQ_CONFIRM);
4702         }
4703       }
4704     }
4705
4706     // restore currently active user
4707     user.nr = last_user_nr;
4708
4709     // restore setup of currently active user
4710     LoadSetup();
4711
4712     // restore last level set of currently active user
4713     LoadLevelSetup_LastSeries();
4714     LoadLevelSetup_SeriesInfo();
4715   }
4716 }
4717
4718 static void HandleTypeNameExt(boolean initialize, Key key)
4719 {
4720   static struct TextPosInfo pos_name = { 0 };
4721   static char name[MAX_PLAYER_NAME_LEN + 1] = { 0 };
4722   static int xpos = 0;
4723   struct TextPosInfo *pos = &pos_name;
4724   char key_char = getValidConfigValueChar(getCharFromKey(key));
4725   boolean is_valid_key_char = (key_char != 0 && (key_char != ' ' || xpos > 0));
4726   boolean active = TRUE;
4727
4728   if (initialize)
4729   {
4730     getTypeNameValues(name, pos, &xpos);
4731
4732     int sx = mSX + ALIGNED_TEXT_XPOS(pos);
4733     int sy = mSY + ALIGNED_TEXT_YPOS(pos);
4734
4735     StartTextInput(sx, sy, pos->width, pos->height);
4736   }
4737   else if (is_valid_key_char && xpos < MAX_PLAYER_NAME_LEN)
4738   {
4739     name[xpos] = key_char;
4740     name[xpos + 1] = 0;
4741
4742     xpos++;
4743   }
4744   else if ((key == KSYM_Delete || key == KSYM_BackSpace) && xpos > 0)
4745   {
4746     xpos--;
4747
4748     name[xpos] = 0;
4749   }
4750   else if (key == KSYM_Return || key == KSYM_Escape)
4751   {
4752     boolean changed = (key == KSYM_Return);
4753
4754     StopTextInput();
4755
4756     setTypeNameValues(name, pos, changed);
4757
4758     active = FALSE;
4759   }
4760
4761   drawTypeNameText(name, pos, active);
4762
4763   if (!active)
4764   {
4765     SetGameStatus(game_status_last_screen);
4766
4767     if (game_status == GAME_MODE_MAIN)
4768       InitializeMainControls();
4769   }
4770 }
4771
4772 static void DrawTypeName(void)
4773 {
4774   HandleTypeNameExt(TRUE, 0);
4775 }
4776
4777 void HandleTypeName(Key key)
4778 {
4779   HandleTypeNameExt(FALSE, key);
4780 }
4781
4782
4783 // ============================================================================
4784 // tree menu functions
4785 // ============================================================================
4786
4787 static int getAlignXOffsetFromTreeInfo(TreeInfo *ti)
4788 {
4789   if (game_status != GAME_MODE_SETUP ||
4790       DRAW_MODE_SETUP(setup_mode) != SETUP_MODE_CHOOSE_OTHER)
4791     return 0;
4792
4793   int max_text_size = 0;
4794   TreeInfo *node;
4795
4796   for (node = getTreeInfoFirstGroupEntry(ti); node != NULL; node = node->next)
4797     max_text_size = MAX(max_text_size, strlen(node->name));
4798
4799   int num_entries = numTreeInfoInGroup(ti);
4800   boolean scrollbar_needed = (num_entries > NUM_MENU_ENTRIES_ON_SCREEN);
4801   int font_nr = MENU_CHOOSE_TREE_FONT(FC_RED);
4802   int text_width = max_text_size * getFontWidth(font_nr);
4803   int button_width = SC_MENUBUTTON_XSIZE;
4804   int scrollbar_xpos = SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
4805   int screen_width = (scrollbar_needed ? scrollbar_xpos : SXSIZE);
4806   int align = menu.list_setup[SETUP_MODE_CHOOSE_OTHER].align;
4807   int x = ALIGNED_XPOS(0, screen_width, align) * -1;
4808   int align_xoffset_raw = ALIGNED_XPOS(x, button_width + text_width, align);
4809   int align_xoffset = MAX(0, align_xoffset_raw);
4810
4811   return align_xoffset;
4812 }
4813
4814 static int getAlignYOffsetFromTreeInfo(TreeInfo *ti)
4815 {
4816   if (game_status != GAME_MODE_SETUP ||
4817       DRAW_MODE_SETUP(setup_mode) != SETUP_MODE_CHOOSE_OTHER)
4818     return 0;
4819
4820   int num_entries = numTreeInfoInGroup(ti);
4821   int num_page_entries = MIN(num_entries, NUM_MENU_ENTRIES_ON_SCREEN);
4822   int font_nr = MENU_CHOOSE_TREE_FONT(FC_RED);
4823   int font_height = getFontHeight(font_nr);
4824   int text_height = font_height * num_page_entries;
4825   int page_height = font_height * NUM_MENU_ENTRIES_ON_SCREEN;
4826   int align = menu.list_setup[SETUP_MODE_CHOOSE_OTHER].valign;
4827   int y = ALIGNED_YPOS(0, page_height, align) * -1;
4828   int align_yoffset_raw = ALIGNED_YPOS(y, text_height, align);
4829   int align_yoffset = MAX(0, align_yoffset_raw);
4830
4831   return align_yoffset;
4832 }
4833
4834 static void DrawChooseTree(TreeInfo **ti_ptr)
4835 {
4836   int fade_mask = REDRAW_FIELD;
4837
4838   if (CheckFadeAll())
4839     fade_mask = REDRAW_ALL;
4840
4841   if (*ti_ptr != NULL && strEqual((*ti_ptr)->subdir, STRING_TOP_DIRECTORY))
4842   {
4843     if (game_status == GAME_MODE_SETUP)
4844     {
4845       execSetupArtwork();
4846     }
4847     else        // GAME_MODE_LEVELS
4848     {
4849       SetGameStatus(GAME_MODE_MAIN);
4850
4851       DrawMainMenu();
4852     }
4853
4854     return;
4855   }
4856
4857   UnmapAllGadgets();
4858
4859   FreeScreenGadgets();
4860   CreateScreenGadgets();
4861
4862   if (game_status != game_status_last_screen)
4863     FadeMenuSoundsAndMusic();
4864
4865   FadeOut(fade_mask);
4866
4867   // needed if different viewport properties defined for this screen
4868   ChangeViewportPropertiesIfNeeded();
4869
4870   if (game_status == GAME_MODE_NAMES)
4871     SetMainBackgroundImage(IMG_BACKGROUND_NAMES);
4872   else if (game_status == GAME_MODE_LEVELNR)
4873     SetMainBackgroundImage(IMG_BACKGROUND_LEVELNR);
4874   else if (game_status == GAME_MODE_LEVELS)
4875     SetMainBackgroundImage(IMG_BACKGROUND_LEVELS);
4876   else if (game_status == GAME_MODE_SCORES)
4877     SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
4878
4879   ClearField();
4880
4881   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
4882
4883   // map gadgets for high score screen
4884   if (game_status == GAME_MODE_SCORES)
4885     MapScreenMenuGadgets(SCREEN_MASK_SCORES);
4886
4887   MapScreenTreeGadgets(*ti_ptr);
4888
4889   HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, ti_ptr);
4890
4891   DrawMaskedBorder(fade_mask);
4892
4893   if (game_status != game_status_last_screen)
4894     PlayMenuSoundsAndMusic();
4895
4896   FadeIn(fade_mask);
4897 }
4898
4899 static int getChooseTreeFont(TreeInfo *node, boolean active)
4900 {
4901   if (game_status == GAME_MODE_SCORES)
4902     return (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4903   else
4904     return MENU_CHOOSE_TREE_FONT(MENU_CHOOSE_TREE_COLOR(node, active));
4905 }
4906
4907 static void drawChooseTreeText(TreeInfo *ti, int y, boolean active)
4908 {
4909   int num_entries = numTreeInfoInGroup(ti);
4910   boolean scrollbar_needed = (num_entries > NUM_MENU_ENTRIES_ON_SCREEN);
4911   int scrollbar_xpos = SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
4912   int screen_width = (scrollbar_needed ? scrollbar_xpos : SXSIZE);
4913   int first_entry = ti->cl_first;
4914   int entry_pos = first_entry + y;
4915   TreeInfo *node_first = getTreeInfoFirstGroupEntry(ti);
4916   TreeInfo *node = getTreeInfoFromPos(node_first, entry_pos);
4917   int font_nr = getChooseTreeFont(node, active);
4918   int font_xoffset = getFontDrawOffsetX(font_nr);
4919   int xpos = MENU_SCREEN_START_XPOS;
4920   int ypos = MENU_SCREEN_START_YPOS + y;
4921   int startdx = xpos * 32;
4922   int startdy = ypos * 32;
4923   int startx = amSX + startdx;
4924   int starty = amSY + startdy;
4925   int startx_text = startx + font_xoffset;
4926   int endx_text = amSX + screen_width;
4927   int max_text_size = endx_text - startx_text;
4928   int max_buffer_len = max_text_size / getFontWidth(font_nr);
4929   char buffer[max_buffer_len + 1];
4930
4931   if (game_status == GAME_MODE_SCORES && !node->parent_link)
4932   {
4933     int font_nr1 = (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4934     int font_nr2 = (active ? FONT_TEXT_2_ACTIVE : FONT_TEXT_2);
4935     int font_nr3 = (active ? FONT_TEXT_3_ACTIVE : FONT_TEXT_3);
4936     int font_nr4 = (active ? FONT_TEXT_4_ACTIVE : FONT_TEXT_4);
4937     int font_size_1 = getFontWidth(font_nr1);
4938     int font_size_3 = getFontWidth(font_nr3);
4939     int font_size_4 = getFontWidth(font_nr4);
4940     int text_size_1 = 4 * font_size_1;
4941     int text_size_4 = 5 * font_size_4;
4942     int border = amSX - SX + getFontDrawOffsetX(font_nr1);
4943     int dx1 = 0;
4944     int dx3 = text_size_1;
4945     int dx4 = screen_width - startdx - 2 * border - text_size_4;
4946     int num_dots = (dx4 - dx3) / font_size_3;
4947     int startx1 = startx + dx1;
4948     int startx3 = startx + dx3;
4949     int startx4 = startx + dx4;
4950     int pos = node->pos;
4951     char *pos_text = getHallOfFameRankText(pos, 3);
4952     int i;
4953
4954     DrawText(startx1, starty, pos_text, font_nr1);
4955
4956     for (i = 0; i < num_dots; i++)
4957       DrawText(startx3 + i * font_size_3, starty, ".", font_nr3);
4958
4959     if (!strEqual(scores.entry[pos].name, EMPTY_PLAYER_NAME))
4960       DrawText(startx3, starty, scores.entry[pos].name, font_nr2);
4961
4962     DrawText(startx4, starty, getHallOfFameScoreText(pos, 5), font_nr4);
4963   }
4964   else
4965   {
4966     strncpy(buffer, node->name, max_buffer_len);
4967     buffer[max_buffer_len] = '\0';
4968
4969     DrawText(startx, starty, buffer, font_nr);
4970   }
4971 }
4972
4973 static void drawChooseTreeHeadExt(int type, char *title_string)
4974 {
4975   int yoffset_sets = MENU_TITLE1_YPOS;
4976   int yoffset_setup = 16;
4977   int yoffset = (type == TREE_TYPE_SCORE_ENTRY ||
4978                  type == TREE_TYPE_LEVEL_DIR ||
4979                  type == TREE_TYPE_LEVEL_NR ? yoffset_sets : yoffset_setup);
4980
4981   DrawTextSCentered(mSY - SY + yoffset, FONT_TITLE_1, title_string);
4982 }
4983
4984 static void drawChooseTreeHead(TreeInfo *ti)
4985 {
4986   drawChooseTreeHeadExt(ti->type, ti->infotext);
4987 }
4988
4989 static void drawChooseTreeList(TreeInfo *ti)
4990 {
4991   int first_entry = ti->cl_first;
4992   int num_entries = numTreeInfoInGroup(ti);
4993   int num_page_entries = MIN(num_entries, NUM_MENU_ENTRIES_ON_SCREEN);
4994   int i;
4995
4996   clearMenuListArea();
4997
4998   for (i = 0; i < num_page_entries; i++)
4999   {
5000     TreeInfo *node, *node_first;
5001     int entry_pos = first_entry + i;
5002
5003     node_first = getTreeInfoFirstGroupEntry(ti);
5004     node = getTreeInfoFromPos(node_first, entry_pos);
5005
5006     drawChooseTreeText(ti, i, FALSE);
5007
5008     if (node->parent_link)
5009       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
5010     else if (node->level_group)
5011       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
5012     else
5013       initCursor(i, IMG_MENU_BUTTON);
5014
5015     if (game_status == GAME_MODE_SCORES && node->pos == scores.last_added)
5016       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
5017
5018     if (game_status == GAME_MODE_NAMES)
5019       drawChooseTreeEdit(i, FALSE);
5020   }
5021
5022   redraw_mask |= REDRAW_FIELD;
5023 }
5024
5025 static void drawChooseTreeInfo(TreeInfo *ti)
5026 {
5027   int entry_pos = ti->cl_first + ti->cl_cursor;
5028   int last_redraw_mask = redraw_mask;
5029   int ypos = MENU_TITLE2_YPOS;
5030   int font_nr = FONT_TITLE_2;
5031   int x;
5032
5033   if (ti->type == TREE_TYPE_LEVEL_NR)
5034     DrawTextFCentered(ypos, font_nr, leveldir_current->name);
5035
5036   if (ti->type == TREE_TYPE_SCORE_ENTRY)
5037     DrawTextFCentered(ypos, font_nr, "HighScores of Level %d",
5038                       scores.last_level_nr);
5039
5040   if (ti->type != TREE_TYPE_LEVEL_DIR)
5041     return;
5042
5043   TreeInfo *node_first = getTreeInfoFirstGroupEntry(ti);
5044   TreeInfo *node = getTreeInfoFromPos(node_first, entry_pos);
5045
5046   DrawBackgroundForFont(SX, SY + ypos, SXSIZE, getFontHeight(font_nr), font_nr);
5047
5048   if (node->parent_link)
5049     DrawTextFCentered(ypos, font_nr, "leave \"%s\"",
5050                       node->node_parent->name);
5051   else if (node->level_group)
5052     DrawTextFCentered(ypos, font_nr, "enter \"%s\"",
5053                       node->name);
5054   else if (ti->type == TREE_TYPE_LEVEL_DIR)
5055     DrawTextFCentered(ypos, font_nr, "%3d %s (%s)",
5056                       node->levels, (node->levels > 1 ? "levels" : "level"),
5057                       node->class_desc);
5058
5059   // let BackToFront() redraw only what is needed
5060   redraw_mask = last_redraw_mask;
5061   for (x = 0; x < SCR_FIELDX; x++)
5062     MarkTileDirty(x, 1);
5063 }
5064
5065 static void drawChooseTreeCursorAndText(TreeInfo *ti, boolean active)
5066 {
5067   drawChooseTreeCursor(ti->cl_cursor, active);
5068   drawChooseTreeText(ti, ti->cl_cursor, active);
5069 }
5070
5071 static void drawChooseTreeScreen(TreeInfo *ti)
5072 {
5073   drawChooseTreeHead(ti);
5074   drawChooseTreeList(ti);
5075   drawChooseTreeInfo(ti);
5076   drawChooseTreeCursorAndText(ti, TRUE);
5077
5078   AdjustChooseTreeScrollbar(ti, SCREEN_CTRL_ID_SCROLL_VERTICAL);
5079
5080   // scroll bar and buttons may just have been added after reloading scores
5081   if (game_status == GAME_MODE_SCORES)
5082     MapScreenTreeGadgets(ti);
5083 }
5084
5085 static void drawChooseTreeScreen_Scores_NotAvailable(void)
5086 {
5087   // dirty workaround to use spacing definitions from info screen
5088   info_mode = INFO_MODE_TITLE;
5089
5090   char *text_info = "HighScores of Level %d";
5091   char *text_title = "Score information:";
5092   char *text_error = "No scores for this level.";
5093   char *text_foot = "Press any key or button for main menu";
5094   int font_info = FONT_TITLE_2;
5095   int font_title = FONT_INITIAL_3;
5096   int font_error = FONT_INITIAL_4;
5097   int font_foot  = FONT_INITIAL_2;
5098   int spacing_title = menu.headline1_spacing_info[INFO_MODE_TITLE];
5099   int ystep_title = getMenuTextStep(spacing_title, font_title);
5100   int ystart1 = mSY - SY + MENU_SCREEN_INFO_YSTART1;
5101   int ystart2 = ystart1 + ystep_title;
5102   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
5103   int ystart0 = MENU_TITLE2_YPOS;
5104
5105   drawChooseTreeHeadExt(TREE_TYPE_SCORE_ENTRY, INFOTEXT_SCORE_ENTRY);
5106   DrawTextFCentered(ystart0, font_info, text_info, scores.last_level_nr);
5107
5108   DrawTextSCentered(ystart1, font_title, text_title);
5109   DrawTextSCentered(ystart2, font_error, text_error);
5110
5111   DrawTextSCentered(ybottom, font_foot, text_foot);
5112 }
5113
5114 static TreeInfo *setHallOfFameActiveEntry(TreeInfo **ti_ptr)
5115 {
5116   // set current tree entry to last added score entry
5117   *ti_ptr = getTreeInfoFromIdentifier(score_entries, i_to_a(scores.last_added));
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 score_pos = (scores.last_added >= 0 ? scores.last_added : 0);
5713   int i;
5714
5715   if (score_entries != NULL)
5716   {
5717     freeTreeInfo(score_entries);
5718
5719     score_entries = NULL;
5720   }
5721
5722   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
5723   {
5724     // do not add empty score entries
5725     if (scores.entry[i].score == 0 &&
5726         scores.entry[i].time == 0)
5727       break;
5728
5729     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_SCORE_ENTRY);
5730     char identifier[32], name[64];
5731     int value = i;
5732
5733     ti->node_top = &score_entries;
5734     ti->sort_priority = 10000 + value;
5735     ti->color = FC_YELLOW;
5736     ti->pos = i;
5737
5738     snprintf(identifier, sizeof(identifier), "%d", value);
5739     snprintf(name, sizeof(name), "%03d.", value + 1);
5740
5741     setString(&ti->identifier, identifier);
5742     setString(&ti->name, name);
5743     setString(&ti->name_sorting, name);
5744
5745     pushTreeInfo(&score_entries, ti);
5746   }
5747
5748   // sort score entries to start with highest score entry
5749   sortTreeInfo(&score_entries);
5750
5751   // add top tree node to create back link to main menu
5752   score_entries = addTopTreeInfoNode(score_entries);
5753
5754   // set current score entry to last added or highest score entry
5755   score_entry_current =
5756     getTreeInfoFromIdentifier(score_entries, i_to_a(score_pos));
5757
5758   // if that fails, set current score entry to first valid score entry
5759   if (score_entry_current == NULL)
5760     score_entry_current = getFirstValidTreeInfoEntry(score_entries);
5761
5762   // ("score_entries" and "score_entry_current" may be NULL here)
5763 }
5764
5765 void DrawHallOfFame(int level_nr)
5766 {
5767   scores.last_level_nr = level_nr;
5768
5769   // (this is needed when called from GameEnd() after winning a game)
5770   KeyboardAutoRepeatOn();
5771
5772   // (this is needed when called from GameEnd() after winning a game)
5773   SetDrawDeactivationMask(REDRAW_NONE);
5774   SetDrawBackgroundMask(REDRAW_FIELD);
5775
5776   LoadLocalAndServerScore(level_nr, TRUE);
5777
5778   DrawHallOfFame_setScoreEntries();
5779
5780   if (scores.last_added >= 0)
5781     SetAnimStatus(GAME_MODE_PSEUDO_SCORESNEW);
5782
5783   FadeSetEnterScreen();
5784
5785   DrawChooseTree(&score_entry_current);
5786 }
5787
5788 static char *getHallOfFameRankText(int nr, int size)
5789 {
5790   static char rank_text[10];
5791   boolean forced = (scores.force_last_added && nr == scores.last_added);
5792   char *rank_text_raw = (forced ? "???" : int2str(nr + 1, size));
5793
5794   sprintf(rank_text, "%s%s", rank_text_raw, (size > 0 || !forced ? "." : ""));
5795
5796   return rank_text;
5797 }
5798
5799 static char *getHallOfFameTimeText(int nr)
5800 {
5801   static char score_text[10];
5802   int time_seconds = scores.entry[nr].time / FRAMES_PER_SECOND;
5803   int mm = (time_seconds / 60) % 60;
5804   int ss = (time_seconds % 60);
5805
5806   sprintf(score_text, "%02d:%02d", mm, ss);     // show playing time
5807
5808   return score_text;
5809 }
5810
5811 static char *getHallOfFameScoreText(int nr, int size)
5812 {
5813   if (!level.rate_time_over_score)
5814     return int2str(scores.entry[nr].score, size);       // show normal score
5815   else if (level.use_step_counter)
5816     return int2str(scores.entry[nr].time, size);        // show number of steps
5817   else
5818     return getHallOfFameTimeText(nr);                   // show playing time
5819 }
5820
5821 static void HandleHallOfFame_SelectLevel(int step, int direction)
5822 {
5823   int old_level_nr = scores.last_level_nr;
5824   int new_level_nr = old_level_nr + step * direction;
5825
5826   if (new_level_nr < leveldir_current->first_level)
5827     new_level_nr = leveldir_current->first_level;
5828   if (new_level_nr > leveldir_current->last_level)
5829     new_level_nr = leveldir_current->last_level;
5830
5831   if (setup.handicap && new_level_nr > leveldir_current->handicap_level)
5832     new_level_nr = leveldir_current->handicap_level;
5833
5834   if (new_level_nr != old_level_nr)
5835   {
5836     PlaySound(SND_MENU_ITEM_SELECTING);
5837
5838     scores.last_level_nr = level_nr = new_level_nr;
5839
5840     LoadLevel(level_nr);
5841     LoadLocalAndServerScore(level_nr, TRUE);
5842
5843     DrawHallOfFame_setScoreEntries();
5844
5845     // force remapping optional gadgets (especially scroll bar)
5846     UnmapScreenTreeGadgets();
5847
5848     // redraw complete high score screen, as sub-title has changed
5849     ClearField();
5850
5851     // redraw level selection buttons (which have just been erased)
5852     RedrawScreenMenuGadgets(SCREEN_MASK_SCORES);
5853
5854     HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, &score_entry_current);
5855
5856     SaveLevelSetup_SeriesInfo();
5857   }
5858 }
5859
5860 void HandleHallOfFame(int mx, int my, int dx, int dy, int button)
5861 {
5862   HandleChooseTree(mx, my, dx, dy, button, &score_entry_current);
5863 }
5864
5865 static void DrawScoreInfo_Content(int entry_nr)
5866 {
5867   struct ScoreEntry *entry = &scores.entry[entry_nr];
5868   char *pos_text = getHallOfFameRankText(entry_nr, 0);
5869   int font_title = MENU_INFO_FONT_TITLE;
5870   int font_head  = MENU_INFO_FONT_HEAD;
5871   int font_text  = MENU_INFO_FONT_TEXT;
5872   int font_foot  = MENU_INFO_FONT_FOOT;
5873   int spacing_title = menu.headline1_spacing[GAME_MODE_SCOREINFO];
5874   int spacing_para  = menu.paragraph_spacing[GAME_MODE_SCOREINFO];
5875   int spacing_line  = menu.line_spacing[GAME_MODE_SCOREINFO];
5876   int xstep = getFontWidth(font_text);
5877   int ystep_title = getMenuTextStep(spacing_title, font_title);
5878   int ystep_para  = getMenuTextStep(spacing_para,  font_text);
5879   int ystep_line  = getMenuTextStep(spacing_line,  font_text);
5880   int ystart  = mSY - SY + menu.top_spacing[GAME_MODE_SCOREINFO];
5881   int ybottom = mSY - SY + SYSIZE - menu.bottom_spacing[GAME_MODE_SCOREINFO];
5882   int xstart1 = mSX - SX + 2 * xstep;
5883   int xstart2 = mSX - SX + 13 * xstep;
5884   int font_width = getFontWidth(font_text);
5885   int font_height = getFontHeight(font_text);
5886   int pad_left = xstart2;
5887   int pad_right = MENU_SCREEN_INFO_SPACE_RIGHT;
5888   int max_chars_per_line = (SXSIZE - pad_left - pad_right) / font_width;
5889   int max_lines_per_text = 5;
5890   int lines;
5891
5892   ClearField();
5893
5894   // redraw score selection buttons (which have just been erased)
5895   RedrawScreenMenuGadgets(SCREEN_MASK_SCORES);
5896
5897   drawChooseTreeHead(score_entries);
5898   drawChooseTreeInfo(score_entries);
5899
5900   DrawTextSCentered(ystart, font_title, "Score Information:");
5901   ystart += ystep_title;
5902
5903   DrawTextF(xstart1, ystart, font_head, "Level Set");
5904   lines = DrawTextBufferS(xstart2, ystart, leveldir_current->name, font_text,
5905                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5906                           TRUE, FALSE, FALSE);
5907   ystart += ystep_line + (lines > 0 ? lines - 1 : 0) * font_height;
5908
5909   DrawTextF(xstart1, ystart, font_head, "Level");
5910   lines = DrawTextBufferS(xstart2, ystart, level.name, font_text,
5911                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5912                           TRUE, FALSE, FALSE);
5913   ystart += ystep_para + (lines > 0 ? lines - 1 : 0) * font_height;
5914
5915   DrawTextF(xstart1, ystart, font_head, "Rank");
5916   DrawTextF(xstart2, ystart, font_text, pos_text);
5917   ystart += ystep_line;
5918
5919   DrawTextF(xstart1, ystart, font_head, "Player");
5920   DrawTextF(xstart2, ystart, font_text, entry->name);
5921   ystart += ystep_line;
5922
5923   DrawTextF(xstart1, ystart, font_head, "Platform");
5924   DrawTextF(xstart2, ystart, font_text, entry->platform);
5925   ystart += ystep_line;
5926
5927   DrawTextF(xstart1, ystart, font_head, "Version");
5928   DrawTextF(xstart2, ystart, font_text, entry->version);
5929   ystart += ystep_line;
5930
5931   DrawTextF(xstart1, ystart, font_head, "Country");
5932   lines = DrawTextBufferS(xstart2, ystart, entry->country_name, font_text,
5933                           max_chars_per_line, -1, max_lines_per_text, 0, -1,
5934                           TRUE, FALSE, FALSE);
5935   ystart += ystep_line + (lines > 0 ? lines - 1 : 0) * font_height;
5936
5937   DrawTextF(xstart1, ystart, font_head, "Tape Date");
5938   DrawTextF(xstart2, ystart, font_text, entry->tape_date);
5939   ystart += ystep_line;
5940
5941   if (level.use_step_counter)
5942   {
5943     DrawTextF(xstart1, ystart, font_head, "Steps");
5944     DrawTextF(xstart2, ystart, font_text, int2str(entry->time, 5));
5945     ystart += ystep_line;
5946   }
5947   else
5948   {
5949     DrawTextF(xstart1, ystart, font_head, "Time");
5950     DrawTextF(xstart2, ystart, font_text, getHallOfFameTimeText(entry_nr));
5951     ystart += ystep_line;
5952   }
5953
5954   if (!level.rate_time_over_score || entry->score > 0)
5955   {
5956     DrawTextF(xstart1, ystart, font_head, "Score");
5957     DrawTextF(xstart2, ystart, font_text, int2str(entry->score, 5));
5958     ystart += ystep_line;
5959   }
5960
5961   DrawTextSCentered(ybottom, font_foot, "Press any key or button to go back");
5962 }
5963
5964 static void DrawScoreInfo(int entry_nr)
5965 {
5966   scores.last_entry_nr = entry_nr;
5967
5968   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_SCOREINFO);
5969
5970   UnmapAllGadgets();
5971
5972   FadeOut(REDRAW_FIELD);
5973
5974   // map gadgets for score info screen
5975   MapScreenMenuGadgets(SCREEN_MASK_SCORES);
5976
5977   DrawScoreInfo_Content(entry_nr);
5978
5979   FadeIn(REDRAW_FIELD);
5980 }
5981
5982 static void HandleScoreInfo_SelectScore(int step, int direction)
5983 {
5984   int old_entry_nr = scores.last_entry_nr;
5985   int new_entry_nr = old_entry_nr + step * direction;
5986   int num_nodes = numTreeInfoInGroup(score_entry_current);
5987   int num_entries = num_nodes - 1;      // score nodes only, without back link
5988
5989   if (new_entry_nr < 0)
5990     new_entry_nr = 0;
5991   if (new_entry_nr > num_entries - 1)
5992     new_entry_nr = num_entries - 1;
5993
5994   if (new_entry_nr != old_entry_nr)
5995   {
5996     scores.last_entry_nr = new_entry_nr;
5997
5998     DrawScoreInfo_Content(new_entry_nr);
5999   }
6000 }
6001
6002 void HandleScoreInfo(int mx, int my, int dx, int dy, int button)
6003 {
6004   boolean button_action = (button == MB_MENU_LEAVE || button == MB_MENU_CHOICE);
6005   boolean button_is_valid = (mx >= 0 && my >= 0);
6006   boolean button_screen_clicked = (button_action && button_is_valid);
6007
6008   if (button_screen_clicked)
6009   {
6010     PlaySound(SND_MENU_ITEM_SELECTING);
6011
6012     SetGameStatus(GAME_MODE_SCORES);
6013
6014     DrawHallOfFame(level_nr);
6015   }
6016   else if (dx || dy)
6017   {
6018     HandleScoreInfo_SelectScore(1, SIGN(dx ? dx : dy));
6019   }
6020 }
6021
6022 static void HandleHallOfFame_SelectLevelOrScore(int step, int direction)
6023 {
6024   if (game_status == GAME_MODE_SCORES)
6025     HandleHallOfFame_SelectLevel(step, direction);
6026   else
6027     HandleScoreInfo_SelectScore(step, direction);
6028 }
6029
6030
6031 // ============================================================================
6032 // setup screen functions
6033 // ============================================================================
6034
6035 static struct TokenInfo *setup_info;
6036 static int num_setup_info;      // number of setup entries shown on screen
6037 static int max_setup_info;      // total number of setup entries in list
6038
6039 static char *window_size_text;
6040 static char *scaling_type_text;
6041 static char *rendering_mode_text;
6042 static char *vsync_mode_text;
6043 static char *scroll_delay_text;
6044 static char *snapshot_mode_text;
6045 static char *game_speed_text;
6046 static char *scores_type_text;
6047 static char *network_server_text;
6048 static char *graphics_set_name;
6049 static char *sounds_set_name;
6050 static char *music_set_name;
6051 static char *volume_simple_text;
6052 static char *volume_loops_text;
6053 static char *volume_music_text;
6054 static char *touch_controls_text;
6055 static char *move_distance_text;
6056 static char *drop_distance_text;
6057 static char *transparency_text;
6058 static char *grid_size_text[2][2];
6059
6060 static void execSetupMain(void)
6061 {
6062   setup_mode = SETUP_MODE_MAIN;
6063
6064   DrawSetupScreen();
6065 }
6066
6067 static void execSetupGame_setScoresType(void)
6068 {
6069   if (scores_types == NULL)
6070   {
6071     int i;
6072
6073     for (i = 0; scores_types_list[i].value != NULL; i++)
6074     {
6075       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6076       char identifier[32], name[32];
6077       char *value = scores_types_list[i].value;
6078       char *text = scores_types_list[i].text;
6079
6080       ti->node_top = &scores_types;
6081       ti->sort_priority = i;
6082
6083       sprintf(identifier, "%s", value);
6084       sprintf(name, "%s", text);
6085
6086       setString(&ti->identifier, identifier);
6087       setString(&ti->name, name);
6088       setString(&ti->name_sorting, name);
6089       setString(&ti->infotext, STR_SETUP_CHOOSE_SCORES_TYPE);
6090
6091       pushTreeInfo(&scores_types, ti);
6092     }
6093
6094     // sort scores type values to start with lowest scores type value
6095     sortTreeInfo(&scores_types);
6096
6097     // set current scores type value to configured scores type value
6098     scores_type_current =
6099       getTreeInfoFromIdentifier(scores_types, setup.scores_in_highscore_list);
6100
6101     // if that fails, set current scores type to reliable default value
6102     if (scores_type_current == NULL)
6103       scores_type_current =
6104         getTreeInfoFromIdentifier(scores_types, STR_SCORES_TYPE_DEFAULT);
6105
6106     // if that also fails, set current scores type to first available value
6107     if (scores_type_current == NULL)
6108       scores_type_current = scores_types;
6109   }
6110
6111   setup.scores_in_highscore_list = scores_type_current->identifier;
6112
6113   // needed for displaying scores type text instead of identifier
6114   scores_type_text = scores_type_current->name;
6115 }
6116
6117 static void execSetupGame_setGameSpeeds(boolean update_value)
6118 {
6119   if (setup.game_speed_extended)
6120   {
6121     game_speeds_list = game_speeds_list_extended;
6122     game_speeds      = game_speeds_extended;
6123   }
6124   else
6125   {
6126     game_speeds_list = game_speeds_list_normal;
6127     game_speeds      = game_speeds_normal;
6128   }
6129
6130   if (game_speeds == NULL)
6131   {
6132     int i;
6133
6134     for (i = 0; game_speeds_list[i].value != -1; i++)
6135     {
6136       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6137       char identifier[32], name[32];
6138       int value = game_speeds_list[i].value;
6139       char *text = game_speeds_list[i].text;
6140
6141       ti->node_top = &game_speeds;
6142       ti->sort_priority = 10000 - value;
6143
6144       sprintf(identifier, "%d", value);
6145       sprintf(name, "%s", text);
6146
6147       setString(&ti->identifier, identifier);
6148       setString(&ti->name, name);
6149       setString(&ti->name_sorting, name);
6150       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_SPEED);
6151
6152       pushTreeInfo(&game_speeds, ti);
6153     }
6154
6155     // sort game speed values to start with slowest game speed
6156     sortTreeInfo(&game_speeds);
6157
6158     update_value = TRUE;
6159   }
6160
6161   if (update_value)
6162   {
6163     // set current game speed to configured game speed value
6164     game_speed_current =
6165       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
6166
6167     // if that fails, set current game speed to reliable default value
6168     if (game_speed_current == NULL)
6169       game_speed_current =
6170         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
6171
6172     // if that also fails, set current game speed to first available speed
6173     if (game_speed_current == NULL)
6174       game_speed_current = game_speeds;
6175
6176     if (setup.game_speed_extended)
6177       game_speeds_extended = game_speeds;
6178     else
6179       game_speeds_normal = game_speeds;
6180   }
6181
6182   setup.game_frame_delay = atoi(game_speed_current->identifier);
6183
6184   // needed for displaying game speed text instead of identifier
6185   game_speed_text = game_speed_current->name;
6186 }
6187
6188 static void execSetupGame_setScrollDelays(void)
6189 {
6190   if (scroll_delays == NULL)
6191   {
6192     int i;
6193
6194     for (i = 0; scroll_delays_list[i].value != -1; i++)
6195     {
6196       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6197       char identifier[32], name[32];
6198       int value = scroll_delays_list[i].value;
6199       char *text = scroll_delays_list[i].text;
6200
6201       ti->node_top = &scroll_delays;
6202       ti->sort_priority = value;
6203
6204       sprintf(identifier, "%d", value);
6205       sprintf(name, "%s", text);
6206
6207       setString(&ti->identifier, identifier);
6208       setString(&ti->name, name);
6209       setString(&ti->name_sorting, name);
6210       setString(&ti->infotext, STR_SETUP_CHOOSE_SCROLL_DELAY);
6211
6212       pushTreeInfo(&scroll_delays, ti);
6213     }
6214
6215     // sort scroll delay values to start with lowest scroll delay value
6216     sortTreeInfo(&scroll_delays);
6217
6218     // set current scroll delay value to configured scroll delay value
6219     scroll_delay_current =
6220       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
6221
6222     // if that fails, set current scroll delay to reliable default value
6223     if (scroll_delay_current == NULL)
6224       scroll_delay_current =
6225         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
6226
6227     // if that also fails, set current scroll delay to first available value
6228     if (scroll_delay_current == NULL)
6229       scroll_delay_current = scroll_delays;
6230   }
6231
6232   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
6233
6234   // needed for displaying scroll delay text instead of identifier
6235   scroll_delay_text = scroll_delay_current->name;
6236 }
6237
6238 static void execSetupGame_setSnapshotModes(void)
6239 {
6240   if (snapshot_modes == NULL)
6241   {
6242     int i;
6243
6244     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
6245     {
6246       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6247       char identifier[32], name[32];
6248       char *value = snapshot_modes_list[i].value;
6249       char *text = snapshot_modes_list[i].text;
6250
6251       ti->node_top = &snapshot_modes;
6252       ti->sort_priority = i;
6253
6254       sprintf(identifier, "%s", value);
6255       sprintf(name, "%s", text);
6256
6257       setString(&ti->identifier, identifier);
6258       setString(&ti->name, name);
6259       setString(&ti->name_sorting, name);
6260       setString(&ti->infotext, STR_SETUP_CHOOSE_SNAPSHOT_MODE);
6261
6262       pushTreeInfo(&snapshot_modes, ti);
6263     }
6264
6265     // sort snapshot mode values to start with lowest snapshot mode value
6266     sortTreeInfo(&snapshot_modes);
6267
6268     // set current snapshot mode value to configured snapshot mode value
6269     snapshot_mode_current =
6270       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
6271
6272     // if that fails, set current snapshot mode to reliable default value
6273     if (snapshot_mode_current == NULL)
6274       snapshot_mode_current =
6275         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
6276
6277     // if that also fails, set current snapshot mode to first available value
6278     if (snapshot_mode_current == NULL)
6279       snapshot_mode_current = snapshot_modes;
6280   }
6281
6282   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
6283
6284   // needed for displaying snapshot mode text instead of identifier
6285   snapshot_mode_text = snapshot_mode_current->name;
6286 }
6287
6288 static void execSetupGame_setNetworkServerText(void)
6289 {
6290   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
6291   {
6292     strcpy(network_server_hostname, STR_NETWORK_AUTO_DETECT_SETUP);
6293   }
6294   else
6295   {
6296     strncpy(network_server_hostname, setup.network_server_hostname,
6297             MAX_SETUP_TEXT_INPUT_LEN);
6298     network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN] = '\0';
6299   }
6300
6301   // needed for displaying network server text instead of identifier
6302   network_server_text = network_server_hostname;
6303 }
6304
6305 static void execSetupGame(void)
6306 {
6307   boolean check_vsync_mode = (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED);
6308
6309   execSetupGame_setGameSpeeds(FALSE);
6310   execSetupGame_setScoresType();
6311   execSetupGame_setScrollDelays();
6312   execSetupGame_setSnapshotModes();
6313
6314   execSetupGame_setNetworkServerText();
6315
6316   if (!setup.provide_uploading_tapes)
6317     setHideSetupEntry(execOfferUploadTapes);
6318
6319   setup_mode = SETUP_MODE_GAME;
6320
6321   DrawSetupScreen();
6322
6323   // check if vsync needs to be disabled for this game speed to work
6324   if (check_vsync_mode)
6325     DisableVsyncIfNeeded();
6326 }
6327
6328 static void execSetupChooseScoresType(void)
6329 {
6330   setup_mode = SETUP_MODE_CHOOSE_SCORES_TYPE;
6331
6332   DrawSetupScreen();
6333 }
6334
6335 static void execSetupChooseGameSpeed(void)
6336 {
6337   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
6338
6339   DrawSetupScreen();
6340 }
6341
6342 static void execSetupChooseScrollDelay(void)
6343 {
6344   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
6345
6346   DrawSetupScreen();
6347 }
6348
6349 static void execSetupChooseSnapshotMode(void)
6350 {
6351   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
6352
6353   DrawSetupScreen();
6354 }
6355
6356 static void execSetupEngines(void)
6357 {
6358   setup_mode = SETUP_MODE_ENGINES;
6359
6360   DrawSetupScreen();
6361 }
6362
6363 static void execSetupEditor(void)
6364 {
6365   setup_mode = SETUP_MODE_EDITOR;
6366
6367   DrawSetupScreen();
6368 }
6369
6370 static void execSetupGraphics_setWindowSizes(boolean update_list)
6371 {
6372   if (window_sizes != NULL && update_list)
6373   {
6374     freeTreeInfo(window_sizes);
6375
6376     window_sizes = NULL;
6377   }
6378
6379   if (window_sizes == NULL)
6380   {
6381     boolean current_window_size_found = FALSE;
6382     int i;
6383
6384     for (i = 0; window_sizes_list[i].value != -1; i++)
6385     {
6386       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6387       char identifier[32], name[32];
6388       int value = window_sizes_list[i].value;
6389       char *text = window_sizes_list[i].text;
6390
6391       ti->node_top = &window_sizes;
6392       ti->sort_priority = value;
6393
6394       sprintf(identifier, "%d", value);
6395       sprintf(name, "%s", text);
6396
6397       setString(&ti->identifier, identifier);
6398       setString(&ti->name, name);
6399       setString(&ti->name_sorting, name);
6400       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6401
6402       pushTreeInfo(&window_sizes, ti);
6403
6404       if (value == setup.window_scaling_percent)
6405         current_window_size_found = TRUE;
6406     }
6407
6408     if (!current_window_size_found)
6409     {
6410       // add entry for non-preset window scaling value
6411
6412       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6413       char identifier[32], name[32];
6414       int value = setup.window_scaling_percent;
6415
6416       ti->node_top = &window_sizes;
6417       ti->sort_priority = value;
6418
6419       sprintf(identifier, "%d", value);
6420       sprintf(name, "%d %% (Current)", value);
6421
6422       setString(&ti->identifier, identifier);
6423       setString(&ti->name, name);
6424       setString(&ti->name_sorting, name);
6425       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6426
6427       pushTreeInfo(&window_sizes, ti);
6428     }
6429
6430     // sort window size values to start with lowest window size value
6431     sortTreeInfo(&window_sizes);
6432
6433     // set current window size value to configured window size value
6434     window_size_current =
6435       getTreeInfoFromIdentifier(window_sizes,
6436                                 i_to_a(setup.window_scaling_percent));
6437
6438     // if that fails, set current window size to reliable default value
6439     if (window_size_current == NULL)
6440       window_size_current =
6441         getTreeInfoFromIdentifier(window_sizes,
6442                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
6443
6444     // if that also fails, set current window size to first available value
6445     if (window_size_current == NULL)
6446       window_size_current = window_sizes;
6447   }
6448
6449   setup.window_scaling_percent = atoi(window_size_current->identifier);
6450
6451   // needed for displaying window size text instead of identifier
6452   window_size_text = window_size_current->name;
6453 }
6454
6455 static void execSetupGraphics_setScalingTypes(void)
6456 {
6457   if (scaling_types == NULL)
6458   {
6459     int i;
6460
6461     for (i = 0; scaling_types_list[i].value != NULL; i++)
6462     {
6463       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6464       char identifier[32], name[32];
6465       char *value = scaling_types_list[i].value;
6466       char *text = scaling_types_list[i].text;
6467
6468       ti->node_top = &scaling_types;
6469       ti->sort_priority = i;
6470
6471       sprintf(identifier, "%s", value);
6472       sprintf(name, "%s", text);
6473
6474       setString(&ti->identifier, identifier);
6475       setString(&ti->name, name);
6476       setString(&ti->name_sorting, name);
6477       setString(&ti->infotext, STR_SETUP_CHOOSE_SCALING_TYPE);
6478
6479       pushTreeInfo(&scaling_types, ti);
6480     }
6481
6482     // sort scaling type values to start with lowest scaling type value
6483     sortTreeInfo(&scaling_types);
6484
6485     // set current scaling type value to configured scaling type value
6486     scaling_type_current =
6487       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
6488
6489     // if that fails, set current scaling type to reliable default value
6490     if (scaling_type_current == NULL)
6491       scaling_type_current =
6492         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
6493
6494     // if that also fails, set current scaling type to first available value
6495     if (scaling_type_current == NULL)
6496       scaling_type_current = scaling_types;
6497   }
6498
6499   setup.window_scaling_quality = scaling_type_current->identifier;
6500
6501   // needed for displaying scaling type text instead of identifier
6502   scaling_type_text = scaling_type_current->name;
6503 }
6504
6505 static void execSetupGraphics_setRenderingModes(void)
6506 {
6507   if (rendering_modes == NULL)
6508   {
6509     int i;
6510
6511     for (i = 0; rendering_modes_list[i].value != NULL; i++)
6512     {
6513       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6514       char identifier[32], name[32];
6515       char *value = rendering_modes_list[i].value;
6516       char *text = rendering_modes_list[i].text;
6517
6518       ti->node_top = &rendering_modes;
6519       ti->sort_priority = i;
6520
6521       sprintf(identifier, "%s", value);
6522       sprintf(name, "%s", text);
6523
6524       setString(&ti->identifier, identifier);
6525       setString(&ti->name, name);
6526       setString(&ti->name_sorting, name);
6527       setString(&ti->infotext, STR_SETUP_CHOOSE_RENDERING);
6528
6529       pushTreeInfo(&rendering_modes, ti);
6530     }
6531
6532     // sort rendering mode values to start with lowest rendering mode value
6533     sortTreeInfo(&rendering_modes);
6534
6535     // set current rendering mode value to configured rendering mode value
6536     rendering_mode_current =
6537       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
6538
6539     // if that fails, set current rendering mode to reliable default value
6540     if (rendering_mode_current == NULL)
6541       rendering_mode_current =
6542         getTreeInfoFromIdentifier(rendering_modes,
6543                                   STR_SPECIAL_RENDERING_DEFAULT);
6544
6545     // if that also fails, set current rendering mode to first available one
6546     if (rendering_mode_current == NULL)
6547       rendering_mode_current = rendering_modes;
6548   }
6549
6550   setup.screen_rendering_mode = rendering_mode_current->identifier;
6551
6552   // needed for displaying rendering mode text instead of identifier
6553   rendering_mode_text = rendering_mode_current->name;
6554 }
6555
6556 static void execSetupGraphics_setVsyncModes(boolean update_value)
6557 {
6558   if (vsync_modes == NULL)
6559   {
6560     int i;
6561
6562     for (i = 0; vsync_modes_list[i].value != NULL; i++)
6563     {
6564       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6565       char identifier[32], name[32];
6566       char *value = vsync_modes_list[i].value;
6567       char *text = vsync_modes_list[i].text;
6568
6569       ti->node_top = &vsync_modes;
6570       ti->sort_priority = i;
6571
6572       sprintf(identifier, "%s", value);
6573       sprintf(name, "%s", text);
6574
6575       setString(&ti->identifier, identifier);
6576       setString(&ti->name, name);
6577       setString(&ti->name_sorting, name);
6578       setString(&ti->infotext, STR_SETUP_CHOOSE_VSYNC);
6579
6580       pushTreeInfo(&vsync_modes, ti);
6581     }
6582
6583     // sort vsync mode values to start with lowest vsync mode value
6584     sortTreeInfo(&vsync_modes);
6585
6586     update_value = TRUE;
6587   }
6588
6589   if (update_value)
6590   {
6591     // set current vsync mode value to configured vsync mode value
6592     vsync_mode_current =
6593       getTreeInfoFromIdentifier(vsync_modes, setup.vsync_mode);
6594
6595     // if that fails, set current vsync mode to reliable default value
6596     if (vsync_mode_current == NULL)
6597       vsync_mode_current =
6598         getTreeInfoFromIdentifier(vsync_modes, STR_VSYNC_MODE_DEFAULT);
6599
6600     // if that also fails, set current vsync mode to first available one
6601     if (vsync_mode_current == NULL)
6602       vsync_mode_current = vsync_modes;
6603   }
6604
6605   setup.vsync_mode = vsync_mode_current->identifier;
6606
6607   // needed for displaying vsync mode text instead of identifier
6608   vsync_mode_text = vsync_mode_current->name;
6609 }
6610
6611 static void execSetupGraphics(void)
6612 {
6613   boolean check_game_speed = (setup_mode == SETUP_MODE_CHOOSE_VSYNC);
6614
6615   // update "setup.window_scaling_percent" from list selection
6616   // (in this case, window scaling was changed on setup screen)
6617   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6618     execSetupGraphics_setWindowSizes(FALSE);
6619
6620   // update "setup.vsync_mode" from list selection
6621   // (in this case, vsync mode was changed on setup screen)
6622   if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
6623     execSetupGraphics_setVsyncModes(FALSE);
6624
6625   // update list selection from "setup.window_scaling_percent"
6626   // (window scaling may have changed by resizing the window)
6627   execSetupGraphics_setWindowSizes(TRUE);
6628
6629   // update list selection from "setup.vsync_mode"
6630   // (vsync_mode may have changed by re-creating the renderer)
6631   execSetupGraphics_setVsyncModes(TRUE);
6632
6633   execSetupGraphics_setScalingTypes();
6634   execSetupGraphics_setRenderingModes();
6635
6636   setup_mode = SETUP_MODE_GRAPHICS;
6637
6638   DrawSetupScreen();
6639
6640   // check if game speed is high enough for 60 Hz vsync to work
6641   if (check_game_speed)
6642     ModifyGameSpeedIfNeeded();
6643
6644   // window scaling may have changed at this point
6645   ChangeWindowScalingIfNeeded();
6646
6647   // window scaling quality may have changed at this point
6648   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
6649     SDLSetWindowScalingQuality(setup.window_scaling_quality);
6650
6651   // screen rendering mode may have changed at this point
6652   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
6653
6654   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
6655   int video_vsync_mode = video.vsync_mode;
6656
6657   // screen vsync mode may have changed at this point
6658   ChangeVsyncModeIfNeeded();
6659
6660   // check if setting vsync mode to selected value failed
6661   if (setup_vsync_mode != video_vsync_mode &&
6662       setup_vsync_mode != video.vsync_mode)
6663   {
6664     // changing vsync mode to selected value failed -- reset displayed value
6665     execSetupGraphics_setVsyncModes(TRUE);
6666
6667     Request("Setting VSync failed!", REQ_CONFIRM);
6668
6669     DrawSetupScreen();
6670   }
6671 }
6672
6673 static void execSetupChooseWindowSize(void)
6674 {
6675   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
6676
6677   DrawSetupScreen();
6678 }
6679
6680 static void execSetupChooseScalingType(void)
6681 {
6682   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
6683
6684   DrawSetupScreen();
6685 }
6686
6687 static void execSetupChooseRenderingMode(void)
6688 {
6689   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
6690
6691   DrawSetupScreen();
6692 }
6693
6694 static void execSetupChooseVsyncMode(void)
6695 {
6696   setup_mode = SETUP_MODE_CHOOSE_VSYNC;
6697
6698   DrawSetupScreen();
6699 }
6700
6701 static void execSetupChooseVolumeSimple(void)
6702 {
6703   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
6704
6705   DrawSetupScreen();
6706 }
6707
6708 static void execSetupChooseVolumeLoops(void)
6709 {
6710   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
6711
6712   DrawSetupScreen();
6713 }
6714
6715 static void execSetupChooseVolumeMusic(void)
6716 {
6717   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
6718
6719   DrawSetupScreen();
6720 }
6721
6722 static void execSetupSound(void)
6723 {
6724   if (volumes_simple == NULL)
6725   {
6726     boolean current_volume_simple_found = FALSE;
6727     int i;
6728
6729     for (i = 0; volumes_list[i].value != -1; i++)
6730     {
6731       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6732       char identifier[32], name[32];
6733       int value = volumes_list[i].value;
6734       char *text = volumes_list[i].text;
6735
6736       ti->node_top = &volumes_simple;
6737       ti->sort_priority = value;
6738
6739       sprintf(identifier, "%d", value);
6740       sprintf(name, "%s", text);
6741
6742       setString(&ti->identifier, identifier);
6743       setString(&ti->name, name);
6744       setString(&ti->name_sorting, name);
6745       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6746
6747       pushTreeInfo(&volumes_simple, ti);
6748
6749       if (value == setup.volume_simple)
6750         current_volume_simple_found = TRUE;
6751     }
6752
6753     if (!current_volume_simple_found)
6754     {
6755       // add entry for non-preset volume value
6756
6757       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6758       char identifier[32], name[32];
6759       int value = setup.volume_simple;
6760
6761       ti->node_top = &volumes_simple;
6762       ti->sort_priority = value;
6763
6764       sprintf(identifier, "%d", value);
6765       sprintf(name, "%d %% (Current)", value);
6766
6767       setString(&ti->identifier, identifier);
6768       setString(&ti->name, name);
6769       setString(&ti->name_sorting, name);
6770       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6771
6772       pushTreeInfo(&volumes_simple, ti);
6773     }
6774
6775     // sort volume values to start with lowest volume value
6776     sortTreeInfo(&volumes_simple);
6777
6778     // set current volume value to configured volume value
6779     volume_simple_current =
6780       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
6781
6782     // if that fails, set current volume to reliable default value
6783     if (volume_simple_current == NULL)
6784       volume_simple_current =
6785         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
6786
6787     // if that also fails, set current volume to first available value
6788     if (volume_simple_current == NULL)
6789       volume_simple_current = volumes_simple;
6790   }
6791
6792   if (volumes_loops == NULL)
6793   {
6794     boolean current_volume_loops_found = FALSE;
6795     int i;
6796
6797     for (i = 0; volumes_list[i].value != -1; i++)
6798     {
6799       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6800       char identifier[32], name[32];
6801       int value = volumes_list[i].value;
6802       char *text = volumes_list[i].text;
6803
6804       ti->node_top = &volumes_loops;
6805       ti->sort_priority = value;
6806
6807       sprintf(identifier, "%d", value);
6808       sprintf(name, "%s", text);
6809
6810       setString(&ti->identifier, identifier);
6811       setString(&ti->name, name);
6812       setString(&ti->name_sorting, name);
6813       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6814
6815       pushTreeInfo(&volumes_loops, ti);
6816
6817       if (value == setup.volume_loops)
6818         current_volume_loops_found = TRUE;
6819     }
6820
6821     if (!current_volume_loops_found)
6822     {
6823       // add entry for non-preset volume value
6824
6825       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6826       char identifier[32], name[32];
6827       int value = setup.volume_loops;
6828
6829       ti->node_top = &volumes_loops;
6830       ti->sort_priority = value;
6831
6832       sprintf(identifier, "%d", value);
6833       sprintf(name, "%d %% (Current)", value);
6834
6835       setString(&ti->identifier, identifier);
6836       setString(&ti->name, name);
6837       setString(&ti->name_sorting, name);
6838       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6839
6840       pushTreeInfo(&volumes_loops, ti);
6841     }
6842
6843     // sort volume values to start with lowest volume value
6844     sortTreeInfo(&volumes_loops);
6845
6846     // set current volume value to configured volume value
6847     volume_loops_current =
6848       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
6849
6850     // if that fails, set current volume to reliable default value
6851     if (volume_loops_current == NULL)
6852       volume_loops_current =
6853         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
6854
6855     // if that also fails, set current volume to first available value
6856     if (volume_loops_current == NULL)
6857       volume_loops_current = volumes_loops;
6858   }
6859
6860   if (volumes_music == NULL)
6861   {
6862     boolean current_volume_music_found = FALSE;
6863     int i;
6864
6865     for (i = 0; volumes_list[i].value != -1; i++)
6866     {
6867       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6868       char identifier[32], name[32];
6869       int value = volumes_list[i].value;
6870       char *text = volumes_list[i].text;
6871
6872       ti->node_top = &volumes_music;
6873       ti->sort_priority = value;
6874
6875       sprintf(identifier, "%d", value);
6876       sprintf(name, "%s", text);
6877
6878       setString(&ti->identifier, identifier);
6879       setString(&ti->name, name);
6880       setString(&ti->name_sorting, name);
6881       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6882
6883       pushTreeInfo(&volumes_music, ti);
6884
6885       if (value == setup.volume_music)
6886         current_volume_music_found = TRUE;
6887     }
6888
6889     if (!current_volume_music_found)
6890     {
6891       // add entry for non-preset volume value
6892
6893       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6894       char identifier[32], name[32];
6895       int value = setup.volume_music;
6896
6897       ti->node_top = &volumes_music;
6898       ti->sort_priority = value;
6899
6900       sprintf(identifier, "%d", value);
6901       sprintf(name, "%d %% (Current)", value);
6902
6903       setString(&ti->identifier, identifier);
6904       setString(&ti->name, name);
6905       setString(&ti->name_sorting, name);
6906       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6907
6908       pushTreeInfo(&volumes_music, ti);
6909     }
6910
6911     // sort volume values to start with lowest volume value
6912     sortTreeInfo(&volumes_music);
6913
6914     // set current volume value to configured volume value
6915     volume_music_current =
6916       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
6917
6918     // if that fails, set current volume to reliable default value
6919     if (volume_music_current == NULL)
6920       volume_music_current =
6921         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
6922
6923     // if that also fails, set current volume to first available value
6924     if (volume_music_current == NULL)
6925       volume_music_current = volumes_music;
6926   }
6927
6928   setup.volume_simple = atoi(volume_simple_current->identifier);
6929   setup.volume_loops  = atoi(volume_loops_current->identifier);
6930   setup.volume_music  = atoi(volume_music_current->identifier);
6931
6932   // needed for displaying volume text instead of identifier
6933   volume_simple_text = volume_simple_current->name;
6934   volume_loops_text = volume_loops_current->name;
6935   volume_music_text = volume_music_current->name;
6936
6937   setup_mode = SETUP_MODE_SOUND;
6938
6939   DrawSetupScreen();
6940 }
6941
6942 static void execSetupChooseTouchControls(void)
6943 {
6944   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
6945
6946   DrawSetupScreen();
6947 }
6948
6949 static void execSetupChooseMoveDistance(void)
6950 {
6951   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
6952
6953   DrawSetupScreen();
6954 }
6955
6956 static void execSetupChooseDropDistance(void)
6957 {
6958   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
6959
6960   DrawSetupScreen();
6961 }
6962
6963 static void execSetupChooseTransparency(void)
6964 {
6965   setup_mode = SETUP_MODE_CHOOSE_TRANSPARENCY;
6966
6967   DrawSetupScreen();
6968 }
6969
6970 static void execSetupChooseGridXSize_0(void)
6971 {
6972   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_0;
6973
6974   DrawSetupScreen();
6975 }
6976
6977 static void execSetupChooseGridYSize_0(void)
6978 {
6979   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_0;
6980
6981   DrawSetupScreen();
6982 }
6983
6984 static void execSetupChooseGridXSize_1(void)
6985 {
6986   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_1;
6987
6988   DrawSetupScreen();
6989 }
6990
6991 static void execSetupChooseGridYSize_1(void)
6992 {
6993   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_1;
6994
6995   DrawSetupScreen();
6996 }
6997
6998 static void execSetupConfigureVirtualButtons(void)
6999 {
7000   setup_mode = SETUP_MODE_CONFIG_VIRT_BUTTONS;
7001
7002   ConfigureVirtualButtons();
7003
7004   setup_mode = SETUP_MODE_TOUCH;
7005
7006   DrawSetupScreen();
7007 }
7008
7009 static void execSetupTouch(void)
7010 {
7011   int i, j, k;
7012
7013   if (touch_controls == NULL)
7014   {
7015     for (i = 0; touch_controls_list[i].value != NULL; i++)
7016     {
7017       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7018       char identifier[32], name[32];
7019       char *value = touch_controls_list[i].value;
7020       char *text = touch_controls_list[i].text;
7021
7022       ti->node_top = &touch_controls;
7023       ti->sort_priority = i;
7024
7025       sprintf(identifier, "%s", value);
7026       sprintf(name, "%s", text);
7027
7028       setString(&ti->identifier, identifier);
7029       setString(&ti->name, name);
7030       setString(&ti->name_sorting, name);
7031       setString(&ti->infotext, STR_SETUP_CHOOSE_TOUCH_CONTROL);
7032
7033       pushTreeInfo(&touch_controls, ti);
7034     }
7035
7036     // sort touch control values to start with lowest touch control value
7037     sortTreeInfo(&touch_controls);
7038
7039     // set current touch control value to configured touch control value
7040     touch_control_current =
7041       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
7042
7043     // if that fails, set current touch control to reliable default value
7044     if (touch_control_current == NULL)
7045       touch_control_current =
7046         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
7047
7048     // if that also fails, set current touch control to first available value
7049     if (touch_control_current == NULL)
7050       touch_control_current = touch_controls;
7051   }
7052
7053   if (move_distances == NULL)
7054   {
7055     for (i = 0; distances_list[i].value != -1; i++)
7056     {
7057       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7058       char identifier[32], name[32];
7059       int value = distances_list[i].value;
7060       char *text = distances_list[i].text;
7061
7062       ti->node_top = &move_distances;
7063       ti->sort_priority = value;
7064
7065       sprintf(identifier, "%d", value);
7066       sprintf(name, "%s", text);
7067
7068       setString(&ti->identifier, identifier);
7069       setString(&ti->name, name);
7070       setString(&ti->name_sorting, name);
7071       setString(&ti->infotext, STR_SETUP_CHOOSE_MOVE_DISTANCE);
7072
7073       pushTreeInfo(&move_distances, ti);
7074     }
7075
7076     // sort distance values to start with lowest distance value
7077     sortTreeInfo(&move_distances);
7078
7079     // set current distance value to configured distance value
7080     move_distance_current =
7081       getTreeInfoFromIdentifier(move_distances,
7082                                 i_to_a(setup.touch.move_distance));
7083
7084     // if that fails, set current distance to reliable default value
7085     if (move_distance_current == NULL)
7086       move_distance_current =
7087         getTreeInfoFromIdentifier(move_distances,
7088                                   i_to_a(TOUCH_MOVE_DISTANCE_DEFAULT));
7089
7090     // if that also fails, set current distance to first available value
7091     if (move_distance_current == NULL)
7092       move_distance_current = move_distances;
7093   }
7094
7095   if (drop_distances == NULL)
7096   {
7097     for (i = 0; distances_list[i].value != -1; i++)
7098     {
7099       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7100       char identifier[32], name[32];
7101       int value = distances_list[i].value;
7102       char *text = distances_list[i].text;
7103
7104       ti->node_top = &drop_distances;
7105       ti->sort_priority = value;
7106
7107       sprintf(identifier, "%d", value);
7108       sprintf(name, "%s", text);
7109
7110       setString(&ti->identifier, identifier);
7111       setString(&ti->name, name);
7112       setString(&ti->name_sorting, name);
7113       setString(&ti->infotext, STR_SETUP_CHOOSE_DROP_DISTANCE);
7114
7115       pushTreeInfo(&drop_distances, ti);
7116     }
7117
7118     // sort distance values to start with lowest distance value
7119     sortTreeInfo(&drop_distances);
7120
7121     // set current distance value to configured distance value
7122     drop_distance_current =
7123       getTreeInfoFromIdentifier(drop_distances,
7124                                 i_to_a(setup.touch.drop_distance));
7125
7126     // if that fails, set current distance to reliable default value
7127     if (drop_distance_current == NULL)
7128       drop_distance_current =
7129         getTreeInfoFromIdentifier(drop_distances,
7130                                   i_to_a(TOUCH_DROP_DISTANCE_DEFAULT));
7131
7132     // if that also fails, set current distance to first available value
7133     if (drop_distance_current == NULL)
7134       drop_distance_current = drop_distances;
7135   }
7136
7137   if (transparencies == NULL)
7138   {
7139     for (i = 0; transparencies_list[i].value != -1; i++)
7140     {
7141       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7142       char identifier[32], name[32];
7143       int value = transparencies_list[i].value;
7144       char *text = transparencies_list[i].text;
7145
7146       ti->node_top = &transparencies;
7147       ti->sort_priority = value;
7148
7149       sprintf(identifier, "%d", value);
7150       sprintf(name, "%s", text);
7151
7152       setString(&ti->identifier, identifier);
7153       setString(&ti->name, name);
7154       setString(&ti->name_sorting, name);
7155       setString(&ti->infotext, STR_SETUP_CHOOSE_TRANSPARENCY);
7156
7157       pushTreeInfo(&transparencies, ti);
7158     }
7159
7160     // sort transparency values to start with lowest transparency value
7161     sortTreeInfo(&transparencies);
7162
7163     // set current transparency value to configured transparency value
7164     transparency_current =
7165       getTreeInfoFromIdentifier(transparencies,
7166                                 i_to_a(setup.touch.transparency));
7167
7168     // if that fails, set current transparency to reliable default value
7169     if (transparency_current == NULL)
7170       transparency_current =
7171         getTreeInfoFromIdentifier(transparencies,
7172                                   i_to_a(TOUCH_TRANSPARENCY_DEFAULT));
7173
7174     // if that also fails, set current transparency to first available value
7175     if (transparency_current == NULL)
7176       transparency_current = transparencies;
7177   }
7178
7179   for (i = 0; i < 2; i++)
7180   {
7181     for (j = 0; j < 2; j++)
7182     {
7183       if (grid_sizes[i][j] == NULL)
7184       {
7185         for (k = 0; grid_sizes_list[k].value != -1; k++)
7186         {
7187           TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7188           char identifier[32], name[32];
7189           int value = grid_sizes_list[k].value;
7190           char *text = grid_sizes_list[k].text;
7191
7192           ti->node_top = &grid_sizes[i][j];
7193           ti->sort_priority = value;
7194
7195           sprintf(identifier, "%d", value);
7196           sprintf(name, "%s", text);
7197
7198           setString(&ti->identifier, identifier);
7199           setString(&ti->name, name);
7200           setString(&ti->name_sorting, name);
7201           setString(&ti->infotext,
7202                     (i == 0 ?
7203                      (j == 0 ?
7204                       STR_SETUP_CHOOSE_GRID_XSIZE_0 :
7205                       STR_SETUP_CHOOSE_GRID_YSIZE_0) :
7206                      (j == 0 ?
7207                       STR_SETUP_CHOOSE_GRID_XSIZE_1 :
7208                       STR_SETUP_CHOOSE_GRID_YSIZE_1)));
7209
7210           pushTreeInfo(&grid_sizes[i][j], ti);
7211         }
7212
7213         // sort grid size values to start with lowest grid size value
7214         sortTreeInfo(&grid_sizes[i][j]);
7215
7216         // set current grid size value to configured grid size value
7217         grid_size_current[i][j] =
7218           getTreeInfoFromIdentifier(grid_sizes[i][j],
7219                                     i_to_a(j == 0 ?
7220                                            setup.touch.grid_xsize[i] :
7221                                            setup.touch.grid_ysize[i]));
7222
7223         // if that fails, set current grid size to reliable default value
7224         if (grid_size_current[i][j] == NULL)
7225           grid_size_current[i][j] =
7226             getTreeInfoFromIdentifier(grid_sizes[i][j],
7227                                       i_to_a(j == 0 ?
7228                                              DEFAULT_GRID_XSIZE(i) :
7229                                              DEFAULT_GRID_YSIZE(i)));
7230
7231         // if that also fails, set current grid size to first available value
7232         if (grid_size_current[i][j] == NULL)
7233           grid_size_current[i][j] = grid_sizes[i][j];
7234       }
7235     }
7236   }
7237
7238   setup.touch.control_type = touch_control_current->identifier;
7239   setup.touch.move_distance = atoi(move_distance_current->identifier);
7240   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
7241   setup.touch.transparency = atoi(transparency_current->identifier);
7242
7243   for (i = 0; i < 2; i++)
7244   {
7245     setup.touch.grid_xsize[i] = atoi(grid_size_current[i][0]->identifier);
7246     setup.touch.grid_ysize[i] = atoi(grid_size_current[i][1]->identifier);
7247
7248     if (i == GRID_ACTIVE_NR())
7249     {
7250       overlay.grid_xsize = setup.touch.grid_xsize[i];
7251       overlay.grid_ysize = setup.touch.grid_ysize[i];
7252     }
7253   }
7254
7255   // needed for displaying value text instead of identifier
7256   touch_controls_text = touch_control_current->name;
7257   move_distance_text = move_distance_current->name;
7258   drop_distance_text = drop_distance_current->name;
7259   transparency_text = transparency_current->name;
7260
7261   for (i = 0; i < 2; i++)
7262     for (j = 0; j < 2; j++)
7263       grid_size_text[i][j] = grid_size_current[i][j]->name;
7264
7265   setup_mode = SETUP_MODE_TOUCH;
7266
7267   DrawSetupScreen();
7268 }
7269
7270 static void execSetupArtwork(void)
7271 {
7272   static ArtworkDirTree *gfx_last_valid = NULL;
7273   static ArtworkDirTree *snd_last_valid = NULL;
7274   static ArtworkDirTree *mus_last_valid = NULL;
7275
7276   // current artwork directory may be invalid (level group, parent link)
7277   if (!validLevelSeries(artwork.gfx_current))
7278     artwork.gfx_current = getFirstValidTreeInfoEntry(gfx_last_valid);
7279   if (!validLevelSeries(artwork.snd_current))
7280     artwork.snd_current = getFirstValidTreeInfoEntry(snd_last_valid);
7281   if (!validLevelSeries(artwork.mus_current))
7282     artwork.mus_current = getFirstValidTreeInfoEntry(mus_last_valid);
7283
7284   // store valid artwork directory information
7285   gfx_last_valid = artwork.gfx_current;
7286   snd_last_valid = artwork.snd_current;
7287   mus_last_valid = artwork.mus_current;
7288
7289 #if 0
7290   Debug("screens:execSetupArtwork", "'%s', '%s', '%s'",
7291         artwork.gfx_current->subdir,
7292         artwork.gfx_current->fullpath,
7293         artwork.gfx_current->basepath);
7294 #endif
7295
7296   setup.graphics_set = artwork.gfx_current->identifier;
7297   setup.sounds_set = artwork.snd_current->identifier;
7298   setup.music_set = artwork.mus_current->identifier;
7299
7300   // needed if last screen (setup choice) changed graphics, sounds or music
7301   ReloadCustomArtwork(0);
7302
7303   // needed for displaying artwork name instead of artwork identifier
7304   graphics_set_name = artwork.gfx_current->name;
7305   sounds_set_name = artwork.snd_current->name;
7306   music_set_name = artwork.mus_current->name;
7307
7308   setup_mode = SETUP_MODE_ARTWORK;
7309
7310   DrawSetupScreen();
7311 }
7312
7313 static void execSetupChooseGraphics(void)
7314 {
7315   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
7316
7317   DrawSetupScreen();
7318 }
7319
7320 static void execSetupChooseSounds(void)
7321 {
7322   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
7323
7324   DrawSetupScreen();
7325 }
7326
7327 static void execSetupChooseMusic(void)
7328 {
7329   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
7330
7331   DrawSetupScreen();
7332 }
7333
7334 static void execSetupInput(void)
7335 {
7336   setup_mode = SETUP_MODE_INPUT;
7337
7338   DrawSetupScreen();
7339 }
7340
7341 static void execSetupShortcuts(void)
7342 {
7343   setup_mode = SETUP_MODE_SHORTCUTS;
7344
7345   DrawSetupScreen();
7346 }
7347
7348 static void execSetupShortcuts1(void)
7349 {
7350   setup_mode = SETUP_MODE_SHORTCUTS_1;
7351
7352   DrawSetupScreen();
7353 }
7354
7355 static void execSetupShortcuts2(void)
7356 {
7357   setup_mode = SETUP_MODE_SHORTCUTS_2;
7358
7359   DrawSetupScreen();
7360 }
7361
7362 static void execSetupShortcuts3(void)
7363 {
7364   setup_mode = SETUP_MODE_SHORTCUTS_3;
7365
7366   DrawSetupScreen();
7367 }
7368
7369 static void execSetupShortcuts4(void)
7370 {
7371   setup_mode = SETUP_MODE_SHORTCUTS_4;
7372
7373   DrawSetupScreen();
7374 }
7375
7376 static void execSetupShortcuts5(void)
7377 {
7378   setup_mode = SETUP_MODE_SHORTCUTS_5;
7379
7380   DrawSetupScreen();
7381 }
7382
7383 static void execExitSetup(void)
7384 {
7385   SetGameStatus(GAME_MODE_MAIN);
7386
7387   DrawMainMenu();
7388 }
7389
7390 static void execSaveAndExitSetup(void)
7391 {
7392   SaveSetup();
7393   execExitSetup();
7394 }
7395
7396 static void execGadgetNetworkServer(void)
7397 {
7398   int gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
7399   struct GadgetInfo *gi = screen_gadget[gadget_id];
7400
7401   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
7402     network_server_hostname[0] = '\0';
7403
7404   ModifyGadget(gi, GDI_TEXT_VALUE, network_server_hostname, GDI_END);
7405
7406   MapGadget(gi);
7407
7408   ClickOnGadget(gi, MB_LEFTBUTTON);
7409 }
7410
7411 static void execOfferUploadTapes(void)
7412 {
7413   OfferUploadTapes();
7414 }
7415
7416 static void ToggleNetworkModeIfNeeded(void)
7417 {
7418   int font_title = FONT_TITLE_1;
7419   int font_foot = FC_BLUE;
7420   int ystart  = mSY - SY + 16;
7421   int ybottom = mSY - SY + SYSIZE - 20;
7422   char *text = (setup.network_mode ? "Start Network" : "Stop Network");
7423
7424   if (setup.network_mode == network.enabled)
7425     return;
7426
7427   network.enabled = setup.network_mode;
7428
7429   FadeOut(REDRAW_ALL);
7430
7431   ClearField();
7432
7433   DrawTextSCentered(ystart, font_title, text);
7434
7435   FadeIn(REDRAW_ALL);
7436
7437   if (network.enabled)
7438     InitNetworkServer();
7439   else
7440     DisconnectFromNetworkServer();
7441
7442   DrawTextSCentered(ybottom, font_foot,
7443                     "Press any key or button for setup menu");
7444
7445   WaitForEventToContinue();
7446
7447   DrawSetupScreen();
7448 }
7449
7450 static void ToggleGameSpeedsListIfNeeded(void)
7451 {
7452   boolean using_game_speeds_extended = (game_speeds == game_speeds_extended);
7453
7454   if (setup.game_speed_extended == using_game_speeds_extended)
7455     return;
7456
7457   // try to match similar values when changing game speeds list
7458   if (setup.game_speed_extended)
7459     setup.game_frame_delay = (setup.game_frame_delay == 15 ? 16 :
7460                               setup.game_frame_delay == 30 ? 29 :
7461                               setup.game_frame_delay);
7462   else
7463     setup.game_frame_delay = (setup.game_frame_delay == 14 ? 15 :
7464                               setup.game_frame_delay == 16 ? 15 :
7465                               setup.game_frame_delay >= 29 ? 30 :
7466                               setup.game_frame_delay <= 10 ? 10 :
7467                               setup.game_frame_delay);
7468
7469   execSetupGame_setGameSpeeds(TRUE);
7470
7471   DrawSetupScreen();
7472 }
7473
7474 static void ToggleUseApiServerIfNeeded(void)
7475 {
7476   if (runtime.use_api_server == setup.use_api_server)
7477     return;
7478
7479   runtime.use_api_server = setup.use_api_server;
7480
7481   if (runtime.use_api_server)
7482     CheckApiServerTasks();
7483 }
7484
7485 static void ModifyGameSpeedIfNeeded(void)
7486 {
7487   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7488       setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY)
7489     return;
7490
7491   char message[100];
7492   char *game_speed_text = "Fast";
7493   int game_speed_value = 15;
7494
7495   if (setup.game_speed_extended)
7496   {
7497     game_speed_text = "60 fps";
7498     game_speed_value = 16;
7499   }
7500
7501   sprintf(message, "Game speed set to %s for VSync to work!", game_speed_text);
7502
7503   // set game speed to existing list value that is fast enough for vsync
7504   setup.game_frame_delay = game_speed_value;
7505
7506   execSetupGame_setGameSpeeds(TRUE);
7507
7508   Request(message, REQ_CONFIRM);
7509 }
7510
7511 static void DisableVsyncIfNeeded(void)
7512 {
7513   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7514       (setup.game_frame_delay >= MIN_VSYNC_FRAME_DELAY &&
7515        setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY))
7516     return;
7517
7518   // disable vsync for the selected game speed to work
7519   setup.vsync_mode = STR_VSYNC_MODE_OFF;
7520
7521   execSetupGraphics_setVsyncModes(TRUE);
7522
7523   Request("VSync disabled for this game speed to work!", REQ_CONFIRM);
7524 }
7525
7526 static struct
7527 {
7528   void *value;
7529   void *related_value;
7530 } hide_related_entry_list[] =
7531 {
7532   { &setup.scores_in_highscore_list,    execSetupChooseScoresType       },
7533   { &setup.scores_in_highscore_list,    &scores_type_text               },
7534
7535   { &setup.game_frame_delay,            execSetupChooseGameSpeed        },
7536   { &setup.game_frame_delay,            &game_speed_text                },
7537
7538   { &setup.scroll_delay_value,          execSetupChooseScrollDelay      },
7539   { &setup.scroll_delay_value,          &scroll_delay_text              },
7540
7541   { &setup.engine_snapshot_mode,        execSetupChooseSnapshotMode     },
7542   { &setup.engine_snapshot_mode,        &snapshot_mode_text             },
7543
7544   { &setup.window_scaling_percent,      execSetupChooseWindowSize       },
7545   { &setup.window_scaling_percent,      &window_size_text               },
7546
7547   { &setup.window_scaling_quality,      execSetupChooseScalingType      },
7548   { &setup.window_scaling_quality,      &scaling_type_text              },
7549
7550   { &setup.screen_rendering_mode,       execSetupChooseRenderingMode    },
7551   { &setup.screen_rendering_mode,       &rendering_mode_text            },
7552
7553   { &setup.vsync_mode,                  execSetupChooseVsyncMode        },
7554   { &setup.vsync_mode,                  &vsync_mode_text                },
7555
7556   { &setup.graphics_set,                execSetupChooseGraphics         },
7557   { &setup.graphics_set,                &graphics_set_name              },
7558
7559   { &setup.sounds_set,                  execSetupChooseSounds           },
7560   { &setup.sounds_set,                  &sounds_set_name                },
7561
7562   { &setup.music_set,                   execSetupChooseMusic            },
7563   { &setup.music_set,                   &music_set_name                 },
7564
7565   { &setup.volume_simple,               execSetupChooseVolumeSimple     },
7566   { &setup.volume_simple,               &volume_simple_text             },
7567
7568   { &setup.volume_loops,                execSetupChooseVolumeLoops      },
7569   { &setup.volume_loops,                &volume_loops_text              },
7570
7571   { &setup.volume_music,                execSetupChooseVolumeMusic      },
7572   { &setup.volume_music,                &volume_music_text              },
7573
7574   { &setup.touch.control_type,          execSetupChooseTouchControls    },
7575   { &setup.touch.control_type,          &touch_controls_text            },
7576
7577   { &setup.touch.move_distance,         execSetupChooseMoveDistance     },
7578   { &setup.touch.move_distance,         &move_distance_text             },
7579
7580   { &setup.touch.drop_distance,         execSetupChooseDropDistance     },
7581   { &setup.touch.drop_distance,         &drop_distance_text             },
7582
7583   { &setup.touch.transparency,          execSetupChooseTransparency     },
7584   { &setup.touch.transparency,          &transparency_text              },
7585
7586   { &setup.touch.grid_xsize[0],         execSetupChooseGridXSize_0      },
7587   { &setup.touch.grid_xsize[0],         &grid_size_text[0][0]           },
7588
7589   { &setup.touch.grid_ysize[0],         execSetupChooseGridYSize_0      },
7590   { &setup.touch.grid_ysize[0],         &grid_size_text[0][1]           },
7591
7592   { &setup.touch.grid_xsize[1],         execSetupChooseGridXSize_1      },
7593   { &setup.touch.grid_xsize[1],         &grid_size_text[1][0]           },
7594
7595   { &setup.touch.grid_ysize[1],         execSetupChooseGridYSize_1      },
7596   { &setup.touch.grid_ysize[1],         &grid_size_text[1][1]           },
7597
7598   { &setup.internal.menu_game,          execSetupGame                   },
7599   { &setup.internal.menu_engines,       execSetupEngines                },
7600   { &setup.internal.menu_editor,        execSetupEditor                 },
7601   { &setup.internal.menu_graphics,      execSetupGraphics               },
7602   { &setup.internal.menu_sound,         execSetupSound                  },
7603   { &setup.internal.menu_artwork,       execSetupArtwork                },
7604   { &setup.internal.menu_input,         execSetupInput                  },
7605   { &setup.internal.menu_touch,         execSetupTouch                  },
7606   { &setup.internal.menu_shortcuts,     execSetupShortcuts              },
7607   { &setup.internal.menu_exit,          execExitSetup                   },
7608   { &setup.internal.menu_save_and_exit, execSaveAndExitSetup            },
7609
7610   { NULL,                               NULL                            }
7611 };
7612
7613 void setHideRelatedSetupEntries(void)
7614 {
7615   int i;
7616
7617   for (i = 0; hide_related_entry_list[i].value != NULL; i++)
7618     if (hideSetupEntry(hide_related_entry_list[i].value))
7619       setHideSetupEntry(hide_related_entry_list[i].related_value);
7620 }
7621
7622 static struct TokenInfo setup_info_main[] =
7623 {
7624   { TYPE_ENTER_MENU,    execSetupGame,          STR_SETUP_GAME          },
7625   { TYPE_ENTER_MENU,    execSetupEngines,       STR_SETUP_ENGINES       },
7626   { TYPE_ENTER_MENU,    execSetupEditor,        STR_SETUP_EDITOR        },
7627   { TYPE_ENTER_MENU,    execSetupGraphics,      STR_SETUP_GRAPHICS      },
7628   { TYPE_ENTER_MENU,    execSetupSound,         STR_SETUP_SOUND         },
7629   { TYPE_ENTER_MENU,    execSetupArtwork,       STR_SETUP_ARTWORK       },
7630   { TYPE_ENTER_MENU,    execSetupInput,         STR_SETUP_INPUT         },
7631   { TYPE_ENTER_MENU,    execSetupTouch,         STR_SETUP_TOUCH         },
7632   { TYPE_ENTER_MENU,    execSetupShortcuts,     STR_SETUP_SHORTCUTS     },
7633   { TYPE_EMPTY,         NULL,                   ""                      },
7634   { TYPE_LEAVE_MENU,    execExitSetup,          STR_SETUP_EXIT          },
7635   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   STR_SETUP_SAVE_AND_EXIT },
7636
7637   { 0,                  NULL,                   NULL                    }
7638 };
7639
7640 static struct TokenInfo setup_info_game[] =
7641 {
7642   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
7643   { TYPE_SWITCH,        &setup.network_mode,    "Network Multi-Player Mode:" },
7644   { TYPE_PLAYER,        &setup.network_player_nr,"Preferred Network Player:" },
7645   { TYPE_TEXT_INPUT,    execGadgetNetworkServer, "Network Server Hostname:" },
7646   { TYPE_STRING,        &network_server_text,   ""                      },
7647   { TYPE_SWITCH,        &setup.use_api_server,  "Use Highscore Server:" },
7648   { TYPE_ENTER_LIST,    execSetupChooseScoresType,"Scores in Highscore List:" },
7649   { TYPE_STRING,        &scores_type_text,      ""                      },
7650   { TYPE_ENTER_LIST,    execOfferUploadTapes,   "Upload Tapes to Server" },
7651   { TYPE_SWITCH,        &setup.multiple_users,  "Multiple Users/Teams:" },
7652   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
7653   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
7654   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
7655   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
7656   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
7657   { TYPE_SWITCH,        &setup.auto_play_next_level,"Auto-play Next Level:" },
7658   { TYPE_SWITCH,        &setup.count_score_after_game,"Count Score After Game:" },
7659   { TYPE_SWITCH,        &setup.show_scores_after_game,"Show Scores After Game:" },
7660   { TYPE_YES_NO,        &setup.ask_on_game_over, "Ask on Game Over:"    },
7661   { TYPE_YES_NO,        &setup.ask_on_quit_game, "Ask on Quit Game:"    },
7662   { TYPE_YES_NO,        &setup.ask_on_quit_program, "Ask on Quit Program:" },
7663   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
7664   { TYPE_SWITCH,        &setup.auto_pause_on_start, "Start Game in Pause Mode:" },
7665   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
7666   { TYPE_STRING,        &game_speed_text,       ""                      },
7667   { TYPE_SWITCH,        &setup.game_speed_extended, "Game Speed Extended List:" },
7668 #if 1
7669   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7670   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7671 #endif
7672   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
7673   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
7674   { TYPE_SWITCH,        &setup.show_load_save_buttons,"Show Load/Save Buttons:" },
7675   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,"Show Undo/Redo Buttons:" },
7676   { TYPE_EMPTY,         NULL,                   ""                      },
7677   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7678
7679   { 0,                  NULL,                   NULL                    }
7680 };
7681
7682 static struct TokenInfo setup_info_engines[] =
7683 {
7684   { TYPE_HEADLINE,      NULL,                   "Emerald Mine"          },
7685   { TYPE_SWITCH,        &setup.forced_scroll_delay, "Scroll Delay:"     },
7686   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics, "Amiga Graphics Chipset:" },
7687   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,"Low-Pass Filter Sounds:" },
7688   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:" },
7689   { TYPE_EMPTY,         NULL,                   ""                      },
7690   { TYPE_HEADLINE,      NULL,                   "Supaplex"              },
7691   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:" },
7692   { TYPE_EMPTY,         NULL,                   ""                      },
7693   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7694
7695   { 0,                  NULL,                   NULL                    }
7696 };
7697
7698 static struct TokenInfo setup_info_editor[] =
7699 {
7700 #if 0
7701   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
7702   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
7703   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
7704   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
7705   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
7706   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
7707   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
7708   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
7709   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
7710   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
7711 #endif
7712   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
7713   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
7714 #if 0
7715   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
7716 #endif
7717   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
7718   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
7719   { TYPE_EMPTY,         NULL,                   ""                      },
7720 #if 0
7721   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
7722   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
7723   { TYPE_EMPTY,         NULL,                   ""                      },
7724 #endif
7725   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
7726   { TYPE_EMPTY,         NULL,                   ""                      },
7727   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:" },
7728   { TYPE_EMPTY,         NULL,                   ""                      },
7729   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7730
7731   { 0,                  NULL,                   NULL                    }
7732 };
7733
7734 static struct TokenInfo setup_info_graphics[] =
7735 {
7736 #if !defined(PLATFORM_ANDROID)
7737   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
7738   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
7739   { TYPE_STRING,        &window_size_text,      ""                      },
7740   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
7741   { TYPE_STRING,        &scaling_type_text,     ""                      },
7742   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
7743   { TYPE_STRING,        &rendering_mode_text,   ""                      },
7744 #endif
7745 #if 0
7746   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7747   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7748 #endif
7749   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode, "Vertical Sync (VSync):" },
7750   { TYPE_STRING,        &vsync_mode_text,       ""                      },
7751   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
7752   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
7753   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
7754   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
7755   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
7756   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
7757   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,  debug_xsn_mode          },
7758   { TYPE_EMPTY,         NULL,                   ""                      },
7759   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7760
7761   { 0,                  NULL,                   NULL                    }
7762 };
7763
7764 static struct TokenInfo setup_info_sound[] =
7765 {
7766   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
7767   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
7768   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
7769   { TYPE_EMPTY,         NULL,                   ""                      },
7770   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
7771   { TYPE_STRING,        &volume_simple_text,    ""                      },
7772   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
7773   { TYPE_STRING,        &volume_loops_text,     ""                      },
7774   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
7775   { TYPE_STRING,        &volume_music_text,     ""                      },
7776   { TYPE_EMPTY,         NULL,                   ""                      },
7777   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7778
7779   { 0,                  NULL,                   NULL                    }
7780 };
7781
7782 static struct TokenInfo setup_info_artwork[] =
7783 {
7784   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
7785   { TYPE_STRING,        &graphics_set_name,     ""                      },
7786   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
7787   { TYPE_STRING,        &sounds_set_name,       ""                      },
7788   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
7789   { TYPE_STRING,        &music_set_name,        ""                      },
7790   { TYPE_EMPTY,         NULL,                   ""                      },
7791   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
7792   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
7793   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
7794   { TYPE_EMPTY,         NULL,                   ""                      },
7795   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7796
7797   { 0,                  NULL,                   NULL                    }
7798 };
7799
7800 static struct TokenInfo setup_info_input[] =
7801 {
7802   { TYPE_SWITCH,        NULL,                   "Player:"               },
7803   { TYPE_SWITCH,        NULL,                   "Device:"               },
7804   { TYPE_SWITCH,        NULL,                   ""                      },
7805   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7806   { TYPE_EMPTY,         NULL,                   ""                      },
7807   { TYPE_EMPTY,         NULL,                   ""                      },
7808   { TYPE_EMPTY,         NULL,                   ""                      },
7809   { TYPE_EMPTY,         NULL,                   ""                      },
7810   { TYPE_EMPTY,         NULL,                   ""                      },
7811   { TYPE_EMPTY,         NULL,                   ""                      },
7812   { TYPE_EMPTY,         NULL,                   ""                      },
7813   { TYPE_EMPTY,         NULL,                   ""                      },
7814   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7815   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7816
7817   { 0,                  NULL,                   NULL                    }
7818 };
7819
7820 static struct TokenInfo setup_info_touch[] =
7821 {
7822   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7823   { TYPE_STRING,        &touch_controls_text,   ""                      },
7824   { TYPE_EMPTY,         NULL,                   ""                      },
7825   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7826
7827   { 0,                  NULL,                   NULL                    }
7828 };
7829
7830 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
7831 {
7832   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7833   { TYPE_STRING,        &touch_controls_text,   ""                      },
7834   { TYPE_EMPTY,         NULL,                   ""                      },
7835   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0, "Horizontal Buttons (Landscape):"   },
7836   { TYPE_STRING,        &grid_size_text[0][0],  ""                      },
7837   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0, "Vertical Buttons (Landscape):"     },
7838   { TYPE_STRING,        &grid_size_text[0][1],  ""                      },
7839   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7840   { TYPE_STRING,        &transparency_text,     ""                      },
7841   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7842   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7843   { TYPE_EMPTY,         NULL,                   ""                      },
7844   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7845   { TYPE_EMPTY,         NULL,                   ""                      },
7846   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7847
7848   { 0,                  NULL,                   NULL                    }
7849 };
7850
7851 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
7852 {
7853   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7854   { TYPE_STRING,        &touch_controls_text,   ""                      },
7855   { TYPE_EMPTY,         NULL,                   ""                      },
7856   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1, "Horizontal Buttons (Portrait):"    },
7857   { TYPE_STRING,        &grid_size_text[1][0],  ""                      },
7858   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1, "Vertical Buttons (Portrait):"      },
7859   { TYPE_STRING,        &grid_size_text[1][1],  ""                      },
7860   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7861   { TYPE_STRING,        &transparency_text,     ""                      },
7862   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7863   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7864   { TYPE_EMPTY,         NULL,                   ""                      },
7865   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7866   { TYPE_EMPTY,         NULL,                   ""                      },
7867   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7868
7869   { 0,                  NULL,                   NULL                    }
7870 };
7871
7872 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
7873 {
7874   setup_info_touch_virtual_buttons_0,
7875   setup_info_touch_virtual_buttons_1
7876 };
7877
7878 static struct TokenInfo setup_info_touch_wipe_gestures[] =
7879 {
7880   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7881   { TYPE_STRING,        &touch_controls_text,   ""                      },
7882   { TYPE_EMPTY,         NULL,                   ""                      },
7883   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
7884   { TYPE_STRING,        &move_distance_text,    ""                      },
7885   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
7886   { TYPE_STRING,        &drop_distance_text,    ""                      },
7887   { TYPE_EMPTY,         NULL,                   ""                      },
7888   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7889
7890   { 0,                  NULL,                   NULL                    }
7891 };
7892
7893 static struct TokenInfo setup_info_shortcuts[] =
7894 {
7895   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
7896   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
7897   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
7898   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
7899   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
7900   { TYPE_EMPTY,         NULL,                   ""                      },
7901   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7902
7903   { 0,                  NULL,                   NULL                    }
7904 };
7905
7906 static struct TokenInfo setup_info_shortcuts_1[] =
7907 {
7908   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
7909   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
7910   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
7911   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
7912   { TYPE_KEYTEXT,       NULL,           "Restart Game:",                },
7913   { TYPE_KEY,           &setup.shortcut.restart_game, ""                },
7914   { TYPE_KEYTEXT,       NULL,           "Replay & Pause Before End:",   },
7915   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""            },
7916   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
7917   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
7918   { TYPE_EMPTY,         NULL,                   ""                      },
7919   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
7920   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
7921   { TYPE_EMPTY,         NULL,                   ""                      },
7922   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7923
7924   { 0,                  NULL,                   NULL                    }
7925 };
7926
7927 static struct TokenInfo setup_info_shortcuts_2[] =
7928 {
7929   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
7930   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
7931   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
7932   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
7933   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
7934   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
7935   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
7936   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
7937   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
7938   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
7939   { TYPE_EMPTY,         NULL,                   ""                      },
7940   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7941
7942   { 0,                  NULL,                   NULL                    }
7943 };
7944
7945 static struct TokenInfo setup_info_shortcuts_3[] =
7946 {
7947   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
7948   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
7949   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
7950   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
7951   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
7952   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
7953   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
7954   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
7955   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
7956   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
7957   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
7958   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
7959   { TYPE_EMPTY,         NULL,                   ""                      },
7960   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7961
7962   { 0,                  NULL,                   NULL                    }
7963 };
7964
7965 static struct TokenInfo setup_info_shortcuts_4[] =
7966 {
7967   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
7968   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
7969   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
7970   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
7971   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
7972   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
7973   { TYPE_EMPTY,         NULL,                   ""                      },
7974   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7975
7976   { 0,                  NULL,                   NULL                    }
7977 };
7978
7979 static struct TokenInfo setup_info_shortcuts_5[] =
7980 {
7981   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
7982   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
7983   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
7984   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
7985   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
7986   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
7987   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
7988   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
7989   { TYPE_EMPTY,         NULL,                   ""                      },
7990   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7991
7992   { 0,                  NULL,                   NULL                    }
7993 };
7994
7995 static Key getSetupKey(void)
7996 {
7997   Key key = KSYM_UNDEFINED;
7998   boolean got_key_event = FALSE;
7999
8000   while (!got_key_event)
8001   {
8002     Event event;
8003
8004     if (NextValidEvent(&event))
8005     {
8006       switch (event.type)
8007       {
8008         case EVENT_KEYPRESS:
8009           {
8010             key = GetEventKey((KeyEvent *)&event, TRUE);
8011
8012             // press 'Escape' or 'Enter' to keep the existing key binding
8013             if (key == KSYM_Escape || key == KSYM_Return)
8014               key = KSYM_UNDEFINED;     // keep old value
8015
8016             got_key_event = TRUE;
8017           }
8018           break;
8019
8020         case EVENT_KEYRELEASE:
8021           key_joystick_mapping = 0;
8022           break;
8023
8024         default:
8025           HandleOtherEvents(&event);
8026           break;
8027       }
8028     }
8029
8030     BackToFront();
8031   }
8032
8033   return key;
8034 }
8035
8036 static int getSetupValueFont(int type, void *value)
8037 {
8038   if (type & TYPE_GHOSTED)
8039     return FONT_OPTION_OFF;
8040   else if (type & TYPE_KEY)
8041     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
8042   else if (type & TYPE_STRING)
8043     return FONT_VALUE_2;
8044   else if (type & TYPE_ECS_AGA)
8045     return FONT_VALUE_1;
8046   else if (type & TYPE_BOOLEAN_STYLE)
8047     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
8048   else if (type & TYPE_YES_NO_AUTO)
8049     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
8050             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
8051   else if (type & TYPE_PLAYER)
8052     return FONT_VALUE_1;
8053   else
8054     return FONT_VALUE_1;
8055 }
8056
8057 static int getSetupValueFontNarrow(int type, int font_nr)
8058 {
8059   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
8060           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
8061           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
8062           font_nr);
8063 }
8064
8065 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
8066 {
8067   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
8068   struct TokenInfo *si = &setup_info[si_pos];
8069   boolean font_draw_xoffset_modified = FALSE;
8070   boolean scrollbar_needed = (num_setup_info < max_setup_info);
8071   int font_draw_xoffset_old = -1;
8072   int xoffset = (scrollbar_needed ? -1 : 0);
8073   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
8074   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
8075   int xpos = menu_screen_value_xpos;
8076   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
8077   int startx = mSX + xpos * 32;
8078   int starty = mSY + ypos * 32;
8079   int type = si->type;
8080   void *value = si->value;
8081   char *value_string = getSetupValue(type, value);
8082   int font_nr_default = getSetupValueFont(type, value);
8083   int font_width_default = getFontWidth(font_nr_default);
8084   int font_nr = font_nr_default;
8085   int i;
8086
8087   if (value_string == NULL)
8088     return;
8089
8090   if (type & TYPE_KEY)
8091   {
8092     xpos = MENU_SCREEN_START_XPOS;
8093
8094     if (type & TYPE_QUERY)
8095       value_string = "<press key>";
8096   }
8097   else if (type & TYPE_STRING)
8098   {
8099     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
8100
8101     xpos = MENU_SCREEN_START_XPOS;
8102
8103     if (strlen(value_string) > max_value_len)
8104       value_string[max_value_len] = '\0';
8105   }
8106   else if (type & TYPE_YES_NO_AUTO)
8107   {
8108     xpos = menu_screen_value_xpos - 1;
8109   }
8110   else if (type & TYPE_PLAYER)
8111   {
8112     int displayed_player_nr = *(int *)value + 1;
8113
8114     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
8115   }
8116
8117   startx = mSX + xpos * 32;
8118   starty = mSY + ypos * 32;
8119
8120   // special check if right-side setup values moved left due to scrollbar
8121   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
8122   {
8123     int max_menu_text_length = 26;      // maximum text length for classic menu
8124     int font_xoffset = getFontDrawOffsetX(font_nr);
8125     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8126     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8127     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8128     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
8129
8130     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
8131     {
8132       // when using narrow font, left-shifting text "auto" not needed
8133       if (type & TYPE_YES_NO_AUTO)
8134         xpos += 1;
8135
8136       xpos += 1;
8137       startx = mSX + xpos * 32;
8138
8139       font_nr = getSetupValueFontNarrow(type, font_nr);
8140     }
8141   }
8142
8143   // downward compatibility correction for Juergen Bonhagen's menu settings
8144   if (setup_mode != SETUP_MODE_INPUT)
8145   {
8146     int max_menu_text_length_big = (menu_screen_value_xpos -
8147                                     MENU_SCREEN_START_XPOS);
8148     int max_menu_text_length_medium = max_menu_text_length_big * 2;
8149     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
8150     int font1_xoffset = getFontDrawOffsetX(font_nr);
8151     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
8152     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8153     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8154     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8155     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
8156     boolean correct_font_draw_xoffset = FALSE;
8157
8158     if (xpos == MENU_SCREEN_START_XPOS &&
8159         startx + font1_xoffset < text_startx + text_font_xoffset)
8160       correct_font_draw_xoffset = TRUE;
8161
8162     if (xpos == menu_screen_value_xpos &&
8163         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
8164       correct_font_draw_xoffset = TRUE;
8165
8166     // check if setup value would overlap with setup text when printed
8167     // (this can happen for extreme/wrong values for font draw offset)
8168     if (correct_font_draw_xoffset)
8169     {
8170       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
8171       font_draw_xoffset_modified = TRUE;
8172
8173       if (type & TYPE_KEY)
8174         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
8175       else if (!(type & TYPE_STRING))
8176         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
8177           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
8178     }
8179   }
8180
8181   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
8182     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
8183
8184   DrawText(startx, starty, value_string, font_nr);
8185
8186   if (type & TYPE_PLAYER)
8187   {
8188     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
8189     int player_nr = *(int *)value;
8190     int xoff = font->draw_xoffset + getFontWidth(font_nr);
8191     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
8192     int startx2 = startx + xoff;
8193     int starty2 = starty + yoff;
8194
8195     if (DrawingOnBackground(startx2, starty2))
8196       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
8197
8198     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
8199                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8200   }
8201
8202   if (font_draw_xoffset_modified)
8203     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
8204 }
8205
8206 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
8207 {
8208   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
8209   struct TokenInfo *si = &setup_info[si_pos];
8210
8211   if (si->type & TYPE_BOOLEAN_STYLE)
8212   {
8213     *(boolean *)si->value ^= TRUE;
8214   }
8215   else if (si->type & TYPE_YES_NO_AUTO)
8216   {
8217     *(int *)si->value =
8218       (dx == -1 ?
8219        (*(int *)si->value == AUTO ? TRUE :
8220         *(int *)si->value == TRUE ? FALSE : AUTO) :
8221        (*(int *)si->value == TRUE ? AUTO :
8222         *(int *)si->value == AUTO ? FALSE : TRUE));
8223   }
8224   else if (si->type & TYPE_KEY)
8225   {
8226     Key key;
8227
8228     si->type |= TYPE_QUERY;
8229     drawSetupValue(screen_pos, setup_info_pos_raw);
8230     si->type &= ~TYPE_QUERY;
8231
8232     key = getSetupKey();
8233     if (key != KSYM_UNDEFINED)
8234       *(Key *)si->value = key;
8235   }
8236   else if (si->type & TYPE_PLAYER)
8237   {
8238     int player_nr = *(int *)si->value;
8239
8240     if (dx)
8241       player_nr += dx;
8242     else
8243       player_nr = Request("Choose player", REQ_PLAYER) - 1;
8244
8245     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
8246   }
8247
8248   drawSetupValue(screen_pos, setup_info_pos_raw);
8249
8250   // fullscreen state may have changed at this point
8251   if (si->value == &setup.fullscreen)
8252     ToggleFullscreenIfNeeded();
8253
8254   // network mode may have changed at this point
8255   if (si->value == &setup.network_mode)
8256     ToggleNetworkModeIfNeeded();
8257
8258   // API server mode may have changed at this point
8259   if (si->value == &setup.use_api_server)
8260     ToggleUseApiServerIfNeeded();
8261
8262   // game speed list may have changed at this point
8263   if (si->value == &setup.game_speed_extended)
8264     ToggleGameSpeedsListIfNeeded();
8265 }
8266
8267 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
8268 {
8269   static struct TokenInfo *setup_info_final = NULL;
8270   int list_size = 0;
8271   int list_pos = 0;
8272   int i;
8273
8274   // determine maximum list size of target list
8275   while (setup_info_orig[list_size++].type != 0);
8276
8277   // free, allocate and clear memory for target list
8278   checked_free(setup_info_final);
8279   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
8280
8281   // copy setup info list without setup entries marked as hidden
8282   for (i = 0; setup_info_orig[i].type != 0; i++)
8283   {
8284     // skip setup entries configured to be hidden
8285     if (hideSetupEntry(setup_info_orig[i].value))
8286       continue;
8287
8288     // skip skippable setup entries if screen is lower than usual
8289     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
8290         setup_info_orig[i].type == TYPE_SKIPPABLE)
8291       continue;
8292
8293     setup_info_final[list_pos++] = setup_info_orig[i];
8294   }
8295
8296   return setup_info_final;
8297 }
8298
8299 static void DrawSetupScreen_Generic(void)
8300 {
8301   int fade_mask = REDRAW_FIELD;
8302   boolean redraw_all = FALSE;
8303   char *title_string = NULL;
8304   int i;
8305
8306   if (CheckFadeAll())
8307     fade_mask = REDRAW_ALL;
8308
8309   UnmapAllGadgets();
8310   FadeMenuSoundsAndMusic();
8311
8312   FreeScreenGadgets();
8313   CreateScreenGadgets();
8314
8315   if (redraw_mask & REDRAW_ALL)
8316     redraw_all = TRUE;
8317
8318   FadeOut(fade_mask);
8319
8320   // needed if different viewport properties defined for setup screen
8321   ChangeViewportPropertiesIfNeeded();
8322
8323   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
8324
8325   ClearField();
8326
8327   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
8328
8329   if (setup_mode == SETUP_MODE_MAIN)
8330   {
8331     setup_info = setup_info_main;
8332     title_string = STR_SETUP_MAIN;
8333   }
8334   else if (setup_mode == SETUP_MODE_GAME)
8335   {
8336     setup_info = setup_info_game;
8337     title_string = STR_SETUP_GAME;
8338   }
8339   else if (setup_mode == SETUP_MODE_ENGINES)
8340   {
8341     setup_info = setup_info_engines;
8342     title_string = STR_SETUP_ENGINES;
8343   }
8344   else if (setup_mode == SETUP_MODE_EDITOR)
8345   {
8346     setup_info = setup_info_editor;
8347     title_string = STR_SETUP_EDITOR;
8348   }
8349   else if (setup_mode == SETUP_MODE_GRAPHICS)
8350   {
8351     setup_info = setup_info_graphics;
8352     title_string = STR_SETUP_GRAPHICS;
8353   }
8354   else if (setup_mode == SETUP_MODE_SOUND)
8355   {
8356     setup_info = setup_info_sound;
8357     title_string = STR_SETUP_SOUND;
8358   }
8359   else if (setup_mode == SETUP_MODE_ARTWORK)
8360   {
8361     setup_info = setup_info_artwork;
8362     title_string = STR_SETUP_ARTWORK;
8363   }
8364   else if (setup_mode == SETUP_MODE_TOUCH)
8365   {
8366     setup_info = setup_info_touch;
8367     title_string = STR_SETUP_TOUCH;
8368
8369     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
8370       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
8371     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
8372       setup_info = setup_info_touch_wipe_gestures;
8373   }
8374   else if (setup_mode == SETUP_MODE_SHORTCUTS)
8375   {
8376     setup_info = setup_info_shortcuts;
8377     title_string = STR_SETUP_SHORTCUTS;
8378   }
8379   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
8380   {
8381     setup_info = setup_info_shortcuts_1;
8382     title_string = STR_SETUP_SHORTCUTS;
8383   }
8384   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
8385   {
8386     setup_info = setup_info_shortcuts_2;
8387     title_string = STR_SETUP_SHORTCUTS;
8388   }
8389   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
8390   {
8391     setup_info = setup_info_shortcuts_3;
8392     title_string = STR_SETUP_SHORTCUTS;
8393   }
8394   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
8395   {
8396     setup_info = setup_info_shortcuts_4;
8397     title_string = STR_SETUP_SHORTCUTS;
8398   }
8399   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
8400   {
8401     setup_info = setup_info_shortcuts_5;
8402     title_string = STR_SETUP_SHORTCUTS;
8403   }
8404
8405   // use modified setup info without setup entries marked as hidden
8406   setup_info = getSetupInfoFinal(setup_info);
8407
8408   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
8409
8410   // determine maximal number of setup entries that can be displayed on screen
8411   num_setup_info = 0;
8412   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
8413     num_setup_info++;
8414
8415   // determine maximal number of setup entries available for this setup screen
8416   max_setup_info = 0;
8417   for (i = 0; setup_info[i].type != 0; i++)
8418     max_setup_info++;
8419
8420   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
8421
8422   MapScreenGadgets(max_setup_info);
8423
8424   if (redraw_all)
8425     redraw_mask = fade_mask = REDRAW_ALL;
8426
8427   DrawMaskedBorder(fade_mask);
8428
8429   FadeIn(fade_mask);
8430 }
8431
8432 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
8433 {
8434   menu_info = setup_info;
8435
8436   HandleMenuScreen(mx, my, dx, dy, button,
8437                    setup_mode, num_setup_info, max_setup_info);
8438 }
8439
8440 static void DrawSetupScreen_Input(void)
8441 {
8442   int i;
8443
8444   FadeOut(REDRAW_FIELD);
8445
8446   ClearField();
8447
8448   setup_info = getSetupInfoFinal(setup_info_input);
8449
8450   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
8451
8452   for (i = 0; setup_info[i].type != 0; i++)
8453   {
8454     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
8455       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
8456     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
8457       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
8458     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
8459       initCursor(i, IMG_MENU_BUTTON);
8460
8461     DrawCursorAndText_Setup(i, -1, FALSE);
8462   }
8463
8464   // create gadgets for setup input menu screen
8465   FreeScreenGadgets();
8466   CreateScreenGadgets();
8467
8468   // map gadgets for setup input menu screen
8469   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
8470
8471   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
8472
8473   FadeIn(REDRAW_FIELD);
8474 }
8475
8476 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8477 {
8478   if (device_name == NULL)
8479     return;
8480
8481   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8482     device_nr = 0;
8483
8484   if (strlen(device_name) > 1)
8485   {
8486     char c1 = device_name[strlen(device_name) - 1];
8487     char c2 = device_name[strlen(device_name) - 2];
8488
8489     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8490       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8491   }
8492   else
8493     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8494             strlen(device_name));
8495 }
8496
8497 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8498 {
8499   int i;
8500   static struct SetupKeyboardInfo custom_key;
8501   static struct
8502   {
8503     Key *key;
8504     char *text;
8505   } custom[] =
8506   {
8507     { &custom_key.left,  "Axis/Pad Left"  },
8508     { &custom_key.right, "Axis/Pad Right" },
8509     { &custom_key.up,    "Axis/Pad Up"    },
8510     { &custom_key.down,  "Axis/Pad Down"  },
8511     { &custom_key.snap,  "Button 1/A/X"   },
8512     { &custom_key.drop,  "Button 2/B/Y"   }
8513   };
8514   static char *joystick_name[MAX_PLAYERS] =
8515   {
8516     "Joystick1",
8517     "Joystick2",
8518     "Joystick3",
8519     "Joystick4"
8520   };
8521   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8522   int font_nr_info = FONT_MENU_1;
8523   int font_nr_name = FONT_VALUE_OLD;
8524   int font_nr_on   = FONT_VALUE_1;
8525   int font_nr_off  = FONT_VALUE_OLD;
8526   int pos = 4;
8527
8528   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8529   {
8530     font_nr_info = FONT_MENU_2;
8531     font_nr_on   = FONT_VALUE_NARROW;
8532     font_nr_off  = FONT_VALUE_OLD_NARROW;
8533   }
8534
8535   custom_key = setup.input[player_nr].key;
8536
8537   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8538            FONT_INPUT_1_ACTIVE);
8539
8540   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8541                              TILEX, TILEY);
8542   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8543                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8544
8545   if (setup.input[player_nr].use_joystick)
8546   {
8547     char *device_name = setup.input[player_nr].joy.device_name;
8548     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8549     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8550     char *text = joystick_name[joystick_nr];
8551     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8552
8553     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8554     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8555   }
8556   else
8557   {
8558     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8559     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8560   }
8561
8562   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8563     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8564   else
8565     pos = 3;
8566
8567   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8568   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8569   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8570   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8571
8572   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8573   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8574   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8575   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8576   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8577   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8578
8579   for (i = 0; i < 6; i++)
8580   {
8581     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8582
8583     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8584              "              ", font_nr_on);
8585     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8586              (setup.input[player_nr].use_joystick ?
8587               custom[i].text :
8588               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8589   }
8590 }
8591
8592 static int input_player_nr = 0;
8593
8594 static void HandleSetupScreen_Input_Player(int step, int direction)
8595 {
8596   int old_player_nr = input_player_nr;
8597   int new_player_nr;
8598
8599   new_player_nr = old_player_nr + step * direction;
8600   if (new_player_nr < 0)
8601     new_player_nr = 0;
8602   if (new_player_nr > MAX_PLAYERS - 1)
8603     new_player_nr = MAX_PLAYERS - 1;
8604
8605   if (new_player_nr != old_player_nr)
8606   {
8607     input_player_nr = new_player_nr;
8608
8609     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8610   }
8611 }
8612
8613 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8614 {
8615   static int choice = 0;
8616   int x = 0;
8617   int y = choice;
8618   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8619   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8620   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8621   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8622
8623   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8624   {
8625     int i;
8626
8627     for (i = 0; setup_info_input[i].type != 0; i++)
8628     {
8629       // adjust menu structure according to skipped setup entries
8630       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8631       {
8632         pos_empty2--;
8633         pos_end--;
8634       }
8635     }
8636   }
8637
8638   if (button == MB_MENU_INITIALIZE)
8639   {
8640     // input setup menu may have changed size due to graphics configuration
8641     if (choice >= pos_empty1)
8642       choice = pos_end;
8643
8644     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8645
8646     DrawCursorAndText_Setup(choice, -1, TRUE);
8647
8648     return;
8649   }
8650   else if (button == MB_MENU_LEAVE)
8651   {
8652     setup_mode = SETUP_MODE_MAIN;
8653     DrawSetupScreen();
8654     InitJoysticks();
8655
8656     return;
8657   }
8658
8659   if (mx || my)         // mouse input
8660   {
8661     x = (mx - mSX) / 32;
8662     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8663   }
8664   else if (dx || dy)    // keyboard input
8665   {
8666     if (dx && choice == 0)
8667       x = (dx < 0 ? 10 : 12);
8668     else if ((dx && choice == 1) ||
8669              (dx == -1 && choice == pos_end))
8670       button = MB_MENU_CHOICE;
8671     else if (dy)
8672       y = choice + dy;
8673
8674     if (y >= pos_empty1 && y <= pos_empty2)
8675       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
8676   }
8677
8678   if (y == 0 && dx != 0 && button)
8679   {
8680     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
8681   }
8682   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
8683            y >= pos_start && y <= pos_end &&
8684            !(y >= pos_empty1 && y <= pos_empty2))
8685   {
8686     if (button)
8687     {
8688       if (y != choice)
8689       {
8690         DrawCursorAndText_Setup(choice, -1, FALSE);
8691         DrawCursorAndText_Setup(y, -1, TRUE);
8692
8693         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
8694
8695         choice = y;
8696       }
8697     }
8698     else
8699     {
8700       if (y == 1)
8701       {
8702         char *device_name = setup.input[input_player_nr].joy.device_name;
8703
8704         if (!setup.input[input_player_nr].use_joystick)
8705         {
8706           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
8707
8708           setJoystickDeviceToNr(device_name, new_device_nr);
8709           setup.input[input_player_nr].use_joystick = TRUE;
8710         }
8711         else
8712         {
8713           int device_nr = getJoystickNrFromDeviceName(device_name);
8714           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
8715
8716           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
8717             setup.input[input_player_nr].use_joystick = FALSE;
8718           else
8719             setJoystickDeviceToNr(device_name, new_device_nr);
8720         }
8721
8722         drawPlayerSetupInputInfo(input_player_nr, FALSE);
8723       }
8724       else if (y == 2)
8725       {
8726         if (setup.input[input_player_nr].use_joystick)
8727           ConfigureJoystick(input_player_nr);
8728         else
8729           CustomizeKeyboard(input_player_nr);
8730       }
8731       else if (y == pos_end)
8732       {
8733         InitJoysticks();
8734
8735         FadeSetLeaveMenu();
8736
8737         setup_mode = SETUP_MODE_MAIN;
8738         DrawSetupScreen();
8739       }
8740     }
8741   }
8742 }
8743
8744 static boolean CustomizeKeyboardMain(int player_nr)
8745 {
8746   int i;
8747   int step_nr;
8748   boolean finished = FALSE;
8749   static struct SetupKeyboardInfo custom_key;
8750   static struct
8751   {
8752     Key *key;
8753     char *text;
8754   } customize_step[] =
8755   {
8756     { &custom_key.left,  "Move Left"    },
8757     { &custom_key.right, "Move Right"   },
8758     { &custom_key.up,    "Move Up"      },
8759     { &custom_key.down,  "Move Down"    },
8760     { &custom_key.snap,  "Snap Field"   },
8761     { &custom_key.drop,  "Drop Element" }
8762   };
8763   int font_nr_old = FONT_VALUE_OLD;
8764   int font_nr_new = FONT_VALUE_1;
8765   boolean success = FALSE;
8766
8767   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8768   {
8769     font_nr_old = FONT_VALUE_OLD_NARROW;
8770     font_nr_new = FONT_VALUE_NARROW;
8771   }
8772
8773   // read existing key bindings from player setup
8774   custom_key = setup.input[player_nr].key;
8775
8776   FadeSetEnterMenu();
8777   FadeOut(REDRAW_FIELD);
8778
8779   ClearField();
8780
8781   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
8782
8783   step_nr = 0;
8784   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8785            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8786   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8787            "Key:", FONT_INPUT_1_ACTIVE);
8788   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8789            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
8790
8791   FadeIn(REDRAW_FIELD);
8792
8793   while (!finished)
8794   {
8795     Event event;
8796
8797     if (NextValidEvent(&event))
8798     {
8799       switch (event.type)
8800       {
8801         case EVENT_KEYPRESS:
8802           {
8803             Key key = GetEventKey((KeyEvent *)&event, FALSE);
8804
8805             // press 'Escape' to abort and keep the old key bindings
8806             if (key == KSYM_Escape)
8807             {
8808               FadeSkipNextFadeIn();
8809
8810               finished = TRUE;
8811
8812               break;
8813             }
8814
8815             // press 'Enter' to keep the existing key binding
8816             if (key == KSYM_Return)
8817               key = *customize_step[step_nr].key;
8818
8819             // check if key already used
8820             for (i = 0; i < step_nr; i++)
8821               if (*customize_step[i].key == key)
8822                 break;
8823             if (i < step_nr)
8824               break;
8825
8826             // got new key binding
8827             *customize_step[step_nr].key = key;
8828             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8829                      "             ", font_nr_new);
8830             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8831                      getKeyNameFromKey(key), font_nr_new);
8832             step_nr++;
8833
8834             // un-highlight last query
8835             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
8836                      customize_step[step_nr - 1].text, FONT_MENU_1);
8837             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
8838                      "Key:", FONT_MENU_1);
8839
8840             // all keys configured
8841             if (step_nr == 6)
8842             {
8843               finished = TRUE;
8844               success = TRUE;
8845
8846               break;
8847             }
8848
8849             // query next key binding
8850             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8851                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8852             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8853                      "Key:", FONT_INPUT_1_ACTIVE);
8854             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8855                      getKeyNameFromKey(*customize_step[step_nr].key),
8856                      font_nr_old);
8857           }
8858           break;
8859
8860         case EVENT_KEYRELEASE:
8861           key_joystick_mapping = 0;
8862           break;
8863
8864         default:
8865           HandleOtherEvents(&event);
8866           break;
8867       }
8868     }
8869
8870     BackToFront();
8871   }
8872
8873   // write new key bindings back to player setup, if successfully finished
8874   if (success)
8875     setup.input[player_nr].key = custom_key;
8876
8877   return success;
8878 }
8879
8880 void CustomizeKeyboard(int player_nr)
8881 {
8882   boolean success = CustomizeKeyboardMain(player_nr);
8883
8884   if (success)
8885   {
8886     int font_nr = FONT_TITLE_1;
8887     int font_height = getFontHeight(font_nr);
8888     int ypos1 = SYSIZE / 2 - font_height * 2;
8889     int ypos2 = SYSIZE / 2 - font_height * 1;
8890     unsigned int wait_frame_delay = 0;
8891     unsigned int wait_frame_delay_value = 2000;
8892
8893     ResetDelayCounter(&wait_frame_delay);
8894
8895     ClearField();
8896
8897     DrawTextSCentered(ypos1, font_nr, "Keyboard");
8898     DrawTextSCentered(ypos2, font_nr, "configured!");
8899
8900     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8901       BackToFront();
8902
8903     ClearEventQueue();
8904   }
8905
8906   DrawSetupScreen_Input();
8907 }
8908
8909 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
8910
8911 #define MARKER_BUTTON           1
8912 #define MARKER_AXIS_X           2
8913 #define MARKER_AXIS_Y           3
8914
8915 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
8916 {
8917   static boolean bitmaps_initialized = FALSE;
8918   boolean screen_initialized = FALSE;
8919   static Bitmap *controller, *button, *axis_x, *axis_y;
8920   char *name;
8921   boolean success = TRUE;
8922   boolean done = FALSE, next = FALSE;
8923   Event event;
8924   int alpha = 200, alpha_step = -1;
8925   int alpha_ticks = 0;
8926   char mapping[4096], temp[256];
8927   int font_name = MENU_SETUP_FONT_TITLE;
8928   int font_info = MENU_SETUP_FONT_TEXT;
8929   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
8930   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
8931   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
8932   int ystep_name = getMenuTextStep(spacing_name, font_name);
8933   int ystep_line = getMenuTextStep(spacing_line, font_info);
8934   int ystep_para = getMenuTextStep(spacing_para, font_info);
8935   int i, j;
8936
8937   struct
8938   {
8939     int x, y;
8940     int marker;
8941     char *field;
8942     int axis, button, hat, hat_value;
8943     char mapping[4096];
8944   }
8945   *step, *prev_step, steps[] =
8946   {
8947     { 356, 155, MARKER_BUTTON, "a",             },
8948     { 396, 122, MARKER_BUTTON, "b",             },
8949     { 320, 125, MARKER_BUTTON, "x",             },
8950     { 358,  95, MARKER_BUTTON, "y",             },
8951     { 162, 125, MARKER_BUTTON, "back",          },
8952     { 216, 125, MARKER_BUTTON, "guide",         },
8953     { 271, 125, MARKER_BUTTON, "start",         },
8954     { 110, 200, MARKER_BUTTON, "dpleft",        },
8955     { 146, 228, MARKER_BUTTON, "dpdown",        },
8956     { 178, 200, MARKER_BUTTON, "dpright",       },
8957     { 146, 172, MARKER_BUTTON, "dpup",          },
8958     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
8959     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
8960     { 382,  40, MARKER_BUTTON, "rightshoulder", },
8961     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
8962     {  73, 141, MARKER_BUTTON, "leftstick",     },
8963     { 282, 210, MARKER_BUTTON, "rightstick",    },
8964     {  73, 141, MARKER_AXIS_X, "leftx",         },
8965     {  73, 141, MARKER_AXIS_Y, "lefty",         },
8966     { 282, 210, MARKER_AXIS_X, "rightx",        },
8967     { 282, 210, MARKER_AXIS_Y, "righty",        },
8968   };
8969
8970   unsigned int event_frame_delay = 0;
8971   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
8972
8973   ResetDelayCounter(&event_frame_delay);
8974
8975   if (!bitmaps_initialized)
8976   {
8977     controller = LoadCustomImage("joystick/controller.png");
8978     button     = LoadCustomImage("joystick/button.png");
8979     axis_x     = LoadCustomImage("joystick/axis_x.png");
8980     axis_y     = LoadCustomImage("joystick/axis_y.png");
8981
8982     bitmaps_initialized = TRUE;
8983   }
8984
8985   name = getFormattedJoystickName(SDL_JoystickName(joystick));
8986
8987 #if DEBUG_JOYSTICKS
8988   // print info about the joystick we are watching
8989   Debug("joystick", "watching joystick %d: (%s)",
8990         SDL_JoystickInstanceID(joystick), name);
8991   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
8992         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
8993         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
8994 #endif
8995
8996   // initialize mapping with GUID and name
8997   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
8998
8999   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
9000            temp, name, SDL_GetPlatform());
9001
9002   // loop through all steps (buttons and axes), getting joystick events
9003   for (i = 0; i < SDL_arraysize(steps) && !done;)
9004   {
9005     Bitmap *marker = button;    // initialize with reliable default value
9006
9007     step = &steps[i];
9008     strcpy(step->mapping, mapping);
9009     step->axis = -1;
9010     step->button = -1;
9011     step->hat = -1;
9012     step->hat_value = -1;
9013
9014     marker = (step->marker == MARKER_BUTTON ? button :
9015               step->marker == MARKER_AXIS_X ? axis_x :
9016               step->marker == MARKER_AXIS_Y ? axis_y : marker);
9017
9018     next = FALSE;
9019
9020     while (!done && !next)
9021     {
9022       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
9023       alpha_ticks = SDL_GetTicks();
9024
9025       if (alpha >= 255)
9026       {
9027         alpha = 255;
9028         alpha_step = -1;
9029       }
9030       else if (alpha < 128)
9031       {
9032         alpha = 127;
9033         alpha_step = 1;
9034       }
9035
9036       int controller_x = SX + (SXSIZE - controller->width) / 2;
9037       int controller_y = SY + ystep_line;
9038
9039       int marker_x = controller_x + step->x;
9040       int marker_y = controller_y + step->y;
9041
9042       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
9043       int ystart2 = ystart1 + ystep_name + ystep_line;
9044
9045       ClearField();
9046
9047       DrawTextSCentered(ystart1, font_name, name);
9048
9049       DrawTextSCentered(ystart2, font_info,
9050                         "Press buttons and move axes on");
9051       ystart2 += ystep_line;
9052       DrawTextSCentered(ystart2, font_info,
9053                         "your controller when indicated.");
9054       ystart2 += ystep_line;
9055       DrawTextSCentered(ystart2, font_info,
9056                         "(Your controller may look different.)");
9057       ystart2 += ystep_para;
9058
9059 #if defined(PLATFORM_ANDROID)
9060       DrawTextSCentered(ystart2, font_info,
9061                         "To correct a mistake,");
9062       ystart2 += ystep_line;
9063       DrawTextSCentered(ystart2, font_info,
9064                         "press the 'back' button.");
9065       ystart2 += ystep_line;
9066       DrawTextSCentered(ystart2, font_info,
9067                         "To skip a button or axis,");
9068       ystart2 += ystep_line;
9069       DrawTextSCentered(ystart2, font_info,
9070                         "press the 'menu' button.");
9071 #else
9072       DrawTextSCentered(ystart2, font_info,
9073                         "To correct a mistake,");
9074       ystart2 += ystep_line;
9075       DrawTextSCentered(ystart2, font_info,
9076                         "press the 'backspace' key.");
9077       ystart2 += ystep_line;
9078       DrawTextSCentered(ystart2, font_info,
9079                         "To skip a button or axis,");
9080       ystart2 += ystep_line;
9081       DrawTextSCentered(ystart2, font_info,
9082                         "press the 'return' key.");
9083       ystart2 += ystep_line;
9084       DrawTextSCentered(ystart2, font_info,
9085                         "To exit, press the 'escape' key.");
9086 #endif
9087
9088       BlitBitmapMasked(controller, drawto, 0, 0,
9089                        controller->width, controller->height,
9090                        controller_x, controller_y);
9091
9092       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
9093       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
9094
9095       BlitBitmapMasked(marker, drawto, 0, 0,
9096                        marker->width, marker->height,
9097                        marker_x, marker_y);
9098
9099       if (!screen_initialized)
9100         FadeIn(REDRAW_FIELD);
9101       else
9102         BackToFront();
9103
9104       screen_initialized = TRUE;
9105
9106       while (NextValidEvent(&event))
9107       {
9108         switch (event.type)
9109         {
9110           case SDL_JOYAXISMOTION:
9111             if (event.jaxis.value > 20000 ||
9112                 event.jaxis.value < -20000)
9113             {
9114               for (j = 0; j < i; j++)
9115                 if (steps[j].axis == event.jaxis.axis)
9116                   break;
9117
9118               if (j == i)
9119               {
9120                 if (step->marker != MARKER_AXIS_X &&
9121                     step->marker != MARKER_AXIS_Y)
9122                   break;
9123
9124                 step->axis = event.jaxis.axis;
9125                 strcat(mapping, step->field);
9126                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
9127                 strcat(mapping, temp);
9128                 i++;
9129                 next = TRUE;
9130               }
9131             }
9132
9133             break;
9134
9135           case SDL_JOYHATMOTION:
9136             // ignore centering; we're probably just coming back
9137             // to the center from the previous item we set
9138             if (event.jhat.value == SDL_HAT_CENTERED)
9139               break;
9140
9141             for (j = 0; j < i; j++)
9142               if (steps[j].hat == event.jhat.hat &&
9143                   steps[j].hat_value == event.jhat.value)
9144                 break;
9145
9146             if (j == i)
9147             {
9148               step->hat = event.jhat.hat;
9149               step->hat_value = event.jhat.value;
9150               strcat(mapping, step->field);
9151               snprintf(temp, sizeof(temp), ":h%u.%u,",
9152                        event.jhat.hat, event.jhat.value );
9153               strcat(mapping, temp);
9154               i++;
9155               next = TRUE;
9156             }
9157
9158             break;
9159
9160           case SDL_JOYBALLMOTION:
9161             break;
9162
9163           case SDL_JOYBUTTONUP:
9164             for (j = 0; j < i; j++)
9165               if (steps[j].button == event.jbutton.button)
9166                 break;
9167
9168             if (j == i)
9169             {
9170               step->button = event.jbutton.button;
9171               strcat(mapping, step->field);
9172               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
9173               strcat(mapping, temp);
9174               i++;
9175               next = TRUE;
9176             }
9177
9178             break;
9179
9180           case SDL_FINGERDOWN:
9181           case SDL_MOUSEBUTTONDOWN:
9182             // skip this step
9183             i++;
9184             next = TRUE;
9185
9186             break;
9187
9188           case SDL_KEYDOWN:
9189             if (event.key.keysym.sym == KSYM_BackSpace ||
9190                 event.key.keysym.sym == KSYM_Back)
9191             {
9192               if (i == 0)
9193               {
9194                 // leave screen
9195                 success = FALSE;
9196                 done = TRUE;
9197
9198                 break;
9199               }
9200
9201               // undo this step
9202               prev_step = &steps[i - 1];
9203               strcpy(mapping, prev_step->mapping);
9204               i--;
9205               next = TRUE;
9206
9207               break;
9208             }
9209
9210             if (event.key.keysym.sym == KSYM_space ||
9211                 event.key.keysym.sym == KSYM_Return ||
9212                 event.key.keysym.sym == KSYM_Menu)
9213             {
9214               // skip this step
9215               i++;
9216               next = TRUE;
9217
9218               break;
9219             }
9220
9221             if (event.key.keysym.sym == KSYM_Escape)
9222             {
9223               // leave screen
9224               success = FALSE;
9225               done = TRUE;
9226             }
9227
9228             break;
9229
9230           case SDL_QUIT:
9231             program.exit_function(0);
9232             break;
9233
9234           default:
9235             break;
9236         }
9237
9238         // do not handle events for longer than standard frame delay period
9239         if (DelayReached(&event_frame_delay, event_frame_delay_value))
9240           break;
9241       }
9242     }
9243   }
9244
9245   if (success)
9246   {
9247 #if DEBUG_JOYSTICKS
9248     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
9249 #endif
9250
9251     // activate mapping for this game
9252     SDL_GameControllerAddMapping(mapping);
9253
9254     // save mapping to personal mappings
9255     SaveSetup_AddGameControllerMapping(mapping);
9256   }
9257
9258   // wait until the last pending event was removed from event queue
9259   while (NextValidEvent(&event));
9260
9261   return success;
9262 }
9263
9264 static int ConfigureJoystickMain(int player_nr)
9265 {
9266   char *device_name = setup.input[player_nr].joy.device_name;
9267   int joystick_nr = getJoystickNrFromDeviceName(device_name);
9268   boolean joystick_active = CheckJoystickOpened(joystick_nr);
9269   int success = FALSE;
9270   int i;
9271
9272   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
9273     return JOYSTICK_NOT_AVAILABLE;
9274
9275   if (!joystick_active || !setup.input[player_nr].use_joystick)
9276     return JOYSTICK_NOT_AVAILABLE;
9277
9278   FadeSetEnterMenu();
9279   FadeOut(REDRAW_FIELD);
9280
9281   // close all joystick devices (potentially opened as game controllers)
9282   for (i = 0; i < SDL_NumJoysticks(); i++)
9283     SDLCloseJoystick(i);
9284
9285   // open joystick device as plain joystick to configure as game controller
9286   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
9287
9288   // as the joystick was successfully opened before, this should not happen
9289   if (joystick == NULL)
9290     return FALSE;
9291
9292   // create new game controller mapping (buttons and axes) for joystick device
9293   success = ConfigureJoystickMapButtonsAndAxes(joystick);
9294
9295   // close joystick (and maybe re-open as configured game controller later)
9296   SDL_JoystickClose(joystick);
9297
9298   // re-open all joystick devices (potentially as game controllers)
9299   for (i = 0; i < SDL_NumJoysticks(); i++)
9300     SDLOpenJoystick(i);
9301
9302   // clear all joystick input actions for all joystick devices
9303   SDLClearJoystickState();
9304
9305   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
9306 }
9307
9308 void ConfigureJoystick(int player_nr)
9309 {
9310   boolean state = ConfigureJoystickMain(player_nr);
9311
9312   if (state != JOYSTICK_NOT_CONFIGURED)
9313   {
9314     boolean success = (state == JOYSTICK_CONFIGURED);
9315     char message1[MAX_OUTPUT_LINESIZE + 1];
9316     char *message2 = (success ? "configured!" : "not available!");
9317     char *device_name = setup.input[player_nr].joy.device_name;
9318     int nr = getJoystickNrFromDeviceName(device_name) + 1;
9319     int font_nr = FONT_TITLE_1;
9320     int font_height = getFontHeight(font_nr);
9321     int ypos1 = SYSIZE / 2 - font_height * 2;
9322     int ypos2 = SYSIZE / 2 - font_height * 1;
9323     unsigned int wait_frame_delay = 0;
9324     unsigned int wait_frame_delay_value = 2000;
9325
9326     ResetDelayCounter(&wait_frame_delay);
9327
9328     ClearField();
9329
9330     sprintf(message1, "Joystick %d", nr);
9331
9332     DrawTextSCentered(ypos1, font_nr, message1);
9333     DrawTextSCentered(ypos2, font_nr, message2);
9334
9335     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9336       BackToFront();
9337
9338     ClearEventQueue();
9339   }
9340
9341   DrawSetupScreen_Input();
9342 }
9343
9344 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
9345 {
9346   if (y < video.screen_height / 3)
9347   {
9348     // remap touch gadgets to access upper part of the screen
9349     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9350     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9351   }
9352   else if (y > 2 * video.screen_height / 3)
9353   {
9354     // remap touch gadgets to access lower part of the screen
9355     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9356     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9357   }
9358 }
9359
9360 static boolean ConfigureVirtualButtonsMain(void)
9361 {
9362   static char *customize_step_text[] =
9363   {
9364     "Move Left",
9365     "Move Right",
9366     "Move Up",
9367     "Move Down",
9368     "Snap Field",
9369     "Drop Element"
9370   };
9371   char grid_button[] =
9372   {
9373     CHAR_GRID_BUTTON_LEFT,
9374     CHAR_GRID_BUTTON_RIGHT,
9375     CHAR_GRID_BUTTON_UP,
9376     CHAR_GRID_BUTTON_DOWN,
9377     CHAR_GRID_BUTTON_SNAP,
9378     CHAR_GRID_BUTTON_DROP
9379   };
9380   enum
9381   {
9382     ACTION_NONE,
9383     ACTION_ESCAPE,
9384     ACTION_BACK,
9385     ACTION_NEXT
9386   };
9387   int font_nr = FONT_INPUT_1_ACTIVE;
9388   int font_height = getFontHeight(font_nr);
9389   int ypos1 = SYSIZE / 2 - font_height * 2;
9390   int ypos2 = SYSIZE / 2 - font_height * 1;
9391   boolean success = FALSE;
9392   boolean finished = FALSE;
9393   int step_nr = 0;
9394   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
9395   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9396   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9397   boolean set_grid_button = FALSE;
9398   int nr = GRID_ACTIVE_NR();
9399   int x, y;
9400
9401   for (x = 0; x < MAX_GRID_XSIZE; x++)
9402     for (y = 0; y < MAX_GRID_YSIZE; y++)
9403       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
9404
9405   overlay.grid_button_highlight = grid_button[step_nr];
9406
9407   UnmapAllGadgets();
9408
9409   FadeSetEnterMenu();
9410   FadeOut(REDRAW_FIELD);
9411
9412   ClearField();
9413
9414   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9415   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9416   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9417
9418   FadeIn(REDRAW_FIELD);
9419
9420   SetOverlayShowGrid(TRUE);
9421
9422   // map gadgets for setup touch buttons menu screen
9423   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9424
9425   while (!finished)
9426   {
9427     Event event;
9428
9429     while (NextValidEvent(&event))
9430     {
9431       int action = ACTION_NONE;
9432
9433       // ---------- handle events and set the resulting action ----------
9434
9435       switch (event.type)
9436       {
9437         case EVENT_USER:
9438           {
9439             UserEvent *user = (UserEvent *)&event;
9440             int id = user->value1;
9441
9442             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
9443                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
9444                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
9445                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
9446                       ACTION_NONE);
9447           }
9448           break;
9449
9450         case EVENT_KEYPRESS:
9451           {
9452             Key key = GetEventKey((KeyEvent *)&event, FALSE);
9453
9454             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
9455                       key == KSYM_BackSpace ||
9456                       key == KSYM_Back ?        ACTION_BACK :
9457                       key == KSYM_Return ||
9458                       key == KSYM_Menu ||
9459                       key == KSYM_space ?       ACTION_NEXT :
9460                       ACTION_NONE);
9461           }
9462           break;
9463
9464         case EVENT_KEYRELEASE:
9465           key_joystick_mapping = 0;
9466           break;
9467
9468         case EVENT_BUTTONPRESS:
9469         case EVENT_BUTTONRELEASE:
9470           {
9471             ButtonEvent *button = (ButtonEvent *)&event;
9472
9473             motion_status = FALSE;
9474
9475             if (button->type == EVENT_BUTTONPRESS)
9476               button_status = button->button;
9477             else
9478               button_status = MB_RELEASED;
9479
9480             if (HandleGadgets(button->x, button->y, button_status))
9481             {
9482               // do not handle this button event anymore
9483               break;
9484             }
9485
9486             button->x += video.screen_xoffset;
9487             button->y += video.screen_yoffset;
9488
9489             x = button->x * overlay.grid_xsize / video.screen_width;
9490             y = button->y * overlay.grid_ysize / video.screen_height;
9491
9492             if (button->type == EVENT_BUTTONPRESS)
9493             {
9494               grid_button_draw =
9495                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9496                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9497
9498               set_grid_button = TRUE;
9499             }
9500
9501             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9502           }
9503           break;
9504
9505         case EVENT_MOTIONNOTIFY:
9506           {
9507             MotionEvent *motion = (MotionEvent *)&event;
9508
9509             motion_status = TRUE;
9510
9511             if (HandleGadgets(motion->x, motion->y, button_status))
9512             {
9513               // do not handle this button event anymore
9514               break;
9515             }
9516
9517             motion->x += video.screen_xoffset;
9518             motion->y += video.screen_yoffset;
9519
9520             x = motion->x * overlay.grid_xsize / video.screen_width;
9521             y = motion->y * overlay.grid_ysize / video.screen_height;
9522
9523             set_grid_button = TRUE;
9524
9525             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9526           }
9527           break;
9528
9529         case SDL_WINDOWEVENT:
9530           HandleWindowEvent((WindowEvent *) &event);
9531
9532           // check if device has been rotated
9533           if (nr != GRID_ACTIVE_NR())
9534           {
9535             nr = GRID_ACTIVE_NR();
9536
9537             for (x = 0; x < MAX_GRID_XSIZE; x++)
9538               for (y = 0; y < MAX_GRID_YSIZE; y++)
9539                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9540                   overlay.grid_button[x][y];
9541           }
9542
9543           break;
9544
9545         case SDL_APP_WILLENTERBACKGROUND:
9546         case SDL_APP_DIDENTERBACKGROUND:
9547         case SDL_APP_WILLENTERFOREGROUND:
9548         case SDL_APP_DIDENTERFOREGROUND:
9549           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9550           break;
9551
9552         default:
9553           HandleOtherEvents(&event);
9554           break;
9555       }
9556
9557       // ---------- perform action set by handling events ----------
9558
9559       if (action == ACTION_ESCAPE)
9560       {
9561         // abort and restore the old key bindings
9562
9563         for (x = 0; x < MAX_GRID_XSIZE; x++)
9564           for (y = 0; y < MAX_GRID_YSIZE; y++)
9565             overlay.grid_button[x][y] = grid_button_old[x][y];
9566
9567         FadeSkipNextFadeIn();
9568
9569         finished = TRUE;
9570       }
9571       else if (action == ACTION_BACK)
9572       {
9573         // keep the configured key bindings and go to previous page
9574
9575         step_nr--;
9576
9577         if (step_nr < 0)
9578         {
9579           FadeSkipNextFadeIn();
9580
9581           finished = TRUE;
9582         }
9583       }
9584       else if (action == ACTION_NEXT)
9585       {
9586         // keep the configured key bindings and go to next page
9587
9588         step_nr++;
9589
9590         // all virtual buttons configured
9591         if (step_nr == 6)
9592         {
9593           finished = TRUE;
9594           success = TRUE;
9595         }
9596       }
9597
9598       if (action != ACTION_NONE && !finished)
9599       {
9600         for (x = 0; x < MAX_GRID_XSIZE; x++)
9601           for (y = 0; y < MAX_GRID_YSIZE; y++)
9602             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9603
9604         overlay.grid_button_highlight = grid_button[step_nr];
9605
9606         // configure next virtual button
9607
9608         ClearField();
9609
9610         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9611         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9612         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9613       }
9614
9615       if (set_grid_button)
9616       {
9617         overlay.grid_button[x][y] =
9618           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9619            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9620            grid_button_tmp[x][y]);
9621
9622         set_grid_button = FALSE;
9623       }
9624     }
9625
9626     BackToFront();
9627   }
9628
9629   for (x = 0; x < MAX_GRID_XSIZE; x++)
9630     for (y = 0; y < MAX_GRID_YSIZE; y++)
9631       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9632
9633   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9634
9635   SetOverlayShowGrid(FALSE);
9636
9637   return success;
9638 }
9639
9640 void ConfigureVirtualButtons(void)
9641 {
9642   boolean success = ConfigureVirtualButtonsMain();
9643
9644   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9645                          SCREEN_MASK_TOUCH2);
9646
9647   if (success)
9648   {
9649     int font_nr = FONT_TITLE_1;
9650     int font_height = getFontHeight(font_nr);
9651     int ypos1 = SYSIZE / 2 - font_height * 2;
9652     int ypos2 = SYSIZE / 2 - font_height * 1;
9653     unsigned int wait_frame_delay = 0;
9654     unsigned int wait_frame_delay_value = 2000;
9655
9656     ResetDelayCounter(&wait_frame_delay);
9657
9658     ClearField();
9659
9660     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9661     DrawTextSCentered(ypos2, font_nr, "configured!");
9662
9663     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9664       BackToFront();
9665
9666     ClearEventQueue();
9667   }
9668 }
9669
9670 void DrawSetupScreen(void)
9671 {
9672   align_xoffset = 0;
9673   align_yoffset = 0;
9674
9675   if (setup_mode == SETUP_MODE_INPUT)
9676     DrawSetupScreen_Input();
9677   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9678     DrawChooseTree(&scores_type_current);
9679   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9680     DrawChooseTree(&game_speed_current);
9681   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9682     DrawChooseTree(&scroll_delay_current);
9683   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9684     DrawChooseTree(&snapshot_mode_current);
9685   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9686     DrawChooseTree(&window_size_current);
9687   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9688     DrawChooseTree(&scaling_type_current);
9689   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9690     DrawChooseTree(&rendering_mode_current);
9691   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9692     DrawChooseTree(&vsync_mode_current);
9693   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9694     DrawChooseTree(&artwork.gfx_current);
9695   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9696     DrawChooseTree(&artwork.snd_current);
9697   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9698     DrawChooseTree(&artwork.mus_current);
9699   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9700     DrawChooseTree(&volume_simple_current);
9701   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9702     DrawChooseTree(&volume_loops_current);
9703   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9704     DrawChooseTree(&volume_music_current);
9705   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9706     DrawChooseTree(&touch_control_current);
9707   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9708     DrawChooseTree(&move_distance_current);
9709   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9710     DrawChooseTree(&drop_distance_current);
9711   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9712     DrawChooseTree(&transparency_current);
9713   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9714     DrawChooseTree(&grid_size_current[0][0]);
9715   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9716     DrawChooseTree(&grid_size_current[0][1]);
9717   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9718     DrawChooseTree(&grid_size_current[1][0]);
9719   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9720     DrawChooseTree(&grid_size_current[1][1]);
9721   else
9722     DrawSetupScreen_Generic();
9723
9724   PlayMenuSoundsAndMusic();
9725 }
9726
9727 void RedrawSetupScreenAfterFullscreenToggle(void)
9728 {
9729   if (setup_mode == SETUP_MODE_GRAPHICS ||
9730       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9731   {
9732     // update list selection from "setup.window_scaling_percent"
9733     execSetupGraphics_setWindowSizes(TRUE);
9734
9735     DrawSetupScreen();
9736   }
9737 }
9738
9739 void RedrawSetupScreenAfterScreenRotation(int nr)
9740 {
9741   int x, y;
9742
9743   if (setup_mode == SETUP_MODE_TOUCH)
9744   {
9745     // update virtual button settings (depending on screen orientation)
9746     DrawSetupScreen();
9747   }
9748   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
9749   {
9750     // save already configured virtual buttons
9751     for (x = 0; x < MAX_GRID_XSIZE; x++)
9752       for (y = 0; y < MAX_GRID_YSIZE; y++)
9753         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9754   }
9755 }
9756
9757 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
9758 {
9759   if (setup_mode == SETUP_MODE_INPUT)
9760     HandleSetupScreen_Input(mx, my, dx, dy, button);
9761   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9762     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
9763   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9764     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
9765   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9766     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
9767   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9768     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
9769   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9770     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
9771   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9772     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
9773   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9774     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
9775   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9776     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
9777   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9778     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
9779   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9780     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
9781   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9782     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
9783   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9784     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
9785   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9786     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
9787   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9788     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
9789   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9790     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
9791   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9792     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
9793   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9794     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
9795   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9796     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
9797   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9798     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
9799   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9800     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
9801   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9802     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
9803   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9804     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
9805   else
9806     HandleSetupScreen_Generic(mx, my, dx, dy, button);
9807 }
9808
9809 void HandleGameActions(void)
9810 {
9811   if (setup.ask_on_game_over)
9812     CheckGameOver();
9813
9814   if (game.restart_game_message != NULL)
9815   {
9816     RequestRestartGame(game.restart_game_message);
9817
9818     return;
9819   }
9820
9821   if (game_status != GAME_MODE_PLAYING)
9822     return;
9823
9824   GameActions();                // main game loop
9825
9826   if (tape.auto_play && !tape.playing)
9827     AutoPlayTapesContinue();    // continue automatically playing next tape
9828 }
9829
9830
9831 // ---------- new screen button stuff --------------------------------------
9832
9833 static struct
9834 {
9835   int gfx_unpressed, gfx_pressed;
9836   struct MenuPosInfo *pos;
9837   boolean *check_value;
9838   int gadget_id;
9839   int screen_mask;
9840   unsigned int event_mask;
9841   boolean is_touch_button;
9842   char *infotext;
9843 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
9844 {
9845   {
9846     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
9847     &menu.main.button.prev_level, NULL,
9848     SCREEN_CTRL_ID_PREV_LEVEL,
9849     SCREEN_MASK_MAIN,
9850     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9851     FALSE, "previous level"
9852   },
9853   {
9854     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
9855     &menu.main.button.next_level, NULL,
9856     SCREEN_CTRL_ID_NEXT_LEVEL,
9857     SCREEN_MASK_MAIN,
9858     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9859     FALSE, "next level"
9860   },
9861   {
9862     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE,
9863     &menu.scores.button.prev_level, NULL,
9864     SCREEN_CTRL_ID_PREV_LEVEL2,
9865     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9866     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9867     FALSE, "previous level"
9868   },
9869   {
9870     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE,
9871     &menu.scores.button.next_level, NULL,
9872     SCREEN_CTRL_ID_NEXT_LEVEL2,
9873     SCREEN_MASK_SCORES | SCREEN_MASK_SCORES_INFO,
9874     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9875     FALSE, "next level"
9876   },
9877   {
9878     IMG_MENU_BUTTON_PREV_SCORE, IMG_MENU_BUTTON_PREV_SCORE_ACTIVE,
9879     &menu.scores.button.prev_score, NULL,
9880     SCREEN_CTRL_ID_PREV_SCORE,
9881     SCREEN_MASK_SCORES_INFO,
9882     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9883     FALSE, "previous score"
9884   },
9885   {
9886     IMG_MENU_BUTTON_NEXT_SCORE, IMG_MENU_BUTTON_NEXT_SCORE_ACTIVE,
9887     &menu.scores.button.next_score, NULL,
9888     SCREEN_CTRL_ID_NEXT_SCORE,
9889     SCREEN_MASK_SCORES_INFO,
9890     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9891     FALSE, "next score"
9892   },
9893   {
9894     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE,
9895     &menu.main.button.first_level, NULL,
9896     SCREEN_CTRL_ID_FIRST_LEVEL,
9897     SCREEN_MASK_MAIN,
9898     GD_EVENT_RELEASED,
9899     FALSE, "first level"
9900   },
9901   {
9902     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE,
9903     &menu.main.button.last_level, NULL,
9904     SCREEN_CTRL_ID_LAST_LEVEL,
9905     SCREEN_MASK_MAIN,
9906     GD_EVENT_RELEASED,
9907     FALSE, "last level"
9908   },
9909   {
9910     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE,
9911     &menu.main.button.level_number, NULL,
9912     SCREEN_CTRL_ID_LEVEL_NUMBER,
9913     SCREEN_MASK_MAIN,
9914     GD_EVENT_RELEASED,
9915     FALSE, "level number"
9916   },
9917   {
9918     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
9919     &menu.setup.button.prev_player, NULL,
9920     SCREEN_CTRL_ID_PREV_PLAYER,
9921     SCREEN_MASK_INPUT,
9922     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9923     FALSE, "previous player"
9924   },
9925   {
9926     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
9927     &menu.setup.button.next_player, NULL,
9928     SCREEN_CTRL_ID_NEXT_PLAYER,
9929     SCREEN_MASK_INPUT,
9930     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9931     FALSE, "next player"
9932   },
9933   {
9934     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE,
9935     &menu.main.button.insert_solution, NULL,
9936     SCREEN_CTRL_ID_INSERT_SOLUTION,
9937     SCREEN_MASK_MAIN_HAS_SOLUTION,
9938     GD_EVENT_RELEASED,
9939     FALSE, "insert solution tape"
9940   },
9941   {
9942     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE,
9943     &menu.main.button.play_solution, NULL,
9944     SCREEN_CTRL_ID_PLAY_SOLUTION,
9945     SCREEN_MASK_MAIN_HAS_SOLUTION,
9946     GD_EVENT_RELEASED,
9947     FALSE, "play solution tape"
9948   },
9949   {
9950     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE,
9951     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
9952     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
9953     SCREEN_MASK_MAIN,
9954     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
9955     FALSE, "switch ECS/AGA chipset"
9956   },
9957   {
9958     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK,
9959     &menu.setup.button.touch_back, NULL,
9960     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
9961     SCREEN_MASK_TOUCH,
9962     GD_EVENT_RELEASED,
9963     TRUE, "previous page"
9964   },
9965   {
9966     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT,
9967     &menu.setup.button.touch_next, NULL,
9968     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
9969     SCREEN_MASK_TOUCH,
9970     GD_EVENT_RELEASED,
9971     TRUE, "next page"
9972   },
9973   {
9974     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2,
9975     &menu.setup.button.touch_back2, NULL,
9976     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
9977     SCREEN_MASK_TOUCH2,
9978     GD_EVENT_RELEASED,
9979     TRUE, "previous page"
9980   },
9981   {
9982     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2,
9983     &menu.setup.button.touch_next2, NULL,
9984     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
9985     SCREEN_MASK_TOUCH2,
9986     GD_EVENT_RELEASED,
9987     TRUE, "next page"
9988   },
9989 };
9990
9991 static struct
9992 {
9993   int gfx_unpressed, gfx_pressed;
9994   int x, y;
9995   int gadget_id;
9996   char *infotext;
9997 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
9998 {
9999   {
10000     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
10001     -1, -1,     // these values are not constant, but can change at runtime
10002     SCREEN_CTRL_ID_SCROLL_UP,
10003     "scroll up"
10004   },
10005   {
10006     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
10007     -1, -1,     // these values are not constant, but can change at runtime
10008     SCREEN_CTRL_ID_SCROLL_DOWN,
10009     "scroll down"
10010   }
10011 };
10012
10013 static struct
10014 {
10015   int gfx_unpressed, gfx_pressed;
10016   int x, y;
10017   int width, height;
10018   int type;
10019   int gadget_id;
10020   char *infotext;
10021 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
10022 {
10023   {
10024     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
10025     -1, -1,     // these values are not constant, but can change at runtime
10026     -1, -1,     // these values are not constant, but can change at runtime
10027     GD_TYPE_SCROLLBAR_VERTICAL,
10028     SCREEN_CTRL_ID_SCROLL_VERTICAL,
10029     "scroll level series vertically"
10030   }
10031 };
10032
10033 static struct
10034 {
10035   int graphic;
10036   int gadget_id;
10037   int x, y;
10038   int size;
10039   char *value;
10040   char *infotext;
10041 } textinput_info[NUM_SCREEN_TEXTINPUT] =
10042 {
10043   {
10044     IMG_SETUP_INPUT_TEXT,
10045     SCREEN_CTRL_ID_NETWORK_SERVER,
10046     -1, -1,     // these values are not constant, but can change at runtime
10047     MAX_SETUP_TEXT_INPUT_LEN,
10048     network_server_hostname,
10049     "Network Server Hostname / IP"
10050   },
10051 };
10052
10053 static void CreateScreenMenubuttons(void)
10054 {
10055   struct GadgetInfo *gi;
10056   unsigned int event_mask;
10057   int i;
10058
10059   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10060   {
10061     struct MenuPosInfo *pos = menubutton_info[i].pos;
10062     int screen_mask = menubutton_info[i].screen_mask;
10063     boolean is_touch_button = menubutton_info[i].is_touch_button;
10064     boolean is_check_button = menubutton_info[i].check_value != NULL;
10065     boolean is_score_button = (screen_mask & SCREEN_MASK_SCORES_INFO);
10066     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10067     int gfx_unpressed, gfx_pressed;
10068     int x, y, width, height;
10069     int gd_x1, gd_x2, gd_y1, gd_y2;
10070     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
10071     int id = menubutton_info[i].gadget_id;
10072     int type = GD_TYPE_NORMAL_BUTTON;
10073     boolean checked = FALSE;
10074
10075     event_mask = menubutton_info[i].event_mask;
10076
10077     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
10078     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
10079
10080     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
10081     height = graphic_info[menubutton_info[i].gfx_pressed].height;
10082
10083     gfx_unpressed = menubutton_info[i].gfx_unpressed;
10084     gfx_pressed   = menubutton_info[i].gfx_pressed;
10085     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10086     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10087     gd_x1 = graphic_info[gfx_unpressed].src_x;
10088     gd_y1 = graphic_info[gfx_unpressed].src_y;
10089     gd_x2 = graphic_info[gfx_pressed].src_x;
10090     gd_y2 = graphic_info[gfx_pressed].src_y;
10091     gd_x1a = gd_x1;
10092     gd_y1a = gd_y1;
10093     gd_x2a = gd_x2;
10094     gd_y2a = gd_y2;
10095
10096     if (is_touch_button)
10097     {
10098       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
10099       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
10100     }
10101
10102     if (is_check_button)
10103     {
10104       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
10105       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
10106       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
10107       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
10108
10109       type = GD_TYPE_CHECK_BUTTON;
10110       checked = *menubutton_info[i].check_value;
10111     }
10112
10113     if (is_score_button)
10114     {
10115       // if x/y set to -1, dynamically place buttons next to title text
10116       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
10117
10118       if (pos->x == -1)
10119         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
10120              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
10121              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
10122              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
10123
10124       if (pos->y == -1)
10125         y = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ||
10126              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ? mSY + MENU_TITLE1_YPOS : 0);
10127     }
10128
10129     gi = CreateGadget(GDI_CUSTOM_ID, id,
10130                       GDI_CUSTOM_TYPE_ID, i,
10131                       GDI_IMAGE_ID, gfx_unpressed,
10132                       GDI_INFO_TEXT, menubutton_info[i].infotext,
10133                       GDI_X, x,
10134                       GDI_Y, y,
10135                       GDI_WIDTH, width,
10136                       GDI_HEIGHT, height,
10137                       GDI_TYPE, type,
10138                       GDI_STATE, GD_BUTTON_UNPRESSED,
10139                       GDI_CHECKED, checked,
10140                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10141                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10142                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1a, gd_y1a,
10143                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2a, gd_y2a,
10144                       GDI_DIRECT_DRAW, FALSE,
10145                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
10146                       GDI_EVENT_MASK, event_mask,
10147                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10148                       GDI_END);
10149
10150     if (gi == NULL)
10151       Fail("cannot create gadget");
10152
10153     screen_gadget[id] = gi;
10154   }
10155 }
10156
10157 static void CreateScreenScrollbuttons(void)
10158 {
10159   struct GadgetInfo *gi;
10160   unsigned int event_mask;
10161   int i;
10162
10163   // these values are not constant, but can change at runtime
10164   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
10165   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
10166   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
10167   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
10168
10169   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10170   {
10171     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10172     int gfx_unpressed, gfx_pressed;
10173     int x, y, width, height;
10174     int gd_x1, gd_x2, gd_y1, gd_y2;
10175     int id = scrollbutton_info[i].gadget_id;
10176
10177     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
10178
10179     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
10180     y = mSY + scrollbutton_info[i].y;
10181     width = SC_SCROLLBUTTON_XSIZE;
10182     height = SC_SCROLLBUTTON_YSIZE;
10183
10184     // correct scrollbar position if placed outside menu (playfield) area
10185     if (x > SX + SC_SCROLL_UP_XPOS)
10186       x = SX + SC_SCROLL_UP_XPOS;
10187
10188     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
10189       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
10190                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
10191
10192     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
10193     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
10194     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10195     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10196     gd_x1 = graphic_info[gfx_unpressed].src_x;
10197     gd_y1 = graphic_info[gfx_unpressed].src_y;
10198     gd_x2 = graphic_info[gfx_pressed].src_x;
10199     gd_y2 = graphic_info[gfx_pressed].src_y;
10200
10201     gi = CreateGadget(GDI_CUSTOM_ID, id,
10202                       GDI_CUSTOM_TYPE_ID, i,
10203                       GDI_IMAGE_ID, gfx_unpressed,
10204                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
10205                       GDI_X, x,
10206                       GDI_Y, y,
10207                       GDI_WIDTH, width,
10208                       GDI_HEIGHT, height,
10209                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
10210                       GDI_STATE, GD_BUTTON_UNPRESSED,
10211                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10212                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10213                       GDI_DIRECT_DRAW, FALSE,
10214                       GDI_EVENT_MASK, event_mask,
10215                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10216                       GDI_END);
10217
10218     if (gi == NULL)
10219       Fail("cannot create gadget");
10220
10221     screen_gadget[id] = gi;
10222   }
10223 }
10224
10225 static void CreateScreenScrollbars(void)
10226 {
10227   int i;
10228
10229   // these values are not constant, but can change at runtime
10230   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
10231   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
10232   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
10233   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
10234
10235   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10236   {
10237     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10238     int gfx_unpressed, gfx_pressed;
10239     int x, y, width, height;
10240     int gd_x1, gd_x2, gd_y1, gd_y2;
10241     struct GadgetInfo *gi;
10242     int items_max, items_visible, item_position;
10243     unsigned int event_mask;
10244     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
10245     int id = scrollbar_info[i].gadget_id;
10246
10247     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
10248
10249     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
10250     y = mSY + scrollbar_info[i].y;
10251     width  = scrollbar_info[i].width;
10252     height = scrollbar_info[i].height;
10253
10254     // correct scrollbar position if placed outside menu (playfield) area
10255     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
10256       x = SX + SC_SCROLL_VERTICAL_XPOS;
10257
10258     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
10259       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
10260
10261     items_max = num_page_entries;
10262     items_visible = num_page_entries;
10263     item_position = 0;
10264
10265     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
10266     gfx_pressed   = scrollbar_info[i].gfx_pressed;
10267     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10268     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10269     gd_x1 = graphic_info[gfx_unpressed].src_x;
10270     gd_y1 = graphic_info[gfx_unpressed].src_y;
10271     gd_x2 = graphic_info[gfx_pressed].src_x;
10272     gd_y2 = graphic_info[gfx_pressed].src_y;
10273
10274     gi = CreateGadget(GDI_CUSTOM_ID, id,
10275                       GDI_CUSTOM_TYPE_ID, i,
10276                       GDI_IMAGE_ID, gfx_unpressed,
10277                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
10278                       GDI_X, x,
10279                       GDI_Y, y,
10280                       GDI_WIDTH, width,
10281                       GDI_HEIGHT, height,
10282                       GDI_TYPE, scrollbar_info[i].type,
10283                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
10284                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
10285                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
10286                       GDI_WHEEL_AREA_X, SX,
10287                       GDI_WHEEL_AREA_Y, SY,
10288                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
10289                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
10290                       GDI_STATE, GD_BUTTON_UNPRESSED,
10291                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10292                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10293                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
10294                       GDI_DIRECT_DRAW, FALSE,
10295                       GDI_EVENT_MASK, event_mask,
10296                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10297                       GDI_END);
10298
10299     if (gi == NULL)
10300       Fail("cannot create gadget");
10301
10302     screen_gadget[id] = gi;
10303   }
10304 }
10305
10306 static void CreateScreenTextInputGadgets(void)
10307 {
10308   int i;
10309
10310   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
10311   {
10312     int graphic = textinput_info[i].graphic;
10313     struct GraphicInfo *gd = &graphic_info[graphic];
10314     int gd_x1 = gd->src_x;
10315     int gd_y1 = gd->src_y;
10316     int gd_x2 = gd->src_x + gd->active_xoffset;
10317     int gd_y2 = gd->src_y + gd->active_yoffset;
10318     struct GadgetInfo *gi;
10319     unsigned int event_mask;
10320     int id = textinput_info[i].gadget_id;
10321     int x = textinput_info[i].x;
10322     int y = textinput_info[i].y;
10323
10324     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
10325
10326     gi = CreateGadget(GDI_CUSTOM_ID, id,
10327                       GDI_CUSTOM_TYPE_ID, i,
10328                       GDI_INFO_TEXT, textinput_info[i].infotext,
10329                       GDI_X, SX + x,
10330                       GDI_Y, SY + y,
10331                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
10332                       GDI_TEXT_VALUE, textinput_info[i].value,
10333                       GDI_TEXT_SIZE, textinput_info[i].size,
10334                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
10335                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
10336                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
10337                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
10338                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
10339                       GDI_DESIGN_WIDTH, gd->width,
10340                       GDI_EVENT_MASK, event_mask,
10341                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10342                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
10343                       GDI_END);
10344
10345     if (gi == NULL)
10346       Fail("cannot create gadget");
10347
10348     screen_gadget[id] = gi;
10349   }
10350 }
10351
10352 void CreateScreenGadgets(void)
10353 {
10354   CreateScreenMenubuttons();
10355
10356   CreateScreenScrollbuttons();
10357   CreateScreenScrollbars();
10358
10359   CreateScreenTextInputGadgets();
10360 }
10361
10362 void FreeScreenGadgets(void)
10363 {
10364   int i;
10365
10366   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
10367     FreeGadget(screen_gadget[i]);
10368 }
10369
10370 static void RedrawScreenMenuGadgets(int screen_mask)
10371 {
10372   int i;
10373
10374   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10375     if (screen_mask & menubutton_info[i].screen_mask)
10376       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
10377 }
10378
10379 static void MapScreenMenuGadgets(int screen_mask)
10380 {
10381   int i;
10382
10383   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10384     if (screen_mask & menubutton_info[i].screen_mask)
10385       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10386 }
10387
10388 static void UnmapScreenMenuGadgets(int screen_mask)
10389 {
10390   int i;
10391
10392   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10393   {
10394     if (screen_mask & menubutton_info[i].screen_mask)
10395     {
10396       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10397
10398       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
10399         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
10400                        screen_gadget[menubutton_info[i].gadget_id]->y,
10401                        screen_gadget[menubutton_info[i].gadget_id]->width,
10402                        screen_gadget[menubutton_info[i].gadget_id]->height);
10403     }
10404   }
10405 }
10406
10407 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
10408 {
10409   if (map_gadgets)
10410     MapScreenMenuGadgets(screen_mask);
10411   else
10412     UnmapScreenMenuGadgets(screen_mask);
10413 }
10414
10415 static void MapScreenGadgets(int num_entries)
10416 {
10417   int i;
10418
10419   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
10420     return;
10421
10422   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10423     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10424
10425   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10426     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10427 }
10428
10429 static void UnmapScreenGadgets()
10430 {
10431   int i;
10432
10433   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10434     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10435
10436   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10437     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10438 }
10439
10440 static void MapScreenTreeGadgets(TreeInfo *ti)
10441 {
10442   MapScreenGadgets(numTreeInfoInGroup(ti));
10443 }
10444
10445 static void UnmapScreenTreeGadgets(void)
10446 {
10447   UnmapScreenGadgets();
10448 }
10449
10450 static void HandleScreenGadgets(struct GadgetInfo *gi)
10451 {
10452   int id = gi->custom_id;
10453   int button = gi->event.button;
10454   int step = (button == MB_LEFTBUTTON   ? 1 :
10455               button == MB_MIDDLEBUTTON ? 5 :
10456               button == MB_RIGHTBUTTON  ? 10 : 1);
10457
10458   switch (id)
10459   {
10460     case SCREEN_CTRL_ID_PREV_LEVEL:
10461       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10462       break;
10463
10464     case SCREEN_CTRL_ID_NEXT_LEVEL:
10465       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10466       break;
10467
10468     case SCREEN_CTRL_ID_PREV_LEVEL2:
10469       HandleHallOfFame_SelectLevelOrScore(step, -1);
10470       break;
10471
10472     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10473       HandleHallOfFame_SelectLevelOrScore(step, +1);
10474       break;
10475
10476     case SCREEN_CTRL_ID_FIRST_LEVEL:
10477       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10478       break;
10479
10480     case SCREEN_CTRL_ID_LAST_LEVEL:
10481       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10482       break;
10483
10484     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10485       CloseDoor(DOOR_CLOSE_2);
10486       SetGameStatus(GAME_MODE_LEVELNR);
10487       DrawChooseLevelNr();
10488       break;
10489
10490     case SCREEN_CTRL_ID_PREV_PLAYER:
10491       HandleSetupScreen_Input_Player(step, -1);
10492       break;
10493
10494     case SCREEN_CTRL_ID_NEXT_PLAYER:
10495       HandleSetupScreen_Input_Player(step, +1);
10496       break;
10497
10498     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10499       InsertSolutionTape();
10500       break;
10501
10502     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10503       PlaySolutionTape();
10504       break;
10505
10506     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10507       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10508       DrawMainMenu();
10509       break;
10510
10511     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10512     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10513     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10514     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10515       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10516       break;
10517
10518     case SCREEN_CTRL_ID_SCROLL_UP:
10519       if (game_status == GAME_MODE_NAMES)
10520         HandleChoosePlayerName(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10521       else if (game_status == GAME_MODE_LEVELS)
10522         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10523       else if (game_status == GAME_MODE_LEVELNR)
10524         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10525       else if (game_status == GAME_MODE_SETUP)
10526         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10527       else if (game_status == GAME_MODE_INFO)
10528         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10529       else if (game_status == GAME_MODE_SCORES)
10530         HandleHallOfFame(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10531       break;
10532
10533     case SCREEN_CTRL_ID_SCROLL_DOWN:
10534       if (game_status == GAME_MODE_NAMES)
10535         HandleChoosePlayerName(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10536       else if (game_status == GAME_MODE_LEVELS)
10537         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10538       else if (game_status == GAME_MODE_LEVELNR)
10539         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10540       else if (game_status == GAME_MODE_SETUP)
10541         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10542       else if (game_status == GAME_MODE_INFO)
10543         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10544       else if (game_status == GAME_MODE_SCORES)
10545         HandleHallOfFame(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10546       break;
10547
10548     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
10549       if (game_status == GAME_MODE_NAMES)
10550         HandleChoosePlayerName(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10551       else if (game_status == GAME_MODE_LEVELS)
10552         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10553       else if (game_status == GAME_MODE_LEVELNR)
10554         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10555       else if (game_status == GAME_MODE_SETUP)
10556         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10557       else if (game_status == GAME_MODE_INFO)
10558         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10559       else if (game_status == GAME_MODE_SCORES)
10560         HandleHallOfFame(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10561       break;
10562
10563     case SCREEN_CTRL_ID_NETWORK_SERVER:
10564     {
10565       if (!strEqual(gi->textinput.value, ""))
10566       {
10567         setString(&setup.network_server_hostname, gi->textinput.value);
10568
10569         network.server_host = setup.network_server_hostname;
10570       }
10571       else
10572       {
10573         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
10574
10575         network.server_host = NULL;
10576       }
10577
10578       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
10579         network.server_host = NULL;
10580
10581       execSetupGame_setNetworkServerText();
10582
10583       DrawSetupScreen();
10584
10585       break;
10586     }
10587
10588     default:
10589       break;
10590   }
10591 }
10592
10593 void DumpScreenIdentifiers(void)
10594 {
10595   int i;
10596
10597   Print("Active screen elements on current screen:\n");
10598
10599   for (i = 0; main_controls[i].nr != -1; i++)
10600   {
10601     struct MainControlInfo *mci = &main_controls[i];
10602
10603     if (mci->button_graphic != -1)
10604     {
10605       char *token = getTokenFromImageID(mci->button_graphic);
10606
10607       Print("- '%s'\n", token);
10608     }
10609   }
10610
10611   Print("Done.\n");
10612 }
10613
10614 boolean DoScreenAction(int image_id)
10615 {
10616   int i;
10617
10618   if (game_status != GAME_MODE_MAIN)
10619     return FALSE;
10620
10621   for (i = 0; main_controls[i].nr != -1; i++)
10622   {
10623     struct MainControlInfo *mci = &main_controls[i];
10624     struct MenuPosInfo *pos = mci->pos_button;
10625
10626     if (mci->button_graphic == image_id)
10627     {
10628       int x = mSX + pos->x;
10629       int y = mSY + pos->y;
10630
10631       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
10632
10633       return TRUE;
10634     }
10635   }
10636
10637   return FALSE;
10638 }
10639
10640 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
10641 {
10642   // get tree info node of newly added level or artwork set
10643   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
10644   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
10645                                                       tree_subdir_new);
10646   if (tree_node_new == NULL)    // should not happen
10647     return;
10648
10649   // if request dialog is active, do nothing
10650   if (game.request_active)
10651     return;
10652
10653   if (game_status == GAME_MODE_MAIN &&
10654       tree_type == TREE_TYPE_LEVEL_DIR)
10655   {
10656     // when adding new level set in main menu, select it as current level set
10657
10658     // change current level set to newly added level set from zip file
10659     leveldir_current = tree_node_new;
10660
10661     // change current level number to first level of newly added level set
10662     level_nr = leveldir_current->first_level;
10663
10664     // redraw screen to reflect changed level set
10665     DrawMainMenu();
10666
10667     // save this level set and level number as last selected level set
10668     SaveLevelSetup_LastSeries();
10669     SaveLevelSetup_SeriesInfo();
10670   }
10671   else if (game_status == GAME_MODE_LEVELS &&
10672            tree_type == TREE_TYPE_LEVEL_DIR)
10673   {
10674     // when adding new level set in level set menu, set cursor and update screen
10675
10676     leveldir_current = tree_node_new;
10677
10678     DrawChooseTree(&leveldir_current);
10679   }
10680   else if (game_status == GAME_MODE_SETUP)
10681   {
10682     // when adding new artwork set in setup menu, set cursor and update screen
10683
10684     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
10685         tree_type == TREE_TYPE_GRAPHICS_DIR)
10686     {
10687       artwork.gfx_current = tree_node_new;
10688
10689       DrawChooseTree(&artwork.gfx_current);
10690     }
10691     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
10692              tree_type == TREE_TYPE_SOUNDS_DIR)
10693     {
10694       artwork.snd_current = tree_node_new;
10695
10696       DrawChooseTree(&artwork.snd_current);
10697     }
10698     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
10699              tree_type == TREE_TYPE_MUSIC_DIR)
10700     {
10701       artwork.mus_current = tree_node_new;
10702
10703       DrawChooseTree(&artwork.mus_current);
10704     }
10705   }
10706 }
10707
10708 static int UploadTapes(void)
10709 {
10710   SetGameStatus(GAME_MODE_LOADING);
10711
10712   FadeSetEnterScreen();
10713   FadeOut(REDRAW_ALL);
10714
10715   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
10716
10717   FadeIn(REDRAW_ALL);
10718
10719   DrawInitTextHead("Uploading tapes");
10720
10721   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
10722   global.autoplay_leveldir = "ALL";
10723   global.autoplay_all = TRUE;
10724
10725   int num_tapes_uploaded = AutoPlayTapes();
10726
10727   global.autoplay_mode = AUTOPLAY_MODE_NONE;
10728   global.autoplay_leveldir = NULL;
10729   global.autoplay_all = FALSE;
10730
10731   SetGameStatus(GAME_MODE_MAIN);
10732
10733   DrawMainMenu();
10734
10735   return num_tapes_uploaded;
10736 }
10737
10738 static boolean OfferUploadTapes(void)
10739 {
10740   if (!Request(setup.has_remaining_tapes ?
10741                "Upload missing tapes to the high score server now?" :
10742                "Upload all your tapes to the high score server now?", REQ_ASK))
10743     return FALSE;
10744
10745   int num_tapes_uploaded = UploadTapes();
10746   char message[100];
10747
10748   if (num_tapes_uploaded < 0)
10749   {
10750     num_tapes_uploaded = -num_tapes_uploaded - 1;
10751
10752     if (num_tapes_uploaded == 0)
10753       sprintf(message, "Upload failed! No tapes uploaded!");
10754     else if (num_tapes_uploaded == 1)
10755       sprintf(message, "Upload failed! Only 1 tape uploaded!");
10756     else
10757       sprintf(message, "Upload failed! Only %d tapes uploaded!",
10758               num_tapes_uploaded);
10759
10760     Request(message, REQ_CONFIRM);
10761
10762     // if uploading tapes failed, add tape upload entry to setup menu
10763     setup.provide_uploading_tapes = TRUE;
10764     setup.has_remaining_tapes = TRUE;
10765
10766     SaveSetup_ServerSetup();
10767
10768     return FALSE;
10769   }
10770
10771   if (num_tapes_uploaded == 0)
10772     sprintf(message, "No tapes uploaded!");
10773   else if (num_tapes_uploaded == 1)
10774     sprintf(message, "1 tape uploaded!");
10775   else
10776     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
10777
10778   Request(message, REQ_CONFIRM);
10779
10780   if (num_tapes_uploaded > 0)
10781     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
10782
10783   // after all tapes have been uploaded, remove entry from setup menu
10784   setup.provide_uploading_tapes = FALSE;
10785   setup.has_remaining_tapes = FALSE;
10786
10787   SaveSetup_ServerSetup();
10788
10789   return TRUE;
10790 }
10791
10792 static void CheckUploadTapes(void)
10793 {
10794   if (!setup.ask_for_uploading_tapes)
10795     return;
10796
10797   // after asking for uploading tapes, do not ask again
10798   setup.ask_for_uploading_tapes = FALSE;
10799   setup.ask_for_remaining_tapes = FALSE;
10800
10801   if (directoryExists(getTapeDir(NULL)))
10802   {
10803     boolean tapes_uploaded = OfferUploadTapes();
10804
10805     if (!tapes_uploaded)
10806     {
10807       Request(setup.has_remaining_tapes ?
10808               "You can upload missing tapes from the setup menu later!" :
10809               "You can upload your tapes from the setup menu later!",
10810               REQ_CONFIRM);
10811     }
10812   }
10813   else
10814   {
10815     // if tapes directory does not exist yet, never offer uploading all tapes
10816     setup.provide_uploading_tapes = FALSE;
10817   }
10818
10819   SaveSetup_ServerSetup();
10820 }
10821
10822 static void UpgradePlayerUUID(void)
10823 {
10824   ApiResetUUIDAsThread(getUUID());
10825 }
10826
10827 static void CheckUpgradePlayerUUID(void)
10828 {
10829   if (setup.player_version > 1)
10830     return;
10831
10832   UpgradePlayerUUID();
10833 }
10834
10835 void CheckApiServerTasks(void)
10836 {
10837   // check if the player's UUID has to be upgraded
10838   CheckUpgradePlayerUUID();
10839
10840   // check if there are any tapes to be uploaded
10841   CheckUploadTapes();
10842 }