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