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