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