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