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