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