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