fixed bug with not unmapping gadgets from previous screen on score info
[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   UnmapAllGadgets();
5873
5874   FadeOut(REDRAW_FIELD);
5875
5876   ClearField();
5877
5878   drawChooseTreeHead(score_entries);
5879   drawChooseTreeInfo(score_entries);
5880
5881   DrawTextSCentered(ystart, font_title, "Score Information:");
5882   ystart += ystep_title;
5883
5884   DrawTextF(xstart1, ystart, font_head, "Level Set");
5885   DrawTextF(xstart2, ystart, font_text, leveldir_current->name);
5886   ystart += ystep_line;
5887
5888   DrawTextF(xstart1, ystart, font_head, "Level Name");
5889   DrawTextF(xstart2, ystart, font_text, level.name);
5890   ystart += ystep_para;
5891
5892   DrawTextF(xstart1, ystart, font_head, "Player");
5893   DrawTextF(xstart2, ystart, font_text, entry->name);
5894   ystart += ystep_line;
5895
5896   if (level.use_step_counter)
5897   {
5898     DrawTextF(xstart1, ystart, font_head, "Steps");
5899     DrawTextF(xstart2, ystart, font_text, int2str(entry->time, 5));
5900     ystart += ystep_line;
5901   }
5902   else
5903   {
5904     DrawTextF(xstart1, ystart, font_head, "Time");
5905     DrawTextF(xstart2, ystart, font_text, getHallOfFameTimeText(pos));
5906     ystart += ystep_line;
5907   }
5908
5909   if (!level.rate_time_over_score || entry->score > 0)
5910   {
5911     DrawTextF(xstart1, ystart, font_head, "Score");
5912     DrawTextF(xstart2, ystart, font_text, int2str(entry->score, 5));
5913     ystart += ystep_line;
5914   }
5915
5916   DrawTextSCentered(ybottom, font_foot, "Press any key or button to go back");
5917
5918   FadeIn(REDRAW_FIELD);
5919 }
5920
5921 void HandleScoreInfo(int mx, int my, int dx, int dy, int button)
5922 {
5923   if (button == MB_MENU_LEAVE || button == MB_MENU_CHOICE)
5924   {
5925     PlaySound(SND_MENU_ITEM_SELECTING);
5926
5927     SetGameStatus(GAME_MODE_SCORES);
5928
5929     DrawHallOfFame(level_nr);
5930   }
5931 }
5932
5933
5934 // ============================================================================
5935 // setup screen functions
5936 // ============================================================================
5937
5938 static struct TokenInfo *setup_info;
5939 static int num_setup_info;      // number of setup entries shown on screen
5940 static int max_setup_info;      // total number of setup entries in list
5941
5942 static char *window_size_text;
5943 static char *scaling_type_text;
5944 static char *rendering_mode_text;
5945 static char *vsync_mode_text;
5946 static char *scroll_delay_text;
5947 static char *snapshot_mode_text;
5948 static char *game_speed_text;
5949 static char *scores_type_text;
5950 static char *network_server_text;
5951 static char *graphics_set_name;
5952 static char *sounds_set_name;
5953 static char *music_set_name;
5954 static char *volume_simple_text;
5955 static char *volume_loops_text;
5956 static char *volume_music_text;
5957 static char *touch_controls_text;
5958 static char *move_distance_text;
5959 static char *drop_distance_text;
5960 static char *transparency_text;
5961 static char *grid_size_text[2][2];
5962
5963 static void execSetupMain(void)
5964 {
5965   setup_mode = SETUP_MODE_MAIN;
5966
5967   DrawSetupScreen();
5968 }
5969
5970 static void execSetupGame_setScoresType(void)
5971 {
5972   if (scores_types == NULL)
5973   {
5974     int i;
5975
5976     for (i = 0; scores_types_list[i].value != NULL; i++)
5977     {
5978       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5979       char identifier[32], name[32];
5980       char *value = scores_types_list[i].value;
5981       char *text = scores_types_list[i].text;
5982
5983       ti->node_top = &scores_types;
5984       ti->sort_priority = i;
5985
5986       sprintf(identifier, "%s", value);
5987       sprintf(name, "%s", text);
5988
5989       setString(&ti->identifier, identifier);
5990       setString(&ti->name, name);
5991       setString(&ti->name_sorting, name);
5992       setString(&ti->infotext, STR_SETUP_CHOOSE_SCORES_TYPE);
5993
5994       pushTreeInfo(&scores_types, ti);
5995     }
5996
5997     // sort scores type values to start with lowest scores type value
5998     sortTreeInfo(&scores_types);
5999
6000     // set current scores type value to configured scores type value
6001     scores_type_current =
6002       getTreeInfoFromIdentifier(scores_types, setup.scores_in_highscore_list);
6003
6004     // if that fails, set current scores type to reliable default value
6005     if (scores_type_current == NULL)
6006       scores_type_current =
6007         getTreeInfoFromIdentifier(scores_types, STR_SCORES_TYPE_DEFAULT);
6008
6009     // if that also fails, set current scores type to first available value
6010     if (scores_type_current == NULL)
6011       scores_type_current = scores_types;
6012   }
6013
6014   setup.scores_in_highscore_list = scores_type_current->identifier;
6015
6016   // needed for displaying scores type text instead of identifier
6017   scores_type_text = scores_type_current->name;
6018 }
6019
6020 static void execSetupGame_setGameSpeeds(boolean update_value)
6021 {
6022   if (setup.game_speed_extended)
6023   {
6024     game_speeds_list = game_speeds_list_extended;
6025     game_speeds      = game_speeds_extended;
6026   }
6027   else
6028   {
6029     game_speeds_list = game_speeds_list_normal;
6030     game_speeds      = game_speeds_normal;
6031   }
6032
6033   if (game_speeds == NULL)
6034   {
6035     int i;
6036
6037     for (i = 0; game_speeds_list[i].value != -1; i++)
6038     {
6039       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6040       char identifier[32], name[32];
6041       int value = game_speeds_list[i].value;
6042       char *text = game_speeds_list[i].text;
6043
6044       ti->node_top = &game_speeds;
6045       ti->sort_priority = 10000 - value;
6046
6047       sprintf(identifier, "%d", value);
6048       sprintf(name, "%s", text);
6049
6050       setString(&ti->identifier, identifier);
6051       setString(&ti->name, name);
6052       setString(&ti->name_sorting, name);
6053       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_SPEED);
6054
6055       pushTreeInfo(&game_speeds, ti);
6056     }
6057
6058     // sort game speed values to start with slowest game speed
6059     sortTreeInfo(&game_speeds);
6060
6061     update_value = TRUE;
6062   }
6063
6064   if (update_value)
6065   {
6066     // set current game speed to configured game speed value
6067     game_speed_current =
6068       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
6069
6070     // if that fails, set current game speed to reliable default value
6071     if (game_speed_current == NULL)
6072       game_speed_current =
6073         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
6074
6075     // if that also fails, set current game speed to first available speed
6076     if (game_speed_current == NULL)
6077       game_speed_current = game_speeds;
6078
6079     if (setup.game_speed_extended)
6080       game_speeds_extended = game_speeds;
6081     else
6082       game_speeds_normal = game_speeds;
6083   }
6084
6085   setup.game_frame_delay = atoi(game_speed_current->identifier);
6086
6087   // needed for displaying game speed text instead of identifier
6088   game_speed_text = game_speed_current->name;
6089 }
6090
6091 static void execSetupGame_setScrollDelays(void)
6092 {
6093   if (scroll_delays == NULL)
6094   {
6095     int i;
6096
6097     for (i = 0; scroll_delays_list[i].value != -1; i++)
6098     {
6099       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6100       char identifier[32], name[32];
6101       int value = scroll_delays_list[i].value;
6102       char *text = scroll_delays_list[i].text;
6103
6104       ti->node_top = &scroll_delays;
6105       ti->sort_priority = value;
6106
6107       sprintf(identifier, "%d", value);
6108       sprintf(name, "%s", text);
6109
6110       setString(&ti->identifier, identifier);
6111       setString(&ti->name, name);
6112       setString(&ti->name_sorting, name);
6113       setString(&ti->infotext, STR_SETUP_CHOOSE_SCROLL_DELAY);
6114
6115       pushTreeInfo(&scroll_delays, ti);
6116     }
6117
6118     // sort scroll delay values to start with lowest scroll delay value
6119     sortTreeInfo(&scroll_delays);
6120
6121     // set current scroll delay value to configured scroll delay value
6122     scroll_delay_current =
6123       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
6124
6125     // if that fails, set current scroll delay to reliable default value
6126     if (scroll_delay_current == NULL)
6127       scroll_delay_current =
6128         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
6129
6130     // if that also fails, set current scroll delay to first available value
6131     if (scroll_delay_current == NULL)
6132       scroll_delay_current = scroll_delays;
6133   }
6134
6135   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
6136
6137   // needed for displaying scroll delay text instead of identifier
6138   scroll_delay_text = scroll_delay_current->name;
6139 }
6140
6141 static void execSetupGame_setSnapshotModes(void)
6142 {
6143   if (snapshot_modes == NULL)
6144   {
6145     int i;
6146
6147     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
6148     {
6149       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6150       char identifier[32], name[32];
6151       char *value = snapshot_modes_list[i].value;
6152       char *text = snapshot_modes_list[i].text;
6153
6154       ti->node_top = &snapshot_modes;
6155       ti->sort_priority = i;
6156
6157       sprintf(identifier, "%s", value);
6158       sprintf(name, "%s", text);
6159
6160       setString(&ti->identifier, identifier);
6161       setString(&ti->name, name);
6162       setString(&ti->name_sorting, name);
6163       setString(&ti->infotext, STR_SETUP_CHOOSE_SNAPSHOT_MODE);
6164
6165       pushTreeInfo(&snapshot_modes, ti);
6166     }
6167
6168     // sort snapshot mode values to start with lowest snapshot mode value
6169     sortTreeInfo(&snapshot_modes);
6170
6171     // set current snapshot mode value to configured snapshot mode value
6172     snapshot_mode_current =
6173       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
6174
6175     // if that fails, set current snapshot mode to reliable default value
6176     if (snapshot_mode_current == NULL)
6177       snapshot_mode_current =
6178         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
6179
6180     // if that also fails, set current snapshot mode to first available value
6181     if (snapshot_mode_current == NULL)
6182       snapshot_mode_current = snapshot_modes;
6183   }
6184
6185   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
6186
6187   // needed for displaying snapshot mode text instead of identifier
6188   snapshot_mode_text = snapshot_mode_current->name;
6189 }
6190
6191 static void execSetupGame_setNetworkServerText(void)
6192 {
6193   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
6194   {
6195     strcpy(network_server_hostname, STR_NETWORK_AUTO_DETECT_SETUP);
6196   }
6197   else
6198   {
6199     strncpy(network_server_hostname, setup.network_server_hostname,
6200             MAX_SETUP_TEXT_INPUT_LEN);
6201     network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN] = '\0';
6202   }
6203
6204   // needed for displaying network server text instead of identifier
6205   network_server_text = network_server_hostname;
6206 }
6207
6208 static void execSetupGame(void)
6209 {
6210   boolean check_vsync_mode = (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED);
6211
6212   execSetupGame_setGameSpeeds(FALSE);
6213   execSetupGame_setScoresType();
6214   execSetupGame_setScrollDelays();
6215   execSetupGame_setSnapshotModes();
6216
6217   execSetupGame_setNetworkServerText();
6218
6219   if (!setup.provide_uploading_tapes)
6220     setHideSetupEntry(execOfferUploadTapes);
6221
6222   setup_mode = SETUP_MODE_GAME;
6223
6224   DrawSetupScreen();
6225
6226   // check if vsync needs to be disabled for this game speed to work
6227   if (check_vsync_mode)
6228     DisableVsyncIfNeeded();
6229 }
6230
6231 static void execSetupChooseScoresType(void)
6232 {
6233   setup_mode = SETUP_MODE_CHOOSE_SCORES_TYPE;
6234
6235   DrawSetupScreen();
6236 }
6237
6238 static void execSetupChooseGameSpeed(void)
6239 {
6240   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
6241
6242   DrawSetupScreen();
6243 }
6244
6245 static void execSetupChooseScrollDelay(void)
6246 {
6247   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
6248
6249   DrawSetupScreen();
6250 }
6251
6252 static void execSetupChooseSnapshotMode(void)
6253 {
6254   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
6255
6256   DrawSetupScreen();
6257 }
6258
6259 static void execSetupEngines(void)
6260 {
6261   setup_mode = SETUP_MODE_ENGINES;
6262
6263   DrawSetupScreen();
6264 }
6265
6266 static void execSetupEditor(void)
6267 {
6268   setup_mode = SETUP_MODE_EDITOR;
6269
6270   DrawSetupScreen();
6271 }
6272
6273 static void execSetupGraphics_setWindowSizes(boolean update_list)
6274 {
6275   if (window_sizes != NULL && update_list)
6276   {
6277     freeTreeInfo(window_sizes);
6278
6279     window_sizes = NULL;
6280   }
6281
6282   if (window_sizes == NULL)
6283   {
6284     boolean current_window_size_found = FALSE;
6285     int i;
6286
6287     for (i = 0; window_sizes_list[i].value != -1; i++)
6288     {
6289       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6290       char identifier[32], name[32];
6291       int value = window_sizes_list[i].value;
6292       char *text = window_sizes_list[i].text;
6293
6294       ti->node_top = &window_sizes;
6295       ti->sort_priority = value;
6296
6297       sprintf(identifier, "%d", value);
6298       sprintf(name, "%s", text);
6299
6300       setString(&ti->identifier, identifier);
6301       setString(&ti->name, name);
6302       setString(&ti->name_sorting, name);
6303       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6304
6305       pushTreeInfo(&window_sizes, ti);
6306
6307       if (value == setup.window_scaling_percent)
6308         current_window_size_found = TRUE;
6309     }
6310
6311     if (!current_window_size_found)
6312     {
6313       // add entry for non-preset window scaling value
6314
6315       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6316       char identifier[32], name[32];
6317       int value = setup.window_scaling_percent;
6318
6319       ti->node_top = &window_sizes;
6320       ti->sort_priority = value;
6321
6322       sprintf(identifier, "%d", value);
6323       sprintf(name, "%d %% (Current)", value);
6324
6325       setString(&ti->identifier, identifier);
6326       setString(&ti->name, name);
6327       setString(&ti->name_sorting, name);
6328       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6329
6330       pushTreeInfo(&window_sizes, ti);
6331     }
6332
6333     // sort window size values to start with lowest window size value
6334     sortTreeInfo(&window_sizes);
6335
6336     // set current window size value to configured window size value
6337     window_size_current =
6338       getTreeInfoFromIdentifier(window_sizes,
6339                                 i_to_a(setup.window_scaling_percent));
6340
6341     // if that fails, set current window size to reliable default value
6342     if (window_size_current == NULL)
6343       window_size_current =
6344         getTreeInfoFromIdentifier(window_sizes,
6345                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
6346
6347     // if that also fails, set current window size to first available value
6348     if (window_size_current == NULL)
6349       window_size_current = window_sizes;
6350   }
6351
6352   setup.window_scaling_percent = atoi(window_size_current->identifier);
6353
6354   // needed for displaying window size text instead of identifier
6355   window_size_text = window_size_current->name;
6356 }
6357
6358 static void execSetupGraphics_setScalingTypes(void)
6359 {
6360   if (scaling_types == NULL)
6361   {
6362     int i;
6363
6364     for (i = 0; scaling_types_list[i].value != NULL; i++)
6365     {
6366       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6367       char identifier[32], name[32];
6368       char *value = scaling_types_list[i].value;
6369       char *text = scaling_types_list[i].text;
6370
6371       ti->node_top = &scaling_types;
6372       ti->sort_priority = i;
6373
6374       sprintf(identifier, "%s", value);
6375       sprintf(name, "%s", text);
6376
6377       setString(&ti->identifier, identifier);
6378       setString(&ti->name, name);
6379       setString(&ti->name_sorting, name);
6380       setString(&ti->infotext, STR_SETUP_CHOOSE_SCALING_TYPE);
6381
6382       pushTreeInfo(&scaling_types, ti);
6383     }
6384
6385     // sort scaling type values to start with lowest scaling type value
6386     sortTreeInfo(&scaling_types);
6387
6388     // set current scaling type value to configured scaling type value
6389     scaling_type_current =
6390       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
6391
6392     // if that fails, set current scaling type to reliable default value
6393     if (scaling_type_current == NULL)
6394       scaling_type_current =
6395         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
6396
6397     // if that also fails, set current scaling type to first available value
6398     if (scaling_type_current == NULL)
6399       scaling_type_current = scaling_types;
6400   }
6401
6402   setup.window_scaling_quality = scaling_type_current->identifier;
6403
6404   // needed for displaying scaling type text instead of identifier
6405   scaling_type_text = scaling_type_current->name;
6406 }
6407
6408 static void execSetupGraphics_setRenderingModes(void)
6409 {
6410   if (rendering_modes == NULL)
6411   {
6412     int i;
6413
6414     for (i = 0; rendering_modes_list[i].value != NULL; i++)
6415     {
6416       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6417       char identifier[32], name[32];
6418       char *value = rendering_modes_list[i].value;
6419       char *text = rendering_modes_list[i].text;
6420
6421       ti->node_top = &rendering_modes;
6422       ti->sort_priority = i;
6423
6424       sprintf(identifier, "%s", value);
6425       sprintf(name, "%s", text);
6426
6427       setString(&ti->identifier, identifier);
6428       setString(&ti->name, name);
6429       setString(&ti->name_sorting, name);
6430       setString(&ti->infotext, STR_SETUP_CHOOSE_RENDERING);
6431
6432       pushTreeInfo(&rendering_modes, ti);
6433     }
6434
6435     // sort rendering mode values to start with lowest rendering mode value
6436     sortTreeInfo(&rendering_modes);
6437
6438     // set current rendering mode value to configured rendering mode value
6439     rendering_mode_current =
6440       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
6441
6442     // if that fails, set current rendering mode to reliable default value
6443     if (rendering_mode_current == NULL)
6444       rendering_mode_current =
6445         getTreeInfoFromIdentifier(rendering_modes,
6446                                   STR_SPECIAL_RENDERING_DEFAULT);
6447
6448     // if that also fails, set current rendering mode to first available one
6449     if (rendering_mode_current == NULL)
6450       rendering_mode_current = rendering_modes;
6451   }
6452
6453   setup.screen_rendering_mode = rendering_mode_current->identifier;
6454
6455   // needed for displaying rendering mode text instead of identifier
6456   rendering_mode_text = rendering_mode_current->name;
6457 }
6458
6459 static void execSetupGraphics_setVsyncModes(boolean update_value)
6460 {
6461   if (vsync_modes == NULL)
6462   {
6463     int i;
6464
6465     for (i = 0; vsync_modes_list[i].value != NULL; i++)
6466     {
6467       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6468       char identifier[32], name[32];
6469       char *value = vsync_modes_list[i].value;
6470       char *text = vsync_modes_list[i].text;
6471
6472       ti->node_top = &vsync_modes;
6473       ti->sort_priority = i;
6474
6475       sprintf(identifier, "%s", value);
6476       sprintf(name, "%s", text);
6477
6478       setString(&ti->identifier, identifier);
6479       setString(&ti->name, name);
6480       setString(&ti->name_sorting, name);
6481       setString(&ti->infotext, STR_SETUP_CHOOSE_VSYNC);
6482
6483       pushTreeInfo(&vsync_modes, ti);
6484     }
6485
6486     // sort vsync mode values to start with lowest vsync mode value
6487     sortTreeInfo(&vsync_modes);
6488
6489     update_value = TRUE;
6490   }
6491
6492   if (update_value)
6493   {
6494     // set current vsync mode value to configured vsync mode value
6495     vsync_mode_current =
6496       getTreeInfoFromIdentifier(vsync_modes, setup.vsync_mode);
6497
6498     // if that fails, set current vsync mode to reliable default value
6499     if (vsync_mode_current == NULL)
6500       vsync_mode_current =
6501         getTreeInfoFromIdentifier(vsync_modes, STR_VSYNC_MODE_DEFAULT);
6502
6503     // if that also fails, set current vsync mode to first available one
6504     if (vsync_mode_current == NULL)
6505       vsync_mode_current = vsync_modes;
6506   }
6507
6508   setup.vsync_mode = vsync_mode_current->identifier;
6509
6510   // needed for displaying vsync mode text instead of identifier
6511   vsync_mode_text = vsync_mode_current->name;
6512 }
6513
6514 static void execSetupGraphics(void)
6515 {
6516   boolean check_game_speed = (setup_mode == SETUP_MODE_CHOOSE_VSYNC);
6517
6518   // update "setup.window_scaling_percent" from list selection
6519   // (in this case, window scaling was changed on setup screen)
6520   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6521     execSetupGraphics_setWindowSizes(FALSE);
6522
6523   // update "setup.vsync_mode" from list selection
6524   // (in this case, vsync mode was changed on setup screen)
6525   if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
6526     execSetupGraphics_setVsyncModes(FALSE);
6527
6528   // update list selection from "setup.window_scaling_percent"
6529   // (window scaling may have changed by resizing the window)
6530   execSetupGraphics_setWindowSizes(TRUE);
6531
6532   // update list selection from "setup.vsync_mode"
6533   // (vsync_mode may have changed by re-creating the renderer)
6534   execSetupGraphics_setVsyncModes(TRUE);
6535
6536   execSetupGraphics_setScalingTypes();
6537   execSetupGraphics_setRenderingModes();
6538
6539   setup_mode = SETUP_MODE_GRAPHICS;
6540
6541   DrawSetupScreen();
6542
6543   // check if game speed is high enough for 60 Hz vsync to work
6544   if (check_game_speed)
6545     ModifyGameSpeedIfNeeded();
6546
6547   // window scaling may have changed at this point
6548   ChangeWindowScalingIfNeeded();
6549
6550   // window scaling quality may have changed at this point
6551   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
6552     SDLSetWindowScalingQuality(setup.window_scaling_quality);
6553
6554   // screen rendering mode may have changed at this point
6555   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
6556
6557   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
6558   int video_vsync_mode = video.vsync_mode;
6559
6560   // screen vsync mode may have changed at this point
6561   ChangeVsyncModeIfNeeded();
6562
6563   // check if setting vsync mode to selected value failed
6564   if (setup_vsync_mode != video_vsync_mode &&
6565       setup_vsync_mode != video.vsync_mode)
6566   {
6567     // changing vsync mode to selected value failed -- reset displayed value
6568     execSetupGraphics_setVsyncModes(TRUE);
6569
6570     Request("Setting VSync failed!", REQ_CONFIRM);
6571
6572     DrawSetupScreen();
6573   }
6574 }
6575
6576 static void execSetupChooseWindowSize(void)
6577 {
6578   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
6579
6580   DrawSetupScreen();
6581 }
6582
6583 static void execSetupChooseScalingType(void)
6584 {
6585   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
6586
6587   DrawSetupScreen();
6588 }
6589
6590 static void execSetupChooseRenderingMode(void)
6591 {
6592   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
6593
6594   DrawSetupScreen();
6595 }
6596
6597 static void execSetupChooseVsyncMode(void)
6598 {
6599   setup_mode = SETUP_MODE_CHOOSE_VSYNC;
6600
6601   DrawSetupScreen();
6602 }
6603
6604 static void execSetupChooseVolumeSimple(void)
6605 {
6606   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
6607
6608   DrawSetupScreen();
6609 }
6610
6611 static void execSetupChooseVolumeLoops(void)
6612 {
6613   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
6614
6615   DrawSetupScreen();
6616 }
6617
6618 static void execSetupChooseVolumeMusic(void)
6619 {
6620   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
6621
6622   DrawSetupScreen();
6623 }
6624
6625 static void execSetupSound(void)
6626 {
6627   if (volumes_simple == NULL)
6628   {
6629     boolean current_volume_simple_found = FALSE;
6630     int i;
6631
6632     for (i = 0; volumes_list[i].value != -1; i++)
6633     {
6634       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6635       char identifier[32], name[32];
6636       int value = volumes_list[i].value;
6637       char *text = volumes_list[i].text;
6638
6639       ti->node_top = &volumes_simple;
6640       ti->sort_priority = value;
6641
6642       sprintf(identifier, "%d", value);
6643       sprintf(name, "%s", text);
6644
6645       setString(&ti->identifier, identifier);
6646       setString(&ti->name, name);
6647       setString(&ti->name_sorting, name);
6648       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6649
6650       pushTreeInfo(&volumes_simple, ti);
6651
6652       if (value == setup.volume_simple)
6653         current_volume_simple_found = TRUE;
6654     }
6655
6656     if (!current_volume_simple_found)
6657     {
6658       // add entry for non-preset volume value
6659
6660       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6661       char identifier[32], name[32];
6662       int value = setup.volume_simple;
6663
6664       ti->node_top = &volumes_simple;
6665       ti->sort_priority = value;
6666
6667       sprintf(identifier, "%d", value);
6668       sprintf(name, "%d %% (Current)", value);
6669
6670       setString(&ti->identifier, identifier);
6671       setString(&ti->name, name);
6672       setString(&ti->name_sorting, name);
6673       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6674
6675       pushTreeInfo(&volumes_simple, ti);
6676     }
6677
6678     // sort volume values to start with lowest volume value
6679     sortTreeInfo(&volumes_simple);
6680
6681     // set current volume value to configured volume value
6682     volume_simple_current =
6683       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
6684
6685     // if that fails, set current volume to reliable default value
6686     if (volume_simple_current == NULL)
6687       volume_simple_current =
6688         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
6689
6690     // if that also fails, set current volume to first available value
6691     if (volume_simple_current == NULL)
6692       volume_simple_current = volumes_simple;
6693   }
6694
6695   if (volumes_loops == NULL)
6696   {
6697     boolean current_volume_loops_found = FALSE;
6698     int i;
6699
6700     for (i = 0; volumes_list[i].value != -1; i++)
6701     {
6702       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6703       char identifier[32], name[32];
6704       int value = volumes_list[i].value;
6705       char *text = volumes_list[i].text;
6706
6707       ti->node_top = &volumes_loops;
6708       ti->sort_priority = value;
6709
6710       sprintf(identifier, "%d", value);
6711       sprintf(name, "%s", text);
6712
6713       setString(&ti->identifier, identifier);
6714       setString(&ti->name, name);
6715       setString(&ti->name_sorting, name);
6716       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6717
6718       pushTreeInfo(&volumes_loops, ti);
6719
6720       if (value == setup.volume_loops)
6721         current_volume_loops_found = TRUE;
6722     }
6723
6724     if (!current_volume_loops_found)
6725     {
6726       // add entry for non-preset volume value
6727
6728       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6729       char identifier[32], name[32];
6730       int value = setup.volume_loops;
6731
6732       ti->node_top = &volumes_loops;
6733       ti->sort_priority = value;
6734
6735       sprintf(identifier, "%d", value);
6736       sprintf(name, "%d %% (Current)", value);
6737
6738       setString(&ti->identifier, identifier);
6739       setString(&ti->name, name);
6740       setString(&ti->name_sorting, name);
6741       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6742
6743       pushTreeInfo(&volumes_loops, ti);
6744     }
6745
6746     // sort volume values to start with lowest volume value
6747     sortTreeInfo(&volumes_loops);
6748
6749     // set current volume value to configured volume value
6750     volume_loops_current =
6751       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
6752
6753     // if that fails, set current volume to reliable default value
6754     if (volume_loops_current == NULL)
6755       volume_loops_current =
6756         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
6757
6758     // if that also fails, set current volume to first available value
6759     if (volume_loops_current == NULL)
6760       volume_loops_current = volumes_loops;
6761   }
6762
6763   if (volumes_music == NULL)
6764   {
6765     boolean current_volume_music_found = FALSE;
6766     int i;
6767
6768     for (i = 0; volumes_list[i].value != -1; i++)
6769     {
6770       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6771       char identifier[32], name[32];
6772       int value = volumes_list[i].value;
6773       char *text = volumes_list[i].text;
6774
6775       ti->node_top = &volumes_music;
6776       ti->sort_priority = value;
6777
6778       sprintf(identifier, "%d", value);
6779       sprintf(name, "%s", text);
6780
6781       setString(&ti->identifier, identifier);
6782       setString(&ti->name, name);
6783       setString(&ti->name_sorting, name);
6784       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6785
6786       pushTreeInfo(&volumes_music, ti);
6787
6788       if (value == setup.volume_music)
6789         current_volume_music_found = TRUE;
6790     }
6791
6792     if (!current_volume_music_found)
6793     {
6794       // add entry for non-preset volume value
6795
6796       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6797       char identifier[32], name[32];
6798       int value = setup.volume_music;
6799
6800       ti->node_top = &volumes_music;
6801       ti->sort_priority = value;
6802
6803       sprintf(identifier, "%d", value);
6804       sprintf(name, "%d %% (Current)", value);
6805
6806       setString(&ti->identifier, identifier);
6807       setString(&ti->name, name);
6808       setString(&ti->name_sorting, name);
6809       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6810
6811       pushTreeInfo(&volumes_music, ti);
6812     }
6813
6814     // sort volume values to start with lowest volume value
6815     sortTreeInfo(&volumes_music);
6816
6817     // set current volume value to configured volume value
6818     volume_music_current =
6819       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
6820
6821     // if that fails, set current volume to reliable default value
6822     if (volume_music_current == NULL)
6823       volume_music_current =
6824         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
6825
6826     // if that also fails, set current volume to first available value
6827     if (volume_music_current == NULL)
6828       volume_music_current = volumes_music;
6829   }
6830
6831   setup.volume_simple = atoi(volume_simple_current->identifier);
6832   setup.volume_loops  = atoi(volume_loops_current->identifier);
6833   setup.volume_music  = atoi(volume_music_current->identifier);
6834
6835   // needed for displaying volume text instead of identifier
6836   volume_simple_text = volume_simple_current->name;
6837   volume_loops_text = volume_loops_current->name;
6838   volume_music_text = volume_music_current->name;
6839
6840   setup_mode = SETUP_MODE_SOUND;
6841
6842   DrawSetupScreen();
6843 }
6844
6845 static void execSetupChooseTouchControls(void)
6846 {
6847   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
6848
6849   DrawSetupScreen();
6850 }
6851
6852 static void execSetupChooseMoveDistance(void)
6853 {
6854   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
6855
6856   DrawSetupScreen();
6857 }
6858
6859 static void execSetupChooseDropDistance(void)
6860 {
6861   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
6862
6863   DrawSetupScreen();
6864 }
6865
6866 static void execSetupChooseTransparency(void)
6867 {
6868   setup_mode = SETUP_MODE_CHOOSE_TRANSPARENCY;
6869
6870   DrawSetupScreen();
6871 }
6872
6873 static void execSetupChooseGridXSize_0(void)
6874 {
6875   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_0;
6876
6877   DrawSetupScreen();
6878 }
6879
6880 static void execSetupChooseGridYSize_0(void)
6881 {
6882   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_0;
6883
6884   DrawSetupScreen();
6885 }
6886
6887 static void execSetupChooseGridXSize_1(void)
6888 {
6889   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_1;
6890
6891   DrawSetupScreen();
6892 }
6893
6894 static void execSetupChooseGridYSize_1(void)
6895 {
6896   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_1;
6897
6898   DrawSetupScreen();
6899 }
6900
6901 static void execSetupConfigureVirtualButtons(void)
6902 {
6903   setup_mode = SETUP_MODE_CONFIG_VIRT_BUTTONS;
6904
6905   ConfigureVirtualButtons();
6906
6907   setup_mode = SETUP_MODE_TOUCH;
6908
6909   DrawSetupScreen();
6910 }
6911
6912 static void execSetupTouch(void)
6913 {
6914   int i, j, k;
6915
6916   if (touch_controls == NULL)
6917   {
6918     for (i = 0; touch_controls_list[i].value != NULL; i++)
6919     {
6920       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6921       char identifier[32], name[32];
6922       char *value = touch_controls_list[i].value;
6923       char *text = touch_controls_list[i].text;
6924
6925       ti->node_top = &touch_controls;
6926       ti->sort_priority = i;
6927
6928       sprintf(identifier, "%s", value);
6929       sprintf(name, "%s", text);
6930
6931       setString(&ti->identifier, identifier);
6932       setString(&ti->name, name);
6933       setString(&ti->name_sorting, name);
6934       setString(&ti->infotext, STR_SETUP_CHOOSE_TOUCH_CONTROL);
6935
6936       pushTreeInfo(&touch_controls, ti);
6937     }
6938
6939     // sort touch control values to start with lowest touch control value
6940     sortTreeInfo(&touch_controls);
6941
6942     // set current touch control value to configured touch control value
6943     touch_control_current =
6944       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
6945
6946     // if that fails, set current touch control to reliable default value
6947     if (touch_control_current == NULL)
6948       touch_control_current =
6949         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
6950
6951     // if that also fails, set current touch control to first available value
6952     if (touch_control_current == NULL)
6953       touch_control_current = touch_controls;
6954   }
6955
6956   if (move_distances == NULL)
6957   {
6958     for (i = 0; distances_list[i].value != -1; i++)
6959     {
6960       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6961       char identifier[32], name[32];
6962       int value = distances_list[i].value;
6963       char *text = distances_list[i].text;
6964
6965       ti->node_top = &move_distances;
6966       ti->sort_priority = value;
6967
6968       sprintf(identifier, "%d", value);
6969       sprintf(name, "%s", text);
6970
6971       setString(&ti->identifier, identifier);
6972       setString(&ti->name, name);
6973       setString(&ti->name_sorting, name);
6974       setString(&ti->infotext, STR_SETUP_CHOOSE_MOVE_DISTANCE);
6975
6976       pushTreeInfo(&move_distances, ti);
6977     }
6978
6979     // sort distance values to start with lowest distance value
6980     sortTreeInfo(&move_distances);
6981
6982     // set current distance value to configured distance value
6983     move_distance_current =
6984       getTreeInfoFromIdentifier(move_distances,
6985                                 i_to_a(setup.touch.move_distance));
6986
6987     // if that fails, set current distance to reliable default value
6988     if (move_distance_current == NULL)
6989       move_distance_current =
6990         getTreeInfoFromIdentifier(move_distances,
6991                                   i_to_a(TOUCH_MOVE_DISTANCE_DEFAULT));
6992
6993     // if that also fails, set current distance to first available value
6994     if (move_distance_current == NULL)
6995       move_distance_current = move_distances;
6996   }
6997
6998   if (drop_distances == NULL)
6999   {
7000     for (i = 0; distances_list[i].value != -1; i++)
7001     {
7002       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7003       char identifier[32], name[32];
7004       int value = distances_list[i].value;
7005       char *text = distances_list[i].text;
7006
7007       ti->node_top = &drop_distances;
7008       ti->sort_priority = value;
7009
7010       sprintf(identifier, "%d", value);
7011       sprintf(name, "%s", text);
7012
7013       setString(&ti->identifier, identifier);
7014       setString(&ti->name, name);
7015       setString(&ti->name_sorting, name);
7016       setString(&ti->infotext, STR_SETUP_CHOOSE_DROP_DISTANCE);
7017
7018       pushTreeInfo(&drop_distances, ti);
7019     }
7020
7021     // sort distance values to start with lowest distance value
7022     sortTreeInfo(&drop_distances);
7023
7024     // set current distance value to configured distance value
7025     drop_distance_current =
7026       getTreeInfoFromIdentifier(drop_distances,
7027                                 i_to_a(setup.touch.drop_distance));
7028
7029     // if that fails, set current distance to reliable default value
7030     if (drop_distance_current == NULL)
7031       drop_distance_current =
7032         getTreeInfoFromIdentifier(drop_distances,
7033                                   i_to_a(TOUCH_DROP_DISTANCE_DEFAULT));
7034
7035     // if that also fails, set current distance to first available value
7036     if (drop_distance_current == NULL)
7037       drop_distance_current = drop_distances;
7038   }
7039
7040   if (transparencies == NULL)
7041   {
7042     for (i = 0; transparencies_list[i].value != -1; i++)
7043     {
7044       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7045       char identifier[32], name[32];
7046       int value = transparencies_list[i].value;
7047       char *text = transparencies_list[i].text;
7048
7049       ti->node_top = &transparencies;
7050       ti->sort_priority = value;
7051
7052       sprintf(identifier, "%d", value);
7053       sprintf(name, "%s", text);
7054
7055       setString(&ti->identifier, identifier);
7056       setString(&ti->name, name);
7057       setString(&ti->name_sorting, name);
7058       setString(&ti->infotext, STR_SETUP_CHOOSE_TRANSPARENCY);
7059
7060       pushTreeInfo(&transparencies, ti);
7061     }
7062
7063     // sort transparency values to start with lowest transparency value
7064     sortTreeInfo(&transparencies);
7065
7066     // set current transparency value to configured transparency value
7067     transparency_current =
7068       getTreeInfoFromIdentifier(transparencies,
7069                                 i_to_a(setup.touch.transparency));
7070
7071     // if that fails, set current transparency to reliable default value
7072     if (transparency_current == NULL)
7073       transparency_current =
7074         getTreeInfoFromIdentifier(transparencies,
7075                                   i_to_a(TOUCH_TRANSPARENCY_DEFAULT));
7076
7077     // if that also fails, set current transparency to first available value
7078     if (transparency_current == NULL)
7079       transparency_current = transparencies;
7080   }
7081
7082   for (i = 0; i < 2; i++)
7083   {
7084     for (j = 0; j < 2; j++)
7085     {
7086       if (grid_sizes[i][j] == NULL)
7087       {
7088         for (k = 0; grid_sizes_list[k].value != -1; k++)
7089         {
7090           TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7091           char identifier[32], name[32];
7092           int value = grid_sizes_list[k].value;
7093           char *text = grid_sizes_list[k].text;
7094
7095           ti->node_top = &grid_sizes[i][j];
7096           ti->sort_priority = value;
7097
7098           sprintf(identifier, "%d", value);
7099           sprintf(name, "%s", text);
7100
7101           setString(&ti->identifier, identifier);
7102           setString(&ti->name, name);
7103           setString(&ti->name_sorting, name);
7104           setString(&ti->infotext,
7105                     (i == 0 ?
7106                      (j == 0 ?
7107                       STR_SETUP_CHOOSE_GRID_XSIZE_0 :
7108                       STR_SETUP_CHOOSE_GRID_YSIZE_0) :
7109                      (j == 0 ?
7110                       STR_SETUP_CHOOSE_GRID_XSIZE_1 :
7111                       STR_SETUP_CHOOSE_GRID_YSIZE_1)));
7112
7113           pushTreeInfo(&grid_sizes[i][j], ti);
7114         }
7115
7116         // sort grid size values to start with lowest grid size value
7117         sortTreeInfo(&grid_sizes[i][j]);
7118
7119         // set current grid size value to configured grid size value
7120         grid_size_current[i][j] =
7121           getTreeInfoFromIdentifier(grid_sizes[i][j],
7122                                     i_to_a(j == 0 ?
7123                                            setup.touch.grid_xsize[i] :
7124                                            setup.touch.grid_ysize[i]));
7125
7126         // if that fails, set current grid size to reliable default value
7127         if (grid_size_current[i][j] == NULL)
7128           grid_size_current[i][j] =
7129             getTreeInfoFromIdentifier(grid_sizes[i][j],
7130                                       i_to_a(j == 0 ?
7131                                              DEFAULT_GRID_XSIZE(i) :
7132                                              DEFAULT_GRID_YSIZE(i)));
7133
7134         // if that also fails, set current grid size to first available value
7135         if (grid_size_current[i][j] == NULL)
7136           grid_size_current[i][j] = grid_sizes[i][j];
7137       }
7138     }
7139   }
7140
7141   setup.touch.control_type = touch_control_current->identifier;
7142   setup.touch.move_distance = atoi(move_distance_current->identifier);
7143   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
7144   setup.touch.transparency = atoi(transparency_current->identifier);
7145
7146   for (i = 0; i < 2; i++)
7147   {
7148     setup.touch.grid_xsize[i] = atoi(grid_size_current[i][0]->identifier);
7149     setup.touch.grid_ysize[i] = atoi(grid_size_current[i][1]->identifier);
7150
7151     if (i == GRID_ACTIVE_NR())
7152     {
7153       overlay.grid_xsize = setup.touch.grid_xsize[i];
7154       overlay.grid_ysize = setup.touch.grid_ysize[i];
7155     }
7156   }
7157
7158   // needed for displaying value text instead of identifier
7159   touch_controls_text = touch_control_current->name;
7160   move_distance_text = move_distance_current->name;
7161   drop_distance_text = drop_distance_current->name;
7162   transparency_text = transparency_current->name;
7163
7164   for (i = 0; i < 2; i++)
7165     for (j = 0; j < 2; j++)
7166       grid_size_text[i][j] = grid_size_current[i][j]->name;
7167
7168   setup_mode = SETUP_MODE_TOUCH;
7169
7170   DrawSetupScreen();
7171 }
7172
7173 static void execSetupArtwork(void)
7174 {
7175   static ArtworkDirTree *gfx_last_valid = NULL;
7176   static ArtworkDirTree *snd_last_valid = NULL;
7177   static ArtworkDirTree *mus_last_valid = NULL;
7178
7179   // current artwork directory may be invalid (level group, parent link)
7180   if (!validLevelSeries(artwork.gfx_current))
7181     artwork.gfx_current = getFirstValidTreeInfoEntry(gfx_last_valid);
7182   if (!validLevelSeries(artwork.snd_current))
7183     artwork.snd_current = getFirstValidTreeInfoEntry(snd_last_valid);
7184   if (!validLevelSeries(artwork.mus_current))
7185     artwork.mus_current = getFirstValidTreeInfoEntry(mus_last_valid);
7186
7187   // store valid artwork directory information
7188   gfx_last_valid = artwork.gfx_current;
7189   snd_last_valid = artwork.snd_current;
7190   mus_last_valid = artwork.mus_current;
7191
7192 #if 0
7193   Debug("screens:execSetupArtwork", "'%s', '%s', '%s'",
7194         artwork.gfx_current->subdir,
7195         artwork.gfx_current->fullpath,
7196         artwork.gfx_current->basepath);
7197 #endif
7198
7199   setup.graphics_set = artwork.gfx_current->identifier;
7200   setup.sounds_set = artwork.snd_current->identifier;
7201   setup.music_set = artwork.mus_current->identifier;
7202
7203   // needed if last screen (setup choice) changed graphics, sounds or music
7204   ReloadCustomArtwork(0);
7205
7206   // needed for displaying artwork name instead of artwork identifier
7207   graphics_set_name = artwork.gfx_current->name;
7208   sounds_set_name = artwork.snd_current->name;
7209   music_set_name = artwork.mus_current->name;
7210
7211   setup_mode = SETUP_MODE_ARTWORK;
7212
7213   DrawSetupScreen();
7214 }
7215
7216 static void execSetupChooseGraphics(void)
7217 {
7218   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
7219
7220   DrawSetupScreen();
7221 }
7222
7223 static void execSetupChooseSounds(void)
7224 {
7225   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
7226
7227   DrawSetupScreen();
7228 }
7229
7230 static void execSetupChooseMusic(void)
7231 {
7232   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
7233
7234   DrawSetupScreen();
7235 }
7236
7237 static void execSetupInput(void)
7238 {
7239   setup_mode = SETUP_MODE_INPUT;
7240
7241   DrawSetupScreen();
7242 }
7243
7244 static void execSetupShortcuts(void)
7245 {
7246   setup_mode = SETUP_MODE_SHORTCUTS;
7247
7248   DrawSetupScreen();
7249 }
7250
7251 static void execSetupShortcuts1(void)
7252 {
7253   setup_mode = SETUP_MODE_SHORTCUTS_1;
7254
7255   DrawSetupScreen();
7256 }
7257
7258 static void execSetupShortcuts2(void)
7259 {
7260   setup_mode = SETUP_MODE_SHORTCUTS_2;
7261
7262   DrawSetupScreen();
7263 }
7264
7265 static void execSetupShortcuts3(void)
7266 {
7267   setup_mode = SETUP_MODE_SHORTCUTS_3;
7268
7269   DrawSetupScreen();
7270 }
7271
7272 static void execSetupShortcuts4(void)
7273 {
7274   setup_mode = SETUP_MODE_SHORTCUTS_4;
7275
7276   DrawSetupScreen();
7277 }
7278
7279 static void execSetupShortcuts5(void)
7280 {
7281   setup_mode = SETUP_MODE_SHORTCUTS_5;
7282
7283   DrawSetupScreen();
7284 }
7285
7286 static void execExitSetup(void)
7287 {
7288   SetGameStatus(GAME_MODE_MAIN);
7289
7290   DrawMainMenu();
7291 }
7292
7293 static void execSaveAndExitSetup(void)
7294 {
7295   SaveSetup();
7296   execExitSetup();
7297 }
7298
7299 static void execGadgetNetworkServer(void)
7300 {
7301   int gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
7302   struct GadgetInfo *gi = screen_gadget[gadget_id];
7303
7304   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
7305     network_server_hostname[0] = '\0';
7306
7307   ModifyGadget(gi, GDI_TEXT_VALUE, network_server_hostname, GDI_END);
7308
7309   MapGadget(gi);
7310
7311   ClickOnGadget(gi, MB_LEFTBUTTON);
7312 }
7313
7314 static void execOfferUploadTapes(void)
7315 {
7316   OfferUploadTapes();
7317 }
7318
7319 static void ToggleNetworkModeIfNeeded(void)
7320 {
7321   int font_title = FONT_TITLE_1;
7322   int font_foot = FC_BLUE;
7323   int ystart  = mSY - SY + 16;
7324   int ybottom = mSY - SY + SYSIZE - 20;
7325   char *text = (setup.network_mode ? "Start Network" : "Stop Network");
7326
7327   if (setup.network_mode == network.enabled)
7328     return;
7329
7330   network.enabled = setup.network_mode;
7331
7332   FadeOut(REDRAW_ALL);
7333
7334   ClearField();
7335
7336   DrawTextSCentered(ystart, font_title, text);
7337
7338   FadeIn(REDRAW_ALL);
7339
7340   if (network.enabled)
7341     InitNetworkServer();
7342   else
7343     DisconnectFromNetworkServer();
7344
7345   DrawTextSCentered(ybottom, font_foot,
7346                     "Press any key or button for setup menu");
7347
7348   WaitForEventToContinue();
7349
7350   DrawSetupScreen();
7351 }
7352
7353 static void ToggleGameSpeedsListIfNeeded(void)
7354 {
7355   boolean using_game_speeds_extended = (game_speeds == game_speeds_extended);
7356
7357   if (setup.game_speed_extended == using_game_speeds_extended)
7358     return;
7359
7360   // try to match similar values when changing game speeds list
7361   if (setup.game_speed_extended)
7362     setup.game_frame_delay = (setup.game_frame_delay == 15 ? 16 :
7363                               setup.game_frame_delay == 30 ? 29 :
7364                               setup.game_frame_delay);
7365   else
7366     setup.game_frame_delay = (setup.game_frame_delay == 14 ? 15 :
7367                               setup.game_frame_delay == 16 ? 15 :
7368                               setup.game_frame_delay >= 29 ? 30 :
7369                               setup.game_frame_delay <= 10 ? 10 :
7370                               setup.game_frame_delay);
7371
7372   execSetupGame_setGameSpeeds(TRUE);
7373
7374   DrawSetupScreen();
7375 }
7376
7377 static void ToggleUseApiServerIfNeeded(void)
7378 {
7379   if (runtime.use_api_server == setup.use_api_server)
7380     return;
7381
7382   runtime.use_api_server = setup.use_api_server;
7383
7384   if (runtime.use_api_server)
7385     CheckApiServerTasks();
7386 }
7387
7388 static void ModifyGameSpeedIfNeeded(void)
7389 {
7390   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7391       setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY)
7392     return;
7393
7394   char message[100];
7395   char *game_speed_text = "Fast";
7396   int game_speed_value = 15;
7397
7398   if (setup.game_speed_extended)
7399   {
7400     game_speed_text = "60 fps";
7401     game_speed_value = 16;
7402   }
7403
7404   sprintf(message, "Game speed set to %s for VSync to work!", game_speed_text);
7405
7406   // set game speed to existing list value that is fast enough for vsync
7407   setup.game_frame_delay = game_speed_value;
7408
7409   execSetupGame_setGameSpeeds(TRUE);
7410
7411   Request(message, REQ_CONFIRM);
7412 }
7413
7414 static void DisableVsyncIfNeeded(void)
7415 {
7416   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7417       (setup.game_frame_delay >= MIN_VSYNC_FRAME_DELAY &&
7418        setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY))
7419     return;
7420
7421   // disable vsync for the selected game speed to work
7422   setup.vsync_mode = STR_VSYNC_MODE_OFF;
7423
7424   execSetupGraphics_setVsyncModes(TRUE);
7425
7426   Request("VSync disabled for this game speed to work!", REQ_CONFIRM);
7427 }
7428
7429 static struct
7430 {
7431   void *value;
7432   void *related_value;
7433 } hide_related_entry_list[] =
7434 {
7435   { &setup.scores_in_highscore_list,    execSetupChooseScoresType       },
7436   { &setup.scores_in_highscore_list,    &scores_type_text               },
7437
7438   { &setup.game_frame_delay,            execSetupChooseGameSpeed        },
7439   { &setup.game_frame_delay,            &game_speed_text                },
7440
7441   { &setup.scroll_delay_value,          execSetupChooseScrollDelay      },
7442   { &setup.scroll_delay_value,          &scroll_delay_text              },
7443
7444   { &setup.engine_snapshot_mode,        execSetupChooseSnapshotMode     },
7445   { &setup.engine_snapshot_mode,        &snapshot_mode_text             },
7446
7447   { &setup.window_scaling_percent,      execSetupChooseWindowSize       },
7448   { &setup.window_scaling_percent,      &window_size_text               },
7449
7450   { &setup.window_scaling_quality,      execSetupChooseScalingType      },
7451   { &setup.window_scaling_quality,      &scaling_type_text              },
7452
7453   { &setup.screen_rendering_mode,       execSetupChooseRenderingMode    },
7454   { &setup.screen_rendering_mode,       &rendering_mode_text            },
7455
7456   { &setup.vsync_mode,                  execSetupChooseVsyncMode        },
7457   { &setup.vsync_mode,                  &vsync_mode_text                },
7458
7459   { &setup.graphics_set,                execSetupChooseGraphics         },
7460   { &setup.graphics_set,                &graphics_set_name              },
7461
7462   { &setup.sounds_set,                  execSetupChooseSounds           },
7463   { &setup.sounds_set,                  &sounds_set_name                },
7464
7465   { &setup.music_set,                   execSetupChooseMusic            },
7466   { &setup.music_set,                   &music_set_name                 },
7467
7468   { &setup.volume_simple,               execSetupChooseVolumeSimple     },
7469   { &setup.volume_simple,               &volume_simple_text             },
7470
7471   { &setup.volume_loops,                execSetupChooseVolumeLoops      },
7472   { &setup.volume_loops,                &volume_loops_text              },
7473
7474   { &setup.volume_music,                execSetupChooseVolumeMusic      },
7475   { &setup.volume_music,                &volume_music_text              },
7476
7477   { &setup.touch.control_type,          execSetupChooseTouchControls    },
7478   { &setup.touch.control_type,          &touch_controls_text            },
7479
7480   { &setup.touch.move_distance,         execSetupChooseMoveDistance     },
7481   { &setup.touch.move_distance,         &move_distance_text             },
7482
7483   { &setup.touch.drop_distance,         execSetupChooseDropDistance     },
7484   { &setup.touch.drop_distance,         &drop_distance_text             },
7485
7486   { &setup.touch.transparency,          execSetupChooseTransparency     },
7487   { &setup.touch.transparency,          &transparency_text              },
7488
7489   { &setup.touch.grid_xsize[0],         execSetupChooseGridXSize_0      },
7490   { &setup.touch.grid_xsize[0],         &grid_size_text[0][0]           },
7491
7492   { &setup.touch.grid_ysize[0],         execSetupChooseGridYSize_0      },
7493   { &setup.touch.grid_ysize[0],         &grid_size_text[0][1]           },
7494
7495   { &setup.touch.grid_xsize[1],         execSetupChooseGridXSize_1      },
7496   { &setup.touch.grid_xsize[1],         &grid_size_text[1][0]           },
7497
7498   { &setup.touch.grid_ysize[1],         execSetupChooseGridYSize_1      },
7499   { &setup.touch.grid_ysize[1],         &grid_size_text[1][1]           },
7500
7501   { &setup.internal.menu_game,          execSetupGame                   },
7502   { &setup.internal.menu_engines,       execSetupEngines                },
7503   { &setup.internal.menu_editor,        execSetupEditor                 },
7504   { &setup.internal.menu_graphics,      execSetupGraphics               },
7505   { &setup.internal.menu_sound,         execSetupSound                  },
7506   { &setup.internal.menu_artwork,       execSetupArtwork                },
7507   { &setup.internal.menu_input,         execSetupInput                  },
7508   { &setup.internal.menu_touch,         execSetupTouch                  },
7509   { &setup.internal.menu_shortcuts,     execSetupShortcuts              },
7510   { &setup.internal.menu_exit,          execExitSetup                   },
7511   { &setup.internal.menu_save_and_exit, execSaveAndExitSetup            },
7512
7513   { NULL,                               NULL                            }
7514 };
7515
7516 void setHideRelatedSetupEntries(void)
7517 {
7518   int i;
7519
7520   for (i = 0; hide_related_entry_list[i].value != NULL; i++)
7521     if (hideSetupEntry(hide_related_entry_list[i].value))
7522       setHideSetupEntry(hide_related_entry_list[i].related_value);
7523 }
7524
7525 static struct TokenInfo setup_info_main[] =
7526 {
7527   { TYPE_ENTER_MENU,    execSetupGame,          STR_SETUP_GAME          },
7528   { TYPE_ENTER_MENU,    execSetupEngines,       STR_SETUP_ENGINES       },
7529   { TYPE_ENTER_MENU,    execSetupEditor,        STR_SETUP_EDITOR        },
7530   { TYPE_ENTER_MENU,    execSetupGraphics,      STR_SETUP_GRAPHICS      },
7531   { TYPE_ENTER_MENU,    execSetupSound,         STR_SETUP_SOUND         },
7532   { TYPE_ENTER_MENU,    execSetupArtwork,       STR_SETUP_ARTWORK       },
7533   { TYPE_ENTER_MENU,    execSetupInput,         STR_SETUP_INPUT         },
7534   { TYPE_ENTER_MENU,    execSetupTouch,         STR_SETUP_TOUCH         },
7535   { TYPE_ENTER_MENU,    execSetupShortcuts,     STR_SETUP_SHORTCUTS     },
7536   { TYPE_EMPTY,         NULL,                   ""                      },
7537   { TYPE_LEAVE_MENU,    execExitSetup,          STR_SETUP_EXIT          },
7538   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   STR_SETUP_SAVE_AND_EXIT },
7539
7540   { 0,                  NULL,                   NULL                    }
7541 };
7542
7543 static struct TokenInfo setup_info_game[] =
7544 {
7545   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
7546   { TYPE_SWITCH,        &setup.network_mode,    "Network Multi-Player Mode:" },
7547   { TYPE_PLAYER,        &setup.network_player_nr,"Preferred Network Player:" },
7548   { TYPE_TEXT_INPUT,    execGadgetNetworkServer, "Network Server Hostname:" },
7549   { TYPE_STRING,        &network_server_text,   ""                      },
7550   { TYPE_SWITCH,        &setup.use_api_server,  "Use Highscore Server:" },
7551   { TYPE_ENTER_LIST,    execSetupChooseScoresType,"Scores in Highscore List:" },
7552   { TYPE_STRING,        &scores_type_text,      ""                      },
7553   { TYPE_ENTER_LIST,    execOfferUploadTapes,   "Upload Tapes to Server" },
7554   { TYPE_SWITCH,        &setup.multiple_users,  "Multiple Users/Teams:" },
7555   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
7556   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
7557   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
7558   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
7559   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
7560   { TYPE_SWITCH,        &setup.auto_play_next_level,"Auto-play Next Level:" },
7561   { TYPE_SWITCH,        &setup.count_score_after_game,"Count Score After Game:" },
7562   { TYPE_SWITCH,        &setup.show_scores_after_game,"Show Scores After Game:" },
7563   { TYPE_YES_NO,        &setup.ask_on_game_over, "Ask on Game Over:"    },
7564   { TYPE_YES_NO,        &setup.ask_on_quit_game, "Ask on Quit Game:"    },
7565   { TYPE_YES_NO,        &setup.ask_on_quit_program, "Ask on Quit Program:" },
7566   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
7567   { TYPE_SWITCH,        &setup.auto_pause_on_start, "Start Game in Pause Mode:" },
7568   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
7569   { TYPE_STRING,        &game_speed_text,       ""                      },
7570   { TYPE_SWITCH,        &setup.game_speed_extended, "Game Speed Extended List:" },
7571 #if 1
7572   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7573   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7574 #endif
7575   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
7576   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
7577   { TYPE_SWITCH,        &setup.show_load_save_buttons,"Show Load/Save Buttons:" },
7578   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,"Show Undo/Redo Buttons:" },
7579   { TYPE_EMPTY,         NULL,                   ""                      },
7580   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7581
7582   { 0,                  NULL,                   NULL                    }
7583 };
7584
7585 static struct TokenInfo setup_info_engines[] =
7586 {
7587   { TYPE_HEADLINE,      NULL,                   "Emerald Mine"          },
7588   { TYPE_SWITCH,        &setup.forced_scroll_delay, "Scroll Delay:"     },
7589   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics, "Amiga Graphics Chipset:" },
7590   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,"Low-Pass Filter Sounds:" },
7591   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:" },
7592   { TYPE_EMPTY,         NULL,                   ""                      },
7593   { TYPE_HEADLINE,      NULL,                   "Supaplex"              },
7594   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:" },
7595   { TYPE_EMPTY,         NULL,                   ""                      },
7596   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7597
7598   { 0,                  NULL,                   NULL                    }
7599 };
7600
7601 static struct TokenInfo setup_info_editor[] =
7602 {
7603 #if 0
7604   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
7605   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
7606   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
7607   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
7608   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
7609   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
7610   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
7611   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
7612   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
7613   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
7614 #endif
7615   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
7616   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
7617 #if 0
7618   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
7619 #endif
7620   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
7621   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
7622   { TYPE_EMPTY,         NULL,                   ""                      },
7623 #if 0
7624   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
7625   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
7626   { TYPE_EMPTY,         NULL,                   ""                      },
7627 #endif
7628   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
7629   { TYPE_EMPTY,         NULL,                   ""                      },
7630   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:" },
7631   { TYPE_EMPTY,         NULL,                   ""                      },
7632   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7633
7634   { 0,                  NULL,                   NULL                    }
7635 };
7636
7637 static struct TokenInfo setup_info_graphics[] =
7638 {
7639 #if !defined(PLATFORM_ANDROID)
7640   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
7641   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
7642   { TYPE_STRING,        &window_size_text,      ""                      },
7643   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
7644   { TYPE_STRING,        &scaling_type_text,     ""                      },
7645   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
7646   { TYPE_STRING,        &rendering_mode_text,   ""                      },
7647 #endif
7648 #if 0
7649   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7650   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7651 #endif
7652   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode, "Vertical Sync (VSync):" },
7653   { TYPE_STRING,        &vsync_mode_text,       ""                      },
7654   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
7655   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
7656   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
7657   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
7658   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
7659   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
7660   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,  debug_xsn_mode          },
7661   { TYPE_EMPTY,         NULL,                   ""                      },
7662   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7663
7664   { 0,                  NULL,                   NULL                    }
7665 };
7666
7667 static struct TokenInfo setup_info_sound[] =
7668 {
7669   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
7670   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
7671   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
7672   { TYPE_EMPTY,         NULL,                   ""                      },
7673   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
7674   { TYPE_STRING,        &volume_simple_text,    ""                      },
7675   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
7676   { TYPE_STRING,        &volume_loops_text,     ""                      },
7677   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
7678   { TYPE_STRING,        &volume_music_text,     ""                      },
7679   { TYPE_EMPTY,         NULL,                   ""                      },
7680   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7681
7682   { 0,                  NULL,                   NULL                    }
7683 };
7684
7685 static struct TokenInfo setup_info_artwork[] =
7686 {
7687   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
7688   { TYPE_STRING,        &graphics_set_name,     ""                      },
7689   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
7690   { TYPE_STRING,        &sounds_set_name,       ""                      },
7691   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
7692   { TYPE_STRING,        &music_set_name,        ""                      },
7693   { TYPE_EMPTY,         NULL,                   ""                      },
7694   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
7695   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
7696   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
7697   { TYPE_EMPTY,         NULL,                   ""                      },
7698   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7699
7700   { 0,                  NULL,                   NULL                    }
7701 };
7702
7703 static struct TokenInfo setup_info_input[] =
7704 {
7705   { TYPE_SWITCH,        NULL,                   "Player:"               },
7706   { TYPE_SWITCH,        NULL,                   "Device:"               },
7707   { TYPE_SWITCH,        NULL,                   ""                      },
7708   { TYPE_SKIPPABLE,     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_EMPTY,         NULL,                   ""                      },
7716   { TYPE_EMPTY,         NULL,                   ""                      },
7717   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7718   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7719
7720   { 0,                  NULL,                   NULL                    }
7721 };
7722
7723 static struct TokenInfo setup_info_touch[] =
7724 {
7725   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7726   { TYPE_STRING,        &touch_controls_text,   ""                      },
7727   { TYPE_EMPTY,         NULL,                   ""                      },
7728   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7729
7730   { 0,                  NULL,                   NULL                    }
7731 };
7732
7733 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
7734 {
7735   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7736   { TYPE_STRING,        &touch_controls_text,   ""                      },
7737   { TYPE_EMPTY,         NULL,                   ""                      },
7738   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0, "Horizontal Buttons (Landscape):"   },
7739   { TYPE_STRING,        &grid_size_text[0][0],  ""                      },
7740   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0, "Vertical Buttons (Landscape):"     },
7741   { TYPE_STRING,        &grid_size_text[0][1],  ""                      },
7742   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7743   { TYPE_STRING,        &transparency_text,     ""                      },
7744   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7745   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7746   { TYPE_EMPTY,         NULL,                   ""                      },
7747   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7748   { TYPE_EMPTY,         NULL,                   ""                      },
7749   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7750
7751   { 0,                  NULL,                   NULL                    }
7752 };
7753
7754 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
7755 {
7756   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7757   { TYPE_STRING,        &touch_controls_text,   ""                      },
7758   { TYPE_EMPTY,         NULL,                   ""                      },
7759   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1, "Horizontal Buttons (Portrait):"    },
7760   { TYPE_STRING,        &grid_size_text[1][0],  ""                      },
7761   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1, "Vertical Buttons (Portrait):"      },
7762   { TYPE_STRING,        &grid_size_text[1][1],  ""                      },
7763   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7764   { TYPE_STRING,        &transparency_text,     ""                      },
7765   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7766   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7767   { TYPE_EMPTY,         NULL,                   ""                      },
7768   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7769   { TYPE_EMPTY,         NULL,                   ""                      },
7770   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7771
7772   { 0,                  NULL,                   NULL                    }
7773 };
7774
7775 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
7776 {
7777   setup_info_touch_virtual_buttons_0,
7778   setup_info_touch_virtual_buttons_1
7779 };
7780
7781 static struct TokenInfo setup_info_touch_wipe_gestures[] =
7782 {
7783   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7784   { TYPE_STRING,        &touch_controls_text,   ""                      },
7785   { TYPE_EMPTY,         NULL,                   ""                      },
7786   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
7787   { TYPE_STRING,        &move_distance_text,    ""                      },
7788   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
7789   { TYPE_STRING,        &drop_distance_text,    ""                      },
7790   { TYPE_EMPTY,         NULL,                   ""                      },
7791   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7792
7793   { 0,                  NULL,                   NULL                    }
7794 };
7795
7796 static struct TokenInfo setup_info_shortcuts[] =
7797 {
7798   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
7799   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
7800   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
7801   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
7802   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
7803   { TYPE_EMPTY,         NULL,                   ""                      },
7804   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7805
7806   { 0,                  NULL,                   NULL                    }
7807 };
7808
7809 static struct TokenInfo setup_info_shortcuts_1[] =
7810 {
7811   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
7812   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
7813   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
7814   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
7815   { TYPE_KEYTEXT,       NULL,           "Restart Game:",                },
7816   { TYPE_KEY,           &setup.shortcut.restart_game, ""                },
7817   { TYPE_KEYTEXT,       NULL,           "Replay & Pause Before End:",   },
7818   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""            },
7819   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
7820   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
7821   { TYPE_EMPTY,         NULL,                   ""                      },
7822   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
7823   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
7824   { TYPE_EMPTY,         NULL,                   ""                      },
7825   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7826
7827   { 0,                  NULL,                   NULL                    }
7828 };
7829
7830 static struct TokenInfo setup_info_shortcuts_2[] =
7831 {
7832   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
7833   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
7834   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
7835   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
7836   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
7837   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
7838   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
7839   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
7840   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
7841   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
7842   { TYPE_EMPTY,         NULL,                   ""                      },
7843   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7844
7845   { 0,                  NULL,                   NULL                    }
7846 };
7847
7848 static struct TokenInfo setup_info_shortcuts_3[] =
7849 {
7850   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
7851   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
7852   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
7853   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
7854   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
7855   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
7856   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
7857   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
7858   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
7859   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
7860   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
7861   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
7862   { TYPE_EMPTY,         NULL,                   ""                      },
7863   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7864
7865   { 0,                  NULL,                   NULL                    }
7866 };
7867
7868 static struct TokenInfo setup_info_shortcuts_4[] =
7869 {
7870   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
7871   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
7872   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
7873   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
7874   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
7875   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
7876   { TYPE_EMPTY,         NULL,                   ""                      },
7877   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7878
7879   { 0,                  NULL,                   NULL                    }
7880 };
7881
7882 static struct TokenInfo setup_info_shortcuts_5[] =
7883 {
7884   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
7885   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
7886   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
7887   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
7888   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
7889   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
7890   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
7891   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
7892   { TYPE_EMPTY,         NULL,                   ""                      },
7893   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7894
7895   { 0,                  NULL,                   NULL                    }
7896 };
7897
7898 static Key getSetupKey(void)
7899 {
7900   Key key = KSYM_UNDEFINED;
7901   boolean got_key_event = FALSE;
7902
7903   while (!got_key_event)
7904   {
7905     Event event;
7906
7907     if (NextValidEvent(&event))
7908     {
7909       switch (event.type)
7910       {
7911         case EVENT_KEYPRESS:
7912           {
7913             key = GetEventKey((KeyEvent *)&event, TRUE);
7914
7915             // press 'Escape' or 'Enter' to keep the existing key binding
7916             if (key == KSYM_Escape || key == KSYM_Return)
7917               key = KSYM_UNDEFINED;     // keep old value
7918
7919             got_key_event = TRUE;
7920           }
7921           break;
7922
7923         case EVENT_KEYRELEASE:
7924           key_joystick_mapping = 0;
7925           break;
7926
7927         default:
7928           HandleOtherEvents(&event);
7929           break;
7930       }
7931     }
7932
7933     BackToFront();
7934   }
7935
7936   return key;
7937 }
7938
7939 static int getSetupValueFont(int type, void *value)
7940 {
7941   if (type & TYPE_GHOSTED)
7942     return FONT_OPTION_OFF;
7943   else if (type & TYPE_KEY)
7944     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
7945   else if (type & TYPE_STRING)
7946     return FONT_VALUE_2;
7947   else if (type & TYPE_ECS_AGA)
7948     return FONT_VALUE_1;
7949   else if (type & TYPE_BOOLEAN_STYLE)
7950     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
7951   else if (type & TYPE_YES_NO_AUTO)
7952     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
7953             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
7954   else if (type & TYPE_PLAYER)
7955     return FONT_VALUE_1;
7956   else
7957     return FONT_VALUE_1;
7958 }
7959
7960 static int getSetupValueFontNarrow(int type, int font_nr)
7961 {
7962   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
7963           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
7964           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
7965           font_nr);
7966 }
7967
7968 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
7969 {
7970   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7971   struct TokenInfo *si = &setup_info[si_pos];
7972   boolean font_draw_xoffset_modified = FALSE;
7973   boolean scrollbar_needed = (num_setup_info < max_setup_info);
7974   int font_draw_xoffset_old = -1;
7975   int xoffset = (scrollbar_needed ? -1 : 0);
7976   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
7977   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
7978   int xpos = menu_screen_value_xpos;
7979   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
7980   int startx = mSX + xpos * 32;
7981   int starty = mSY + ypos * 32;
7982   int type = si->type;
7983   void *value = si->value;
7984   char *value_string = getSetupValue(type, value);
7985   int font_nr_default = getSetupValueFont(type, value);
7986   int font_width_default = getFontWidth(font_nr_default);
7987   int font_nr = font_nr_default;
7988   int i;
7989
7990   if (value_string == NULL)
7991     return;
7992
7993   if (type & TYPE_KEY)
7994   {
7995     xpos = MENU_SCREEN_START_XPOS;
7996
7997     if (type & TYPE_QUERY)
7998       value_string = "<press key>";
7999   }
8000   else if (type & TYPE_STRING)
8001   {
8002     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
8003
8004     xpos = MENU_SCREEN_START_XPOS;
8005
8006     if (strlen(value_string) > max_value_len)
8007       value_string[max_value_len] = '\0';
8008   }
8009   else if (type & TYPE_YES_NO_AUTO)
8010   {
8011     xpos = menu_screen_value_xpos - 1;
8012   }
8013   else if (type & TYPE_PLAYER)
8014   {
8015     int displayed_player_nr = *(int *)value + 1;
8016
8017     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
8018   }
8019
8020   startx = mSX + xpos * 32;
8021   starty = mSY + ypos * 32;
8022
8023   // special check if right-side setup values moved left due to scrollbar
8024   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
8025   {
8026     int max_menu_text_length = 26;      // maximum text length for classic menu
8027     int font_xoffset = getFontDrawOffsetX(font_nr);
8028     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8029     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8030     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8031     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
8032
8033     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
8034     {
8035       // when using narrow font, left-shifting text "auto" not needed
8036       if (type & TYPE_YES_NO_AUTO)
8037         xpos += 1;
8038
8039       xpos += 1;
8040       startx = mSX + xpos * 32;
8041
8042       font_nr = getSetupValueFontNarrow(type, font_nr);
8043     }
8044   }
8045
8046   // downward compatibility correction for Juergen Bonhagen's menu settings
8047   if (setup_mode != SETUP_MODE_INPUT)
8048   {
8049     int max_menu_text_length_big = (menu_screen_value_xpos -
8050                                     MENU_SCREEN_START_XPOS);
8051     int max_menu_text_length_medium = max_menu_text_length_big * 2;
8052     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
8053     int font1_xoffset = getFontDrawOffsetX(font_nr);
8054     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
8055     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8056     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8057     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8058     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
8059     boolean correct_font_draw_xoffset = FALSE;
8060
8061     if (xpos == MENU_SCREEN_START_XPOS &&
8062         startx + font1_xoffset < text_startx + text_font_xoffset)
8063       correct_font_draw_xoffset = TRUE;
8064
8065     if (xpos == menu_screen_value_xpos &&
8066         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
8067       correct_font_draw_xoffset = TRUE;
8068
8069     // check if setup value would overlap with setup text when printed
8070     // (this can happen for extreme/wrong values for font draw offset)
8071     if (correct_font_draw_xoffset)
8072     {
8073       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
8074       font_draw_xoffset_modified = TRUE;
8075
8076       if (type & TYPE_KEY)
8077         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
8078       else if (!(type & TYPE_STRING))
8079         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
8080           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
8081     }
8082   }
8083
8084   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
8085     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
8086
8087   DrawText(startx, starty, value_string, font_nr);
8088
8089   if (type & TYPE_PLAYER)
8090   {
8091     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
8092     int player_nr = *(int *)value;
8093     int xoff = font->draw_xoffset + getFontWidth(font_nr);
8094     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
8095     int startx2 = startx + xoff;
8096     int starty2 = starty + yoff;
8097
8098     if (DrawingOnBackground(startx2, starty2))
8099       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
8100
8101     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
8102                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8103   }
8104
8105   if (font_draw_xoffset_modified)
8106     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
8107 }
8108
8109 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
8110 {
8111   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
8112   struct TokenInfo *si = &setup_info[si_pos];
8113
8114   if (si->type & TYPE_BOOLEAN_STYLE)
8115   {
8116     *(boolean *)si->value ^= TRUE;
8117   }
8118   else if (si->type & TYPE_YES_NO_AUTO)
8119   {
8120     *(int *)si->value =
8121       (dx == -1 ?
8122        (*(int *)si->value == AUTO ? TRUE :
8123         *(int *)si->value == TRUE ? FALSE : AUTO) :
8124        (*(int *)si->value == TRUE ? AUTO :
8125         *(int *)si->value == AUTO ? FALSE : TRUE));
8126   }
8127   else if (si->type & TYPE_KEY)
8128   {
8129     Key key;
8130
8131     si->type |= TYPE_QUERY;
8132     drawSetupValue(screen_pos, setup_info_pos_raw);
8133     si->type &= ~TYPE_QUERY;
8134
8135     key = getSetupKey();
8136     if (key != KSYM_UNDEFINED)
8137       *(Key *)si->value = key;
8138   }
8139   else if (si->type & TYPE_PLAYER)
8140   {
8141     int player_nr = *(int *)si->value;
8142
8143     if (dx)
8144       player_nr += dx;
8145     else
8146       player_nr = Request("Choose player", REQ_PLAYER) - 1;
8147
8148     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
8149   }
8150
8151   drawSetupValue(screen_pos, setup_info_pos_raw);
8152
8153   // fullscreen state may have changed at this point
8154   if (si->value == &setup.fullscreen)
8155     ToggleFullscreenIfNeeded();
8156
8157   // network mode may have changed at this point
8158   if (si->value == &setup.network_mode)
8159     ToggleNetworkModeIfNeeded();
8160
8161   // API server mode may have changed at this point
8162   if (si->value == &setup.use_api_server)
8163     ToggleUseApiServerIfNeeded();
8164
8165   // game speed list may have changed at this point
8166   if (si->value == &setup.game_speed_extended)
8167     ToggleGameSpeedsListIfNeeded();
8168 }
8169
8170 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
8171 {
8172   static struct TokenInfo *setup_info_final = NULL;
8173   int list_size = 0;
8174   int list_pos = 0;
8175   int i;
8176
8177   // determine maximum list size of target list
8178   while (setup_info_orig[list_size++].type != 0);
8179
8180   // free, allocate and clear memory for target list
8181   checked_free(setup_info_final);
8182   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
8183
8184   // copy setup info list without setup entries marked as hidden
8185   for (i = 0; setup_info_orig[i].type != 0; i++)
8186   {
8187     // skip setup entries configured to be hidden
8188     if (hideSetupEntry(setup_info_orig[i].value))
8189       continue;
8190
8191     // skip skippable setup entries if screen is lower than usual
8192     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
8193         setup_info_orig[i].type == TYPE_SKIPPABLE)
8194       continue;
8195
8196     setup_info_final[list_pos++] = setup_info_orig[i];
8197   }
8198
8199   return setup_info_final;
8200 }
8201
8202 static void DrawSetupScreen_Generic(void)
8203 {
8204   int fade_mask = REDRAW_FIELD;
8205   boolean redraw_all = FALSE;
8206   char *title_string = NULL;
8207   int i;
8208
8209   if (CheckFadeAll())
8210     fade_mask = REDRAW_ALL;
8211
8212   UnmapAllGadgets();
8213   FadeMenuSoundsAndMusic();
8214
8215   FreeScreenGadgets();
8216   CreateScreenGadgets();
8217
8218   if (redraw_mask & REDRAW_ALL)
8219     redraw_all = TRUE;
8220
8221   FadeOut(fade_mask);
8222
8223   // needed if different viewport properties defined for setup screen
8224   ChangeViewportPropertiesIfNeeded();
8225
8226   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
8227
8228   ClearField();
8229
8230   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
8231
8232   if (setup_mode == SETUP_MODE_MAIN)
8233   {
8234     setup_info = setup_info_main;
8235     title_string = STR_SETUP_MAIN;
8236   }
8237   else if (setup_mode == SETUP_MODE_GAME)
8238   {
8239     setup_info = setup_info_game;
8240     title_string = STR_SETUP_GAME;
8241   }
8242   else if (setup_mode == SETUP_MODE_ENGINES)
8243   {
8244     setup_info = setup_info_engines;
8245     title_string = STR_SETUP_ENGINES;
8246   }
8247   else if (setup_mode == SETUP_MODE_EDITOR)
8248   {
8249     setup_info = setup_info_editor;
8250     title_string = STR_SETUP_EDITOR;
8251   }
8252   else if (setup_mode == SETUP_MODE_GRAPHICS)
8253   {
8254     setup_info = setup_info_graphics;
8255     title_string = STR_SETUP_GRAPHICS;
8256   }
8257   else if (setup_mode == SETUP_MODE_SOUND)
8258   {
8259     setup_info = setup_info_sound;
8260     title_string = STR_SETUP_SOUND;
8261   }
8262   else if (setup_mode == SETUP_MODE_ARTWORK)
8263   {
8264     setup_info = setup_info_artwork;
8265     title_string = STR_SETUP_ARTWORK;
8266   }
8267   else if (setup_mode == SETUP_MODE_TOUCH)
8268   {
8269     setup_info = setup_info_touch;
8270     title_string = STR_SETUP_TOUCH;
8271
8272     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
8273       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
8274     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
8275       setup_info = setup_info_touch_wipe_gestures;
8276   }
8277   else if (setup_mode == SETUP_MODE_SHORTCUTS)
8278   {
8279     setup_info = setup_info_shortcuts;
8280     title_string = STR_SETUP_SHORTCUTS;
8281   }
8282   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
8283   {
8284     setup_info = setup_info_shortcuts_1;
8285     title_string = STR_SETUP_SHORTCUTS;
8286   }
8287   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
8288   {
8289     setup_info = setup_info_shortcuts_2;
8290     title_string = STR_SETUP_SHORTCUTS;
8291   }
8292   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
8293   {
8294     setup_info = setup_info_shortcuts_3;
8295     title_string = STR_SETUP_SHORTCUTS;
8296   }
8297   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
8298   {
8299     setup_info = setup_info_shortcuts_4;
8300     title_string = STR_SETUP_SHORTCUTS;
8301   }
8302   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
8303   {
8304     setup_info = setup_info_shortcuts_5;
8305     title_string = STR_SETUP_SHORTCUTS;
8306   }
8307
8308   // use modified setup info without setup entries marked as hidden
8309   setup_info = getSetupInfoFinal(setup_info);
8310
8311   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
8312
8313   // determine maximal number of setup entries that can be displayed on screen
8314   num_setup_info = 0;
8315   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
8316     num_setup_info++;
8317
8318   // determine maximal number of setup entries available for this setup screen
8319   max_setup_info = 0;
8320   for (i = 0; setup_info[i].type != 0; i++)
8321     max_setup_info++;
8322
8323   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
8324
8325   MapScreenGadgets(max_setup_info);
8326
8327   if (redraw_all)
8328     redraw_mask = fade_mask = REDRAW_ALL;
8329
8330   DrawMaskedBorder(fade_mask);
8331
8332   FadeIn(fade_mask);
8333 }
8334
8335 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
8336 {
8337   menu_info = setup_info;
8338
8339   HandleMenuScreen(mx, my, dx, dy, button,
8340                    setup_mode, num_setup_info, max_setup_info);
8341 }
8342
8343 static void DrawSetupScreen_Input(void)
8344 {
8345   int i;
8346
8347   FadeOut(REDRAW_FIELD);
8348
8349   ClearField();
8350
8351   setup_info = getSetupInfoFinal(setup_info_input);
8352
8353   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
8354
8355   for (i = 0; setup_info[i].type != 0; i++)
8356   {
8357     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
8358       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
8359     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
8360       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
8361     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
8362       initCursor(i, IMG_MENU_BUTTON);
8363
8364     DrawCursorAndText_Setup(i, -1, FALSE);
8365   }
8366
8367   // create gadgets for setup input menu screen
8368   FreeScreenGadgets();
8369   CreateScreenGadgets();
8370
8371   // map gadgets for setup input menu screen
8372   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
8373
8374   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
8375
8376   FadeIn(REDRAW_FIELD);
8377 }
8378
8379 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8380 {
8381   if (device_name == NULL)
8382     return;
8383
8384   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8385     device_nr = 0;
8386
8387   if (strlen(device_name) > 1)
8388   {
8389     char c1 = device_name[strlen(device_name) - 1];
8390     char c2 = device_name[strlen(device_name) - 2];
8391
8392     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8393       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8394   }
8395   else
8396     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8397             strlen(device_name));
8398 }
8399
8400 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8401 {
8402   int i;
8403   static struct SetupKeyboardInfo custom_key;
8404   static struct
8405   {
8406     Key *key;
8407     char *text;
8408   } custom[] =
8409   {
8410     { &custom_key.left,  "Axis/Pad Left"  },
8411     { &custom_key.right, "Axis/Pad Right" },
8412     { &custom_key.up,    "Axis/Pad Up"    },
8413     { &custom_key.down,  "Axis/Pad Down"  },
8414     { &custom_key.snap,  "Button 1/A/X"   },
8415     { &custom_key.drop,  "Button 2/B/Y"   }
8416   };
8417   static char *joystick_name[MAX_PLAYERS] =
8418   {
8419     "Joystick1",
8420     "Joystick2",
8421     "Joystick3",
8422     "Joystick4"
8423   };
8424   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8425   int font_nr_info = FONT_MENU_1;
8426   int font_nr_name = FONT_VALUE_OLD;
8427   int font_nr_on   = FONT_VALUE_1;
8428   int font_nr_off  = FONT_VALUE_OLD;
8429   int pos = 4;
8430
8431   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8432   {
8433     font_nr_info = FONT_MENU_2;
8434     font_nr_on   = FONT_VALUE_NARROW;
8435     font_nr_off  = FONT_VALUE_OLD_NARROW;
8436   }
8437
8438   custom_key = setup.input[player_nr].key;
8439
8440   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8441            FONT_INPUT_1_ACTIVE);
8442
8443   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8444                              TILEX, TILEY);
8445   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8446                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8447
8448   if (setup.input[player_nr].use_joystick)
8449   {
8450     char *device_name = setup.input[player_nr].joy.device_name;
8451     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8452     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8453     char *text = joystick_name[joystick_nr];
8454     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8455
8456     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8457     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8458   }
8459   else
8460   {
8461     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8462     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8463   }
8464
8465   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8466     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8467   else
8468     pos = 3;
8469
8470   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8471   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8472   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8473   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8474
8475   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8476   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8477   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8478   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8479   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8480   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8481
8482   for (i = 0; i < 6; i++)
8483   {
8484     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8485
8486     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8487              "              ", font_nr_on);
8488     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8489              (setup.input[player_nr].use_joystick ?
8490               custom[i].text :
8491               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8492   }
8493 }
8494
8495 static int input_player_nr = 0;
8496
8497 static void HandleSetupScreen_Input_Player(int step, int direction)
8498 {
8499   int old_player_nr = input_player_nr;
8500   int new_player_nr;
8501
8502   new_player_nr = old_player_nr + step * direction;
8503   if (new_player_nr < 0)
8504     new_player_nr = 0;
8505   if (new_player_nr > MAX_PLAYERS - 1)
8506     new_player_nr = MAX_PLAYERS - 1;
8507
8508   if (new_player_nr != old_player_nr)
8509   {
8510     input_player_nr = new_player_nr;
8511
8512     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8513   }
8514 }
8515
8516 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8517 {
8518   static int choice = 0;
8519   int x = 0;
8520   int y = choice;
8521   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8522   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8523   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8524   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8525
8526   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8527   {
8528     int i;
8529
8530     for (i = 0; setup_info_input[i].type != 0; i++)
8531     {
8532       // adjust menu structure according to skipped setup entries
8533       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8534       {
8535         pos_empty2--;
8536         pos_end--;
8537       }
8538     }
8539   }
8540
8541   if (button == MB_MENU_INITIALIZE)
8542   {
8543     // input setup menu may have changed size due to graphics configuration
8544     if (choice >= pos_empty1)
8545       choice = pos_end;
8546
8547     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8548
8549     DrawCursorAndText_Setup(choice, -1, TRUE);
8550
8551     return;
8552   }
8553   else if (button == MB_MENU_LEAVE)
8554   {
8555     setup_mode = SETUP_MODE_MAIN;
8556     DrawSetupScreen();
8557     InitJoysticks();
8558
8559     return;
8560   }
8561
8562   if (mx || my)         // mouse input
8563   {
8564     x = (mx - mSX) / 32;
8565     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8566   }
8567   else if (dx || dy)    // keyboard input
8568   {
8569     if (dx && choice == 0)
8570       x = (dx < 0 ? 10 : 12);
8571     else if ((dx && choice == 1) ||
8572              (dx == -1 && choice == pos_end))
8573       button = MB_MENU_CHOICE;
8574     else if (dy)
8575       y = choice + dy;
8576
8577     if (y >= pos_empty1 && y <= pos_empty2)
8578       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
8579   }
8580
8581   if (y == 0 && dx != 0 && button)
8582   {
8583     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
8584   }
8585   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
8586            y >= pos_start && y <= pos_end &&
8587            !(y >= pos_empty1 && y <= pos_empty2))
8588   {
8589     if (button)
8590     {
8591       if (y != choice)
8592       {
8593         DrawCursorAndText_Setup(choice, -1, FALSE);
8594         DrawCursorAndText_Setup(y, -1, TRUE);
8595
8596         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
8597
8598         choice = y;
8599       }
8600     }
8601     else
8602     {
8603       if (y == 1)
8604       {
8605         char *device_name = setup.input[input_player_nr].joy.device_name;
8606
8607         if (!setup.input[input_player_nr].use_joystick)
8608         {
8609           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
8610
8611           setJoystickDeviceToNr(device_name, new_device_nr);
8612           setup.input[input_player_nr].use_joystick = TRUE;
8613         }
8614         else
8615         {
8616           int device_nr = getJoystickNrFromDeviceName(device_name);
8617           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
8618
8619           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
8620             setup.input[input_player_nr].use_joystick = FALSE;
8621           else
8622             setJoystickDeviceToNr(device_name, new_device_nr);
8623         }
8624
8625         drawPlayerSetupInputInfo(input_player_nr, FALSE);
8626       }
8627       else if (y == 2)
8628       {
8629         if (setup.input[input_player_nr].use_joystick)
8630           ConfigureJoystick(input_player_nr);
8631         else
8632           CustomizeKeyboard(input_player_nr);
8633       }
8634       else if (y == pos_end)
8635       {
8636         InitJoysticks();
8637
8638         FadeSetLeaveMenu();
8639
8640         setup_mode = SETUP_MODE_MAIN;
8641         DrawSetupScreen();
8642       }
8643     }
8644   }
8645 }
8646
8647 static boolean CustomizeKeyboardMain(int player_nr)
8648 {
8649   int i;
8650   int step_nr;
8651   boolean finished = FALSE;
8652   static struct SetupKeyboardInfo custom_key;
8653   static struct
8654   {
8655     Key *key;
8656     char *text;
8657   } customize_step[] =
8658   {
8659     { &custom_key.left,  "Move Left"    },
8660     { &custom_key.right, "Move Right"   },
8661     { &custom_key.up,    "Move Up"      },
8662     { &custom_key.down,  "Move Down"    },
8663     { &custom_key.snap,  "Snap Field"   },
8664     { &custom_key.drop,  "Drop Element" }
8665   };
8666   int font_nr_old = FONT_VALUE_OLD;
8667   int font_nr_new = FONT_VALUE_1;
8668   boolean success = FALSE;
8669
8670   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8671   {
8672     font_nr_old = FONT_VALUE_OLD_NARROW;
8673     font_nr_new = FONT_VALUE_NARROW;
8674   }
8675
8676   // read existing key bindings from player setup
8677   custom_key = setup.input[player_nr].key;
8678
8679   FadeSetEnterMenu();
8680   FadeOut(REDRAW_FIELD);
8681
8682   ClearField();
8683
8684   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
8685
8686   step_nr = 0;
8687   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8688            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8689   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8690            "Key:", FONT_INPUT_1_ACTIVE);
8691   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8692            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
8693
8694   FadeIn(REDRAW_FIELD);
8695
8696   while (!finished)
8697   {
8698     Event event;
8699
8700     if (NextValidEvent(&event))
8701     {
8702       switch (event.type)
8703       {
8704         case EVENT_KEYPRESS:
8705           {
8706             Key key = GetEventKey((KeyEvent *)&event, FALSE);
8707
8708             // press 'Escape' to abort and keep the old key bindings
8709             if (key == KSYM_Escape)
8710             {
8711               FadeSkipNextFadeIn();
8712
8713               finished = TRUE;
8714
8715               break;
8716             }
8717
8718             // press 'Enter' to keep the existing key binding
8719             if (key == KSYM_Return)
8720               key = *customize_step[step_nr].key;
8721
8722             // check if key already used
8723             for (i = 0; i < step_nr; i++)
8724               if (*customize_step[i].key == key)
8725                 break;
8726             if (i < step_nr)
8727               break;
8728
8729             // got new key binding
8730             *customize_step[step_nr].key = key;
8731             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8732                      "             ", font_nr_new);
8733             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8734                      getKeyNameFromKey(key), font_nr_new);
8735             step_nr++;
8736
8737             // un-highlight last query
8738             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
8739                      customize_step[step_nr - 1].text, FONT_MENU_1);
8740             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
8741                      "Key:", FONT_MENU_1);
8742
8743             // all keys configured
8744             if (step_nr == 6)
8745             {
8746               finished = TRUE;
8747               success = TRUE;
8748
8749               break;
8750             }
8751
8752             // query next key binding
8753             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8754                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8755             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8756                      "Key:", FONT_INPUT_1_ACTIVE);
8757             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8758                      getKeyNameFromKey(*customize_step[step_nr].key),
8759                      font_nr_old);
8760           }
8761           break;
8762
8763         case EVENT_KEYRELEASE:
8764           key_joystick_mapping = 0;
8765           break;
8766
8767         default:
8768           HandleOtherEvents(&event);
8769           break;
8770       }
8771     }
8772
8773     BackToFront();
8774   }
8775
8776   // write new key bindings back to player setup, if successfully finished
8777   if (success)
8778     setup.input[player_nr].key = custom_key;
8779
8780   return success;
8781 }
8782
8783 void CustomizeKeyboard(int player_nr)
8784 {
8785   boolean success = CustomizeKeyboardMain(player_nr);
8786
8787   if (success)
8788   {
8789     int font_nr = FONT_TITLE_1;
8790     int font_height = getFontHeight(font_nr);
8791     int ypos1 = SYSIZE / 2 - font_height * 2;
8792     int ypos2 = SYSIZE / 2 - font_height * 1;
8793     unsigned int wait_frame_delay = 0;
8794     unsigned int wait_frame_delay_value = 2000;
8795
8796     ResetDelayCounter(&wait_frame_delay);
8797
8798     ClearField();
8799
8800     DrawTextSCentered(ypos1, font_nr, "Keyboard");
8801     DrawTextSCentered(ypos2, font_nr, "configured!");
8802
8803     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8804       BackToFront();
8805
8806     ClearEventQueue();
8807   }
8808
8809   DrawSetupScreen_Input();
8810 }
8811
8812 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
8813
8814 #define MARKER_BUTTON           1
8815 #define MARKER_AXIS_X           2
8816 #define MARKER_AXIS_Y           3
8817
8818 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
8819 {
8820   static boolean bitmaps_initialized = FALSE;
8821   boolean screen_initialized = FALSE;
8822   static Bitmap *controller, *button, *axis_x, *axis_y;
8823   char *name;
8824   boolean success = TRUE;
8825   boolean done = FALSE, next = FALSE;
8826   Event event;
8827   int alpha = 200, alpha_step = -1;
8828   int alpha_ticks = 0;
8829   char mapping[4096], temp[256];
8830   int font_name = MENU_SETUP_FONT_TITLE;
8831   int font_info = MENU_SETUP_FONT_TEXT;
8832   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
8833   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
8834   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
8835   int ystep_name = getMenuTextStep(spacing_name, font_name);
8836   int ystep_line = getMenuTextStep(spacing_line, font_info);
8837   int ystep_para = getMenuTextStep(spacing_para, font_info);
8838   int i, j;
8839
8840   struct
8841   {
8842     int x, y;
8843     int marker;
8844     char *field;
8845     int axis, button, hat, hat_value;
8846     char mapping[4096];
8847   }
8848   *step, *prev_step, steps[] =
8849   {
8850     { 356, 155, MARKER_BUTTON, "a",             },
8851     { 396, 122, MARKER_BUTTON, "b",             },
8852     { 320, 125, MARKER_BUTTON, "x",             },
8853     { 358,  95, MARKER_BUTTON, "y",             },
8854     { 162, 125, MARKER_BUTTON, "back",          },
8855     { 216, 125, MARKER_BUTTON, "guide",         },
8856     { 271, 125, MARKER_BUTTON, "start",         },
8857     { 110, 200, MARKER_BUTTON, "dpleft",        },
8858     { 146, 228, MARKER_BUTTON, "dpdown",        },
8859     { 178, 200, MARKER_BUTTON, "dpright",       },
8860     { 146, 172, MARKER_BUTTON, "dpup",          },
8861     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
8862     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
8863     { 382,  40, MARKER_BUTTON, "rightshoulder", },
8864     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
8865     {  73, 141, MARKER_BUTTON, "leftstick",     },
8866     { 282, 210, MARKER_BUTTON, "rightstick",    },
8867     {  73, 141, MARKER_AXIS_X, "leftx",         },
8868     {  73, 141, MARKER_AXIS_Y, "lefty",         },
8869     { 282, 210, MARKER_AXIS_X, "rightx",        },
8870     { 282, 210, MARKER_AXIS_Y, "righty",        },
8871   };
8872
8873   unsigned int event_frame_delay = 0;
8874   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
8875
8876   ResetDelayCounter(&event_frame_delay);
8877
8878   if (!bitmaps_initialized)
8879   {
8880     controller = LoadCustomImage("joystick/controller.png");
8881     button     = LoadCustomImage("joystick/button.png");
8882     axis_x     = LoadCustomImage("joystick/axis_x.png");
8883     axis_y     = LoadCustomImage("joystick/axis_y.png");
8884
8885     bitmaps_initialized = TRUE;
8886   }
8887
8888   name = getFormattedJoystickName(SDL_JoystickName(joystick));
8889
8890 #if DEBUG_JOYSTICKS
8891   // print info about the joystick we are watching
8892   Debug("joystick", "watching joystick %d: (%s)",
8893         SDL_JoystickInstanceID(joystick), name);
8894   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
8895         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
8896         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
8897 #endif
8898
8899   // initialize mapping with GUID and name
8900   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
8901
8902   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
8903            temp, name, SDL_GetPlatform());
8904
8905   // loop through all steps (buttons and axes), getting joystick events
8906   for (i = 0; i < SDL_arraysize(steps) && !done;)
8907   {
8908     Bitmap *marker = button;    // initialize with reliable default value
8909
8910     step = &steps[i];
8911     strcpy(step->mapping, mapping);
8912     step->axis = -1;
8913     step->button = -1;
8914     step->hat = -1;
8915     step->hat_value = -1;
8916
8917     marker = (step->marker == MARKER_BUTTON ? button :
8918               step->marker == MARKER_AXIS_X ? axis_x :
8919               step->marker == MARKER_AXIS_Y ? axis_y : marker);
8920
8921     next = FALSE;
8922
8923     while (!done && !next)
8924     {
8925       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
8926       alpha_ticks = SDL_GetTicks();
8927
8928       if (alpha >= 255)
8929       {
8930         alpha = 255;
8931         alpha_step = -1;
8932       }
8933       else if (alpha < 128)
8934       {
8935         alpha = 127;
8936         alpha_step = 1;
8937       }
8938
8939       int controller_x = SX + (SXSIZE - controller->width) / 2;
8940       int controller_y = SY + ystep_line;
8941
8942       int marker_x = controller_x + step->x;
8943       int marker_y = controller_y + step->y;
8944
8945       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
8946       int ystart2 = ystart1 + ystep_name + ystep_line;
8947
8948       ClearField();
8949
8950       DrawTextSCentered(ystart1, font_name, name);
8951
8952       DrawTextSCentered(ystart2, font_info,
8953                         "Press buttons and move axes on");
8954       ystart2 += ystep_line;
8955       DrawTextSCentered(ystart2, font_info,
8956                         "your controller when indicated.");
8957       ystart2 += ystep_line;
8958       DrawTextSCentered(ystart2, font_info,
8959                         "(Your controller may look different.)");
8960       ystart2 += ystep_para;
8961
8962 #if defined(PLATFORM_ANDROID)
8963       DrawTextSCentered(ystart2, font_info,
8964                         "To correct a mistake,");
8965       ystart2 += ystep_line;
8966       DrawTextSCentered(ystart2, font_info,
8967                         "press the 'back' button.");
8968       ystart2 += ystep_line;
8969       DrawTextSCentered(ystart2, font_info,
8970                         "To skip a button or axis,");
8971       ystart2 += ystep_line;
8972       DrawTextSCentered(ystart2, font_info,
8973                         "press the 'menu' button.");
8974 #else
8975       DrawTextSCentered(ystart2, font_info,
8976                         "To correct a mistake,");
8977       ystart2 += ystep_line;
8978       DrawTextSCentered(ystart2, font_info,
8979                         "press the 'backspace' key.");
8980       ystart2 += ystep_line;
8981       DrawTextSCentered(ystart2, font_info,
8982                         "To skip a button or axis,");
8983       ystart2 += ystep_line;
8984       DrawTextSCentered(ystart2, font_info,
8985                         "press the 'return' key.");
8986       ystart2 += ystep_line;
8987       DrawTextSCentered(ystart2, font_info,
8988                         "To exit, press the 'escape' key.");
8989 #endif
8990
8991       BlitBitmapMasked(controller, drawto, 0, 0,
8992                        controller->width, controller->height,
8993                        controller_x, controller_y);
8994
8995       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
8996       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
8997
8998       BlitBitmapMasked(marker, drawto, 0, 0,
8999                        marker->width, marker->height,
9000                        marker_x, marker_y);
9001
9002       if (!screen_initialized)
9003         FadeIn(REDRAW_FIELD);
9004       else
9005         BackToFront();
9006
9007       screen_initialized = TRUE;
9008
9009       while (NextValidEvent(&event))
9010       {
9011         switch (event.type)
9012         {
9013           case SDL_JOYAXISMOTION:
9014             if (event.jaxis.value > 20000 ||
9015                 event.jaxis.value < -20000)
9016             {
9017               for (j = 0; j < i; j++)
9018                 if (steps[j].axis == event.jaxis.axis)
9019                   break;
9020
9021               if (j == i)
9022               {
9023                 if (step->marker != MARKER_AXIS_X &&
9024                     step->marker != MARKER_AXIS_Y)
9025                   break;
9026
9027                 step->axis = event.jaxis.axis;
9028                 strcat(mapping, step->field);
9029                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
9030                 strcat(mapping, temp);
9031                 i++;
9032                 next = TRUE;
9033               }
9034             }
9035
9036             break;
9037
9038           case SDL_JOYHATMOTION:
9039             // ignore centering; we're probably just coming back
9040             // to the center from the previous item we set
9041             if (event.jhat.value == SDL_HAT_CENTERED)
9042               break;
9043
9044             for (j = 0; j < i; j++)
9045               if (steps[j].hat == event.jhat.hat &&
9046                   steps[j].hat_value == event.jhat.value)
9047                 break;
9048
9049             if (j == i)
9050             {
9051               step->hat = event.jhat.hat;
9052               step->hat_value = event.jhat.value;
9053               strcat(mapping, step->field);
9054               snprintf(temp, sizeof(temp), ":h%u.%u,",
9055                        event.jhat.hat, event.jhat.value );
9056               strcat(mapping, temp);
9057               i++;
9058               next = TRUE;
9059             }
9060
9061             break;
9062
9063           case SDL_JOYBALLMOTION:
9064             break;
9065
9066           case SDL_JOYBUTTONUP:
9067             for (j = 0; j < i; j++)
9068               if (steps[j].button == event.jbutton.button)
9069                 break;
9070
9071             if (j == i)
9072             {
9073               step->button = event.jbutton.button;
9074               strcat(mapping, step->field);
9075               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
9076               strcat(mapping, temp);
9077               i++;
9078               next = TRUE;
9079             }
9080
9081             break;
9082
9083           case SDL_FINGERDOWN:
9084           case SDL_MOUSEBUTTONDOWN:
9085             // skip this step
9086             i++;
9087             next = TRUE;
9088
9089             break;
9090
9091           case SDL_KEYDOWN:
9092             if (event.key.keysym.sym == KSYM_BackSpace ||
9093                 event.key.keysym.sym == KSYM_Back)
9094             {
9095               if (i == 0)
9096               {
9097                 // leave screen
9098                 success = FALSE;
9099                 done = TRUE;
9100
9101                 break;
9102               }
9103
9104               // undo this step
9105               prev_step = &steps[i - 1];
9106               strcpy(mapping, prev_step->mapping);
9107               i--;
9108               next = TRUE;
9109
9110               break;
9111             }
9112
9113             if (event.key.keysym.sym == KSYM_space ||
9114                 event.key.keysym.sym == KSYM_Return ||
9115                 event.key.keysym.sym == KSYM_Menu)
9116             {
9117               // skip this step
9118               i++;
9119               next = TRUE;
9120
9121               break;
9122             }
9123
9124             if (event.key.keysym.sym == KSYM_Escape)
9125             {
9126               // leave screen
9127               success = FALSE;
9128               done = TRUE;
9129             }
9130
9131             break;
9132
9133           case SDL_QUIT:
9134             program.exit_function(0);
9135             break;
9136
9137           default:
9138             break;
9139         }
9140
9141         // do not handle events for longer than standard frame delay period
9142         if (DelayReached(&event_frame_delay, event_frame_delay_value))
9143           break;
9144       }
9145     }
9146   }
9147
9148   if (success)
9149   {
9150 #if DEBUG_JOYSTICKS
9151     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
9152 #endif
9153
9154     // activate mapping for this game
9155     SDL_GameControllerAddMapping(mapping);
9156
9157     // save mapping to personal mappings
9158     SaveSetup_AddGameControllerMapping(mapping);
9159   }
9160
9161   // wait until the last pending event was removed from event queue
9162   while (NextValidEvent(&event));
9163
9164   return success;
9165 }
9166
9167 static int ConfigureJoystickMain(int player_nr)
9168 {
9169   char *device_name = setup.input[player_nr].joy.device_name;
9170   int joystick_nr = getJoystickNrFromDeviceName(device_name);
9171   boolean joystick_active = CheckJoystickOpened(joystick_nr);
9172   int success = FALSE;
9173   int i;
9174
9175   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
9176     return JOYSTICK_NOT_AVAILABLE;
9177
9178   if (!joystick_active || !setup.input[player_nr].use_joystick)
9179     return JOYSTICK_NOT_AVAILABLE;
9180
9181   FadeSetEnterMenu();
9182   FadeOut(REDRAW_FIELD);
9183
9184   // close all joystick devices (potentially opened as game controllers)
9185   for (i = 0; i < SDL_NumJoysticks(); i++)
9186     SDLCloseJoystick(i);
9187
9188   // open joystick device as plain joystick to configure as game controller
9189   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
9190
9191   // as the joystick was successfully opened before, this should not happen
9192   if (joystick == NULL)
9193     return FALSE;
9194
9195   // create new game controller mapping (buttons and axes) for joystick device
9196   success = ConfigureJoystickMapButtonsAndAxes(joystick);
9197
9198   // close joystick (and maybe re-open as configured game controller later)
9199   SDL_JoystickClose(joystick);
9200
9201   // re-open all joystick devices (potentially as game controllers)
9202   for (i = 0; i < SDL_NumJoysticks(); i++)
9203     SDLOpenJoystick(i);
9204
9205   // clear all joystick input actions for all joystick devices
9206   SDLClearJoystickState();
9207
9208   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
9209 }
9210
9211 void ConfigureJoystick(int player_nr)
9212 {
9213   boolean state = ConfigureJoystickMain(player_nr);
9214
9215   if (state != JOYSTICK_NOT_CONFIGURED)
9216   {
9217     boolean success = (state == JOYSTICK_CONFIGURED);
9218     char message1[MAX_OUTPUT_LINESIZE + 1];
9219     char *message2 = (success ? "configured!" : "not available!");
9220     char *device_name = setup.input[player_nr].joy.device_name;
9221     int nr = getJoystickNrFromDeviceName(device_name) + 1;
9222     int font_nr = FONT_TITLE_1;
9223     int font_height = getFontHeight(font_nr);
9224     int ypos1 = SYSIZE / 2 - font_height * 2;
9225     int ypos2 = SYSIZE / 2 - font_height * 1;
9226     unsigned int wait_frame_delay = 0;
9227     unsigned int wait_frame_delay_value = 2000;
9228
9229     ResetDelayCounter(&wait_frame_delay);
9230
9231     ClearField();
9232
9233     sprintf(message1, "Joystick %d", nr);
9234
9235     DrawTextSCentered(ypos1, font_nr, message1);
9236     DrawTextSCentered(ypos2, font_nr, message2);
9237
9238     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9239       BackToFront();
9240
9241     ClearEventQueue();
9242   }
9243
9244   DrawSetupScreen_Input();
9245 }
9246
9247 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
9248 {
9249   if (y < video.screen_height / 3)
9250   {
9251     // remap touch gadgets to access upper part of the screen
9252     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9253     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9254   }
9255   else if (y > 2 * video.screen_height / 3)
9256   {
9257     // remap touch gadgets to access lower part of the screen
9258     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9259     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9260   }
9261 }
9262
9263 static boolean ConfigureVirtualButtonsMain(void)
9264 {
9265   static char *customize_step_text[] =
9266   {
9267     "Move Left",
9268     "Move Right",
9269     "Move Up",
9270     "Move Down",
9271     "Snap Field",
9272     "Drop Element"
9273   };
9274   char grid_button[] =
9275   {
9276     CHAR_GRID_BUTTON_LEFT,
9277     CHAR_GRID_BUTTON_RIGHT,
9278     CHAR_GRID_BUTTON_UP,
9279     CHAR_GRID_BUTTON_DOWN,
9280     CHAR_GRID_BUTTON_SNAP,
9281     CHAR_GRID_BUTTON_DROP
9282   };
9283   enum
9284   {
9285     ACTION_NONE,
9286     ACTION_ESCAPE,
9287     ACTION_BACK,
9288     ACTION_NEXT
9289   };
9290   int font_nr = FONT_INPUT_1_ACTIVE;
9291   int font_height = getFontHeight(font_nr);
9292   int ypos1 = SYSIZE / 2 - font_height * 2;
9293   int ypos2 = SYSIZE / 2 - font_height * 1;
9294   boolean success = FALSE;
9295   boolean finished = FALSE;
9296   int step_nr = 0;
9297   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
9298   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9299   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9300   boolean set_grid_button = FALSE;
9301   int nr = GRID_ACTIVE_NR();
9302   int x, y;
9303
9304   for (x = 0; x < MAX_GRID_XSIZE; x++)
9305     for (y = 0; y < MAX_GRID_YSIZE; y++)
9306       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
9307
9308   overlay.grid_button_highlight = grid_button[step_nr];
9309
9310   UnmapAllGadgets();
9311
9312   FadeSetEnterMenu();
9313   FadeOut(REDRAW_FIELD);
9314
9315   ClearField();
9316
9317   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9318   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9319   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9320
9321   FadeIn(REDRAW_FIELD);
9322
9323   SetOverlayShowGrid(TRUE);
9324
9325   // map gadgets for setup touch buttons menu screen
9326   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9327
9328   while (!finished)
9329   {
9330     Event event;
9331
9332     while (NextValidEvent(&event))
9333     {
9334       int action = ACTION_NONE;
9335
9336       // ---------- handle events and set the resulting action ----------
9337
9338       switch (event.type)
9339       {
9340         case EVENT_USER:
9341           {
9342             UserEvent *user = (UserEvent *)&event;
9343             int id = user->value1;
9344
9345             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
9346                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
9347                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
9348                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
9349                       ACTION_NONE);
9350           }
9351           break;
9352
9353         case EVENT_KEYPRESS:
9354           {
9355             Key key = GetEventKey((KeyEvent *)&event, FALSE);
9356
9357             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
9358                       key == KSYM_BackSpace ||
9359                       key == KSYM_Back ?        ACTION_BACK :
9360                       key == KSYM_Return ||
9361                       key == KSYM_Menu ||
9362                       key == KSYM_space ?       ACTION_NEXT :
9363                       ACTION_NONE);
9364           }
9365           break;
9366
9367         case EVENT_KEYRELEASE:
9368           key_joystick_mapping = 0;
9369           break;
9370
9371         case EVENT_BUTTONPRESS:
9372         case EVENT_BUTTONRELEASE:
9373           {
9374             ButtonEvent *button = (ButtonEvent *)&event;
9375
9376             motion_status = FALSE;
9377
9378             if (button->type == EVENT_BUTTONPRESS)
9379               button_status = button->button;
9380             else
9381               button_status = MB_RELEASED;
9382
9383             if (HandleGadgets(button->x, button->y, button_status))
9384             {
9385               // do not handle this button event anymore
9386               break;
9387             }
9388
9389             button->x += video.screen_xoffset;
9390             button->y += video.screen_yoffset;
9391
9392             x = button->x * overlay.grid_xsize / video.screen_width;
9393             y = button->y * overlay.grid_ysize / video.screen_height;
9394
9395             if (button->type == EVENT_BUTTONPRESS)
9396             {
9397               grid_button_draw =
9398                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9399                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9400
9401               set_grid_button = TRUE;
9402             }
9403
9404             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9405           }
9406           break;
9407
9408         case EVENT_MOTIONNOTIFY:
9409           {
9410             MotionEvent *motion = (MotionEvent *)&event;
9411
9412             motion_status = TRUE;
9413
9414             if (HandleGadgets(motion->x, motion->y, button_status))
9415             {
9416               // do not handle this button event anymore
9417               break;
9418             }
9419
9420             motion->x += video.screen_xoffset;
9421             motion->y += video.screen_yoffset;
9422
9423             x = motion->x * overlay.grid_xsize / video.screen_width;
9424             y = motion->y * overlay.grid_ysize / video.screen_height;
9425
9426             set_grid_button = TRUE;
9427
9428             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9429           }
9430           break;
9431
9432         case SDL_WINDOWEVENT:
9433           HandleWindowEvent((WindowEvent *) &event);
9434
9435           // check if device has been rotated
9436           if (nr != GRID_ACTIVE_NR())
9437           {
9438             nr = GRID_ACTIVE_NR();
9439
9440             for (x = 0; x < MAX_GRID_XSIZE; x++)
9441               for (y = 0; y < MAX_GRID_YSIZE; y++)
9442                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9443                   overlay.grid_button[x][y];
9444           }
9445
9446           break;
9447
9448         case SDL_APP_WILLENTERBACKGROUND:
9449         case SDL_APP_DIDENTERBACKGROUND:
9450         case SDL_APP_WILLENTERFOREGROUND:
9451         case SDL_APP_DIDENTERFOREGROUND:
9452           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9453           break;
9454
9455         default:
9456           HandleOtherEvents(&event);
9457           break;
9458       }
9459
9460       // ---------- perform action set by handling events ----------
9461
9462       if (action == ACTION_ESCAPE)
9463       {
9464         // abort and restore the old key bindings
9465
9466         for (x = 0; x < MAX_GRID_XSIZE; x++)
9467           for (y = 0; y < MAX_GRID_YSIZE; y++)
9468             overlay.grid_button[x][y] = grid_button_old[x][y];
9469
9470         FadeSkipNextFadeIn();
9471
9472         finished = TRUE;
9473       }
9474       else if (action == ACTION_BACK)
9475       {
9476         // keep the configured key bindings and go to previous page
9477
9478         step_nr--;
9479
9480         if (step_nr < 0)
9481         {
9482           FadeSkipNextFadeIn();
9483
9484           finished = TRUE;
9485         }
9486       }
9487       else if (action == ACTION_NEXT)
9488       {
9489         // keep the configured key bindings and go to next page
9490
9491         step_nr++;
9492
9493         // all virtual buttons configured
9494         if (step_nr == 6)
9495         {
9496           finished = TRUE;
9497           success = TRUE;
9498         }
9499       }
9500
9501       if (action != ACTION_NONE && !finished)
9502       {
9503         for (x = 0; x < MAX_GRID_XSIZE; x++)
9504           for (y = 0; y < MAX_GRID_YSIZE; y++)
9505             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9506
9507         overlay.grid_button_highlight = grid_button[step_nr];
9508
9509         // configure next virtual button
9510
9511         ClearField();
9512
9513         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9514         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9515         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9516       }
9517
9518       if (set_grid_button)
9519       {
9520         overlay.grid_button[x][y] =
9521           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9522            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9523            grid_button_tmp[x][y]);
9524
9525         set_grid_button = FALSE;
9526       }
9527     }
9528
9529     BackToFront();
9530   }
9531
9532   for (x = 0; x < MAX_GRID_XSIZE; x++)
9533     for (y = 0; y < MAX_GRID_YSIZE; y++)
9534       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9535
9536   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9537
9538   SetOverlayShowGrid(FALSE);
9539
9540   return success;
9541 }
9542
9543 void ConfigureVirtualButtons(void)
9544 {
9545   boolean success = ConfigureVirtualButtonsMain();
9546
9547   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9548                          SCREEN_MASK_TOUCH2);
9549
9550   if (success)
9551   {
9552     int font_nr = FONT_TITLE_1;
9553     int font_height = getFontHeight(font_nr);
9554     int ypos1 = SYSIZE / 2 - font_height * 2;
9555     int ypos2 = SYSIZE / 2 - font_height * 1;
9556     unsigned int wait_frame_delay = 0;
9557     unsigned int wait_frame_delay_value = 2000;
9558
9559     ResetDelayCounter(&wait_frame_delay);
9560
9561     ClearField();
9562
9563     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9564     DrawTextSCentered(ypos2, font_nr, "configured!");
9565
9566     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9567       BackToFront();
9568
9569     ClearEventQueue();
9570   }
9571 }
9572
9573 void DrawSetupScreen(void)
9574 {
9575   align_xoffset = 0;
9576   align_yoffset = 0;
9577
9578   if (setup_mode == SETUP_MODE_INPUT)
9579     DrawSetupScreen_Input();
9580   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9581     DrawChooseTree(&scores_type_current);
9582   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9583     DrawChooseTree(&game_speed_current);
9584   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9585     DrawChooseTree(&scroll_delay_current);
9586   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9587     DrawChooseTree(&snapshot_mode_current);
9588   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9589     DrawChooseTree(&window_size_current);
9590   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9591     DrawChooseTree(&scaling_type_current);
9592   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9593     DrawChooseTree(&rendering_mode_current);
9594   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9595     DrawChooseTree(&vsync_mode_current);
9596   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9597     DrawChooseTree(&artwork.gfx_current);
9598   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9599     DrawChooseTree(&artwork.snd_current);
9600   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9601     DrawChooseTree(&artwork.mus_current);
9602   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9603     DrawChooseTree(&volume_simple_current);
9604   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9605     DrawChooseTree(&volume_loops_current);
9606   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9607     DrawChooseTree(&volume_music_current);
9608   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9609     DrawChooseTree(&touch_control_current);
9610   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9611     DrawChooseTree(&move_distance_current);
9612   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9613     DrawChooseTree(&drop_distance_current);
9614   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9615     DrawChooseTree(&transparency_current);
9616   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9617     DrawChooseTree(&grid_size_current[0][0]);
9618   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9619     DrawChooseTree(&grid_size_current[0][1]);
9620   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9621     DrawChooseTree(&grid_size_current[1][0]);
9622   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9623     DrawChooseTree(&grid_size_current[1][1]);
9624   else
9625     DrawSetupScreen_Generic();
9626
9627   PlayMenuSoundsAndMusic();
9628 }
9629
9630 void RedrawSetupScreenAfterFullscreenToggle(void)
9631 {
9632   if (setup_mode == SETUP_MODE_GRAPHICS ||
9633       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9634   {
9635     // update list selection from "setup.window_scaling_percent"
9636     execSetupGraphics_setWindowSizes(TRUE);
9637
9638     DrawSetupScreen();
9639   }
9640 }
9641
9642 void RedrawSetupScreenAfterScreenRotation(int nr)
9643 {
9644   int x, y;
9645
9646   if (setup_mode == SETUP_MODE_TOUCH)
9647   {
9648     // update virtual button settings (depending on screen orientation)
9649     DrawSetupScreen();
9650   }
9651   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
9652   {
9653     // save already configured virtual buttons
9654     for (x = 0; x < MAX_GRID_XSIZE; x++)
9655       for (y = 0; y < MAX_GRID_YSIZE; y++)
9656         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9657   }
9658 }
9659
9660 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
9661 {
9662   if (setup_mode == SETUP_MODE_INPUT)
9663     HandleSetupScreen_Input(mx, my, dx, dy, button);
9664   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9665     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
9666   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9667     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
9668   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9669     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
9670   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9671     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
9672   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9673     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
9674   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9675     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
9676   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9677     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
9678   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9679     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
9680   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9681     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
9682   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9683     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
9684   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9685     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
9686   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9687     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
9688   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9689     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
9690   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9691     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
9692   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9693     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
9694   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9695     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
9696   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9697     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
9698   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9699     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
9700   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9701     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
9702   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9703     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
9704   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9705     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
9706   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9707     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
9708   else
9709     HandleSetupScreen_Generic(mx, my, dx, dy, button);
9710 }
9711
9712 void HandleGameActions(void)
9713 {
9714   if (setup.ask_on_game_over)
9715     CheckGameOver();
9716
9717   if (game.restart_game_message != NULL)
9718   {
9719     RequestRestartGame(game.restart_game_message);
9720
9721     return;
9722   }
9723
9724   if (game_status != GAME_MODE_PLAYING)
9725     return;
9726
9727   GameActions();                // main game loop
9728
9729   if (tape.auto_play && !tape.playing)
9730     AutoPlayTapesContinue();    // continue automatically playing next tape
9731 }
9732
9733
9734 // ---------- new screen button stuff --------------------------------------
9735
9736 static struct
9737 {
9738   int gfx_unpressed, gfx_pressed;
9739   struct MenuPosInfo *pos;
9740   boolean *check_value;
9741   int gadget_id;
9742   int screen_mask;
9743   unsigned int event_mask;
9744   boolean is_touch_button;
9745   char *infotext;
9746 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
9747 {
9748   {
9749     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
9750     &menu.main.button.prev_level, NULL,
9751     SCREEN_CTRL_ID_PREV_LEVEL,
9752     SCREEN_MASK_MAIN,
9753     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9754     FALSE, "previous level"
9755   },
9756   {
9757     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
9758     &menu.main.button.next_level, NULL,
9759     SCREEN_CTRL_ID_NEXT_LEVEL,
9760     SCREEN_MASK_MAIN,
9761     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9762     FALSE, "next level"
9763   },
9764   {
9765     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE,
9766     &menu.scores.button.prev_level, NULL,
9767     SCREEN_CTRL_ID_PREV_LEVEL2,
9768     SCREEN_MASK_SCORES,
9769     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9770     FALSE, "previous level"
9771   },
9772   {
9773     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE,
9774     &menu.scores.button.next_level, NULL,
9775     SCREEN_CTRL_ID_NEXT_LEVEL2,
9776     SCREEN_MASK_SCORES,
9777     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9778     FALSE, "next level"
9779   },
9780   {
9781     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE,
9782     &menu.main.button.first_level, NULL,
9783     SCREEN_CTRL_ID_FIRST_LEVEL,
9784     SCREEN_MASK_MAIN,
9785     GD_EVENT_RELEASED,
9786     FALSE, "first level"
9787   },
9788   {
9789     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE,
9790     &menu.main.button.last_level, NULL,
9791     SCREEN_CTRL_ID_LAST_LEVEL,
9792     SCREEN_MASK_MAIN,
9793     GD_EVENT_RELEASED,
9794     FALSE, "last level"
9795   },
9796   {
9797     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE,
9798     &menu.main.button.level_number, NULL,
9799     SCREEN_CTRL_ID_LEVEL_NUMBER,
9800     SCREEN_MASK_MAIN,
9801     GD_EVENT_RELEASED,
9802     FALSE, "level number"
9803   },
9804   {
9805     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
9806     &menu.setup.button.prev_player, NULL,
9807     SCREEN_CTRL_ID_PREV_PLAYER,
9808     SCREEN_MASK_INPUT,
9809     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9810     FALSE, "previous player"
9811   },
9812   {
9813     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
9814     &menu.setup.button.next_player, NULL,
9815     SCREEN_CTRL_ID_NEXT_PLAYER,
9816     SCREEN_MASK_INPUT,
9817     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9818     FALSE, "next player"
9819   },
9820   {
9821     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE,
9822     &menu.main.button.insert_solution, NULL,
9823     SCREEN_CTRL_ID_INSERT_SOLUTION,
9824     SCREEN_MASK_MAIN_HAS_SOLUTION,
9825     GD_EVENT_RELEASED,
9826     FALSE, "insert solution tape"
9827   },
9828   {
9829     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE,
9830     &menu.main.button.play_solution, NULL,
9831     SCREEN_CTRL_ID_PLAY_SOLUTION,
9832     SCREEN_MASK_MAIN_HAS_SOLUTION,
9833     GD_EVENT_RELEASED,
9834     FALSE, "play solution tape"
9835   },
9836   {
9837     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE,
9838     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
9839     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
9840     SCREEN_MASK_MAIN,
9841     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
9842     FALSE, "switch ECS/AGA chipset"
9843   },
9844   {
9845     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK,
9846     &menu.setup.button.touch_back, NULL,
9847     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
9848     SCREEN_MASK_TOUCH,
9849     GD_EVENT_RELEASED,
9850     TRUE, "previous page"
9851   },
9852   {
9853     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT,
9854     &menu.setup.button.touch_next, NULL,
9855     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
9856     SCREEN_MASK_TOUCH,
9857     GD_EVENT_RELEASED,
9858     TRUE, "next page"
9859   },
9860   {
9861     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2,
9862     &menu.setup.button.touch_back2, NULL,
9863     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
9864     SCREEN_MASK_TOUCH2,
9865     GD_EVENT_RELEASED,
9866     TRUE, "previous page"
9867   },
9868   {
9869     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2,
9870     &menu.setup.button.touch_next2, NULL,
9871     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
9872     SCREEN_MASK_TOUCH2,
9873     GD_EVENT_RELEASED,
9874     TRUE, "next page"
9875   },
9876 };
9877
9878 static struct
9879 {
9880   int gfx_unpressed, gfx_pressed;
9881   int x, y;
9882   int gadget_id;
9883   char *infotext;
9884 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
9885 {
9886   {
9887     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
9888     -1, -1,     // these values are not constant, but can change at runtime
9889     SCREEN_CTRL_ID_SCROLL_UP,
9890     "scroll up"
9891   },
9892   {
9893     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
9894     -1, -1,     // these values are not constant, but can change at runtime
9895     SCREEN_CTRL_ID_SCROLL_DOWN,
9896     "scroll down"
9897   }
9898 };
9899
9900 static struct
9901 {
9902   int gfx_unpressed, gfx_pressed;
9903   int x, y;
9904   int width, height;
9905   int type;
9906   int gadget_id;
9907   char *infotext;
9908 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
9909 {
9910   {
9911     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
9912     -1, -1,     // these values are not constant, but can change at runtime
9913     -1, -1,     // these values are not constant, but can change at runtime
9914     GD_TYPE_SCROLLBAR_VERTICAL,
9915     SCREEN_CTRL_ID_SCROLL_VERTICAL,
9916     "scroll level series vertically"
9917   }
9918 };
9919
9920 static struct
9921 {
9922   int graphic;
9923   int gadget_id;
9924   int x, y;
9925   int size;
9926   char *value;
9927   char *infotext;
9928 } textinput_info[NUM_SCREEN_TEXTINPUT] =
9929 {
9930   {
9931     IMG_SETUP_INPUT_TEXT,
9932     SCREEN_CTRL_ID_NETWORK_SERVER,
9933     -1, -1,     // these values are not constant, but can change at runtime
9934     MAX_SETUP_TEXT_INPUT_LEN,
9935     network_server_hostname,
9936     "Network Server Hostname / IP"
9937   },
9938 };
9939
9940 static void CreateScreenMenubuttons(void)
9941 {
9942   struct GadgetInfo *gi;
9943   unsigned int event_mask;
9944   int i;
9945
9946   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9947   {
9948     struct MenuPosInfo *pos = menubutton_info[i].pos;
9949     int screen_mask = menubutton_info[i].screen_mask;
9950     boolean is_touch_button = menubutton_info[i].is_touch_button;
9951     boolean is_check_button = menubutton_info[i].check_value != NULL;
9952     boolean is_score_button = (screen_mask == SCREEN_MASK_SCORES);
9953     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9954     int gfx_unpressed, gfx_pressed;
9955     int x, y, width, height;
9956     int gd_x1, gd_x2, gd_y1, gd_y2;
9957     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
9958     int id = menubutton_info[i].gadget_id;
9959     int type = GD_TYPE_NORMAL_BUTTON;
9960     boolean checked = FALSE;
9961
9962     event_mask = menubutton_info[i].event_mask;
9963
9964     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
9965     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
9966
9967     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
9968     height = graphic_info[menubutton_info[i].gfx_pressed].height;
9969
9970     gfx_unpressed = menubutton_info[i].gfx_unpressed;
9971     gfx_pressed   = menubutton_info[i].gfx_pressed;
9972     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9973     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9974     gd_x1 = graphic_info[gfx_unpressed].src_x;
9975     gd_y1 = graphic_info[gfx_unpressed].src_y;
9976     gd_x2 = graphic_info[gfx_pressed].src_x;
9977     gd_y2 = graphic_info[gfx_pressed].src_y;
9978     gd_x1a = gd_x1;
9979     gd_y1a = gd_y1;
9980     gd_x2a = gd_x2;
9981     gd_y2a = gd_y2;
9982
9983     if (is_touch_button)
9984     {
9985       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
9986       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
9987     }
9988
9989     if (is_check_button)
9990     {
9991       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
9992       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
9993       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
9994       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
9995
9996       type = GD_TYPE_CHECK_BUTTON;
9997       checked = *menubutton_info[i].check_value;
9998     }
9999
10000     if (is_score_button)
10001     {
10002       // if x/y set to -1, dynamically place buttons next to title text
10003       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
10004
10005       if (pos->x == -1)
10006         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
10007              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
10008              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
10009              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
10010
10011       if (pos->y == -1)
10012         y = mSY + MENU_TITLE1_YPOS;
10013     }
10014
10015     gi = CreateGadget(GDI_CUSTOM_ID, id,
10016                       GDI_CUSTOM_TYPE_ID, i,
10017                       GDI_IMAGE_ID, gfx_unpressed,
10018                       GDI_INFO_TEXT, menubutton_info[i].infotext,
10019                       GDI_X, x,
10020                       GDI_Y, y,
10021                       GDI_WIDTH, width,
10022                       GDI_HEIGHT, height,
10023                       GDI_TYPE, type,
10024                       GDI_STATE, GD_BUTTON_UNPRESSED,
10025                       GDI_CHECKED, checked,
10026                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10027                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10028                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1a, gd_y1a,
10029                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2a, gd_y2a,
10030                       GDI_DIRECT_DRAW, FALSE,
10031                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
10032                       GDI_EVENT_MASK, event_mask,
10033                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10034                       GDI_END);
10035
10036     if (gi == NULL)
10037       Fail("cannot create gadget");
10038
10039     screen_gadget[id] = gi;
10040   }
10041 }
10042
10043 static void CreateScreenScrollbuttons(void)
10044 {
10045   struct GadgetInfo *gi;
10046   unsigned int event_mask;
10047   int i;
10048
10049   // these values are not constant, but can change at runtime
10050   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
10051   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
10052   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
10053   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
10054
10055   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10056   {
10057     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10058     int gfx_unpressed, gfx_pressed;
10059     int x, y, width, height;
10060     int gd_x1, gd_x2, gd_y1, gd_y2;
10061     int id = scrollbutton_info[i].gadget_id;
10062
10063     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
10064
10065     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
10066     y = mSY + scrollbutton_info[i].y;
10067     width = SC_SCROLLBUTTON_XSIZE;
10068     height = SC_SCROLLBUTTON_YSIZE;
10069
10070     // correct scrollbar position if placed outside menu (playfield) area
10071     if (x > SX + SC_SCROLL_UP_XPOS)
10072       x = SX + SC_SCROLL_UP_XPOS;
10073
10074     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
10075       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
10076                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
10077
10078     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
10079     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
10080     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10081     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10082     gd_x1 = graphic_info[gfx_unpressed].src_x;
10083     gd_y1 = graphic_info[gfx_unpressed].src_y;
10084     gd_x2 = graphic_info[gfx_pressed].src_x;
10085     gd_y2 = graphic_info[gfx_pressed].src_y;
10086
10087     gi = CreateGadget(GDI_CUSTOM_ID, id,
10088                       GDI_CUSTOM_TYPE_ID, i,
10089                       GDI_IMAGE_ID, gfx_unpressed,
10090                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
10091                       GDI_X, x,
10092                       GDI_Y, y,
10093                       GDI_WIDTH, width,
10094                       GDI_HEIGHT, height,
10095                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
10096                       GDI_STATE, GD_BUTTON_UNPRESSED,
10097                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10098                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10099                       GDI_DIRECT_DRAW, FALSE,
10100                       GDI_EVENT_MASK, event_mask,
10101                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10102                       GDI_END);
10103
10104     if (gi == NULL)
10105       Fail("cannot create gadget");
10106
10107     screen_gadget[id] = gi;
10108   }
10109 }
10110
10111 static void CreateScreenScrollbars(void)
10112 {
10113   int i;
10114
10115   // these values are not constant, but can change at runtime
10116   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
10117   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
10118   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
10119   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
10120
10121   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10122   {
10123     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10124     int gfx_unpressed, gfx_pressed;
10125     int x, y, width, height;
10126     int gd_x1, gd_x2, gd_y1, gd_y2;
10127     struct GadgetInfo *gi;
10128     int items_max, items_visible, item_position;
10129     unsigned int event_mask;
10130     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
10131     int id = scrollbar_info[i].gadget_id;
10132
10133     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
10134
10135     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
10136     y = mSY + scrollbar_info[i].y;
10137     width  = scrollbar_info[i].width;
10138     height = scrollbar_info[i].height;
10139
10140     // correct scrollbar position if placed outside menu (playfield) area
10141     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
10142       x = SX + SC_SCROLL_VERTICAL_XPOS;
10143
10144     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
10145       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
10146
10147     items_max = num_page_entries;
10148     items_visible = num_page_entries;
10149     item_position = 0;
10150
10151     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
10152     gfx_pressed   = scrollbar_info[i].gfx_pressed;
10153     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10154     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10155     gd_x1 = graphic_info[gfx_unpressed].src_x;
10156     gd_y1 = graphic_info[gfx_unpressed].src_y;
10157     gd_x2 = graphic_info[gfx_pressed].src_x;
10158     gd_y2 = graphic_info[gfx_pressed].src_y;
10159
10160     gi = CreateGadget(GDI_CUSTOM_ID, id,
10161                       GDI_CUSTOM_TYPE_ID, i,
10162                       GDI_IMAGE_ID, gfx_unpressed,
10163                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
10164                       GDI_X, x,
10165                       GDI_Y, y,
10166                       GDI_WIDTH, width,
10167                       GDI_HEIGHT, height,
10168                       GDI_TYPE, scrollbar_info[i].type,
10169                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
10170                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
10171                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
10172                       GDI_WHEEL_AREA_X, SX,
10173                       GDI_WHEEL_AREA_Y, SY,
10174                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
10175                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
10176                       GDI_STATE, GD_BUTTON_UNPRESSED,
10177                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10178                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10179                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
10180                       GDI_DIRECT_DRAW, FALSE,
10181                       GDI_EVENT_MASK, event_mask,
10182                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10183                       GDI_END);
10184
10185     if (gi == NULL)
10186       Fail("cannot create gadget");
10187
10188     screen_gadget[id] = gi;
10189   }
10190 }
10191
10192 static void CreateScreenTextInputGadgets(void)
10193 {
10194   int i;
10195
10196   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
10197   {
10198     int graphic = textinput_info[i].graphic;
10199     struct GraphicInfo *gd = &graphic_info[graphic];
10200     int gd_x1 = gd->src_x;
10201     int gd_y1 = gd->src_y;
10202     int gd_x2 = gd->src_x + gd->active_xoffset;
10203     int gd_y2 = gd->src_y + gd->active_yoffset;
10204     struct GadgetInfo *gi;
10205     unsigned int event_mask;
10206     int id = textinput_info[i].gadget_id;
10207     int x = textinput_info[i].x;
10208     int y = textinput_info[i].y;
10209
10210     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
10211
10212     gi = CreateGadget(GDI_CUSTOM_ID, id,
10213                       GDI_CUSTOM_TYPE_ID, i,
10214                       GDI_INFO_TEXT, textinput_info[i].infotext,
10215                       GDI_X, SX + x,
10216                       GDI_Y, SY + y,
10217                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
10218                       GDI_TEXT_VALUE, textinput_info[i].value,
10219                       GDI_TEXT_SIZE, textinput_info[i].size,
10220                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
10221                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
10222                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
10223                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
10224                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
10225                       GDI_DESIGN_WIDTH, gd->width,
10226                       GDI_EVENT_MASK, event_mask,
10227                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10228                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
10229                       GDI_END);
10230
10231     if (gi == NULL)
10232       Fail("cannot create gadget");
10233
10234     screen_gadget[id] = gi;
10235   }
10236 }
10237
10238 void CreateScreenGadgets(void)
10239 {
10240   CreateScreenMenubuttons();
10241
10242   CreateScreenScrollbuttons();
10243   CreateScreenScrollbars();
10244
10245   CreateScreenTextInputGadgets();
10246 }
10247
10248 void FreeScreenGadgets(void)
10249 {
10250   int i;
10251
10252   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
10253     FreeGadget(screen_gadget[i]);
10254 }
10255
10256 static void RedrawScreenMenuGadgets(int screen_mask)
10257 {
10258   int i;
10259
10260   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10261     if (screen_mask & menubutton_info[i].screen_mask)
10262       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
10263 }
10264
10265 static void MapScreenMenuGadgets(int screen_mask)
10266 {
10267   int i;
10268
10269   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10270     if (screen_mask & menubutton_info[i].screen_mask)
10271       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10272 }
10273
10274 static void UnmapScreenMenuGadgets(int screen_mask)
10275 {
10276   int i;
10277
10278   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10279   {
10280     if (screen_mask & menubutton_info[i].screen_mask)
10281     {
10282       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10283
10284       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
10285         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
10286                        screen_gadget[menubutton_info[i].gadget_id]->y,
10287                        screen_gadget[menubutton_info[i].gadget_id]->width,
10288                        screen_gadget[menubutton_info[i].gadget_id]->height);
10289     }
10290   }
10291 }
10292
10293 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
10294 {
10295   if (map_gadgets)
10296     MapScreenMenuGadgets(screen_mask);
10297   else
10298     UnmapScreenMenuGadgets(screen_mask);
10299 }
10300
10301 static void MapScreenGadgets(int num_entries)
10302 {
10303   int i;
10304
10305   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
10306     return;
10307
10308   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10309     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10310
10311   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10312     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10313 }
10314
10315 static void UnmapScreenGadgets()
10316 {
10317   int i;
10318
10319   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10320     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10321
10322   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10323     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10324 }
10325
10326 static void MapScreenTreeGadgets(TreeInfo *ti)
10327 {
10328   MapScreenGadgets(numTreeInfoInGroup(ti));
10329 }
10330
10331 static void UnmapScreenTreeGadgets(void)
10332 {
10333   UnmapScreenGadgets();
10334 }
10335
10336 static void HandleScreenGadgets(struct GadgetInfo *gi)
10337 {
10338   int id = gi->custom_id;
10339   int button = gi->event.button;
10340   int step = (button == MB_LEFTBUTTON   ? 1 :
10341               button == MB_MIDDLEBUTTON ? 5 :
10342               button == MB_RIGHTBUTTON  ? 10 : 1);
10343
10344   switch (id)
10345   {
10346     case SCREEN_CTRL_ID_PREV_LEVEL:
10347       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10348       break;
10349
10350     case SCREEN_CTRL_ID_NEXT_LEVEL:
10351       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10352       break;
10353
10354     case SCREEN_CTRL_ID_PREV_LEVEL2:
10355       HandleHallOfFame_SelectLevel(step, -1);
10356       break;
10357
10358     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10359       HandleHallOfFame_SelectLevel(step, +1);
10360       break;
10361
10362     case SCREEN_CTRL_ID_FIRST_LEVEL:
10363       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10364       break;
10365
10366     case SCREEN_CTRL_ID_LAST_LEVEL:
10367       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10368       break;
10369
10370     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10371       CloseDoor(DOOR_CLOSE_2);
10372       SetGameStatus(GAME_MODE_LEVELNR);
10373       DrawChooseLevelNr();
10374       break;
10375
10376     case SCREEN_CTRL_ID_PREV_PLAYER:
10377       HandleSetupScreen_Input_Player(step, -1);
10378       break;
10379
10380     case SCREEN_CTRL_ID_NEXT_PLAYER:
10381       HandleSetupScreen_Input_Player(step, +1);
10382       break;
10383
10384     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10385       InsertSolutionTape();
10386       break;
10387
10388     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10389       PlaySolutionTape();
10390       break;
10391
10392     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10393       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10394       DrawMainMenu();
10395       break;
10396
10397     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10398     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10399     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10400     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10401       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10402       break;
10403
10404     case SCREEN_CTRL_ID_SCROLL_UP:
10405       if (game_status == GAME_MODE_NAMES)
10406         HandleChoosePlayerName(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10407       else if (game_status == GAME_MODE_LEVELS)
10408         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10409       else if (game_status == GAME_MODE_LEVELNR)
10410         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10411       else if (game_status == GAME_MODE_SETUP)
10412         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10413       else if (game_status == GAME_MODE_INFO)
10414         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10415       else if (game_status == GAME_MODE_SCORES)
10416         HandleHallOfFame(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10417       break;
10418
10419     case SCREEN_CTRL_ID_SCROLL_DOWN:
10420       if (game_status == GAME_MODE_NAMES)
10421         HandleChoosePlayerName(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10422       else if (game_status == GAME_MODE_LEVELS)
10423         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10424       else if (game_status == GAME_MODE_LEVELNR)
10425         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10426       else if (game_status == GAME_MODE_SETUP)
10427         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10428       else if (game_status == GAME_MODE_INFO)
10429         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10430       else if (game_status == GAME_MODE_SCORES)
10431         HandleHallOfFame(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10432       break;
10433
10434     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
10435       if (game_status == GAME_MODE_NAMES)
10436         HandleChoosePlayerName(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10437       else if (game_status == GAME_MODE_LEVELS)
10438         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10439       else if (game_status == GAME_MODE_LEVELNR)
10440         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10441       else if (game_status == GAME_MODE_SETUP)
10442         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10443       else if (game_status == GAME_MODE_INFO)
10444         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10445       else if (game_status == GAME_MODE_SCORES)
10446         HandleHallOfFame(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10447       break;
10448
10449     case SCREEN_CTRL_ID_NETWORK_SERVER:
10450     {
10451       if (!strEqual(gi->textinput.value, ""))
10452       {
10453         setString(&setup.network_server_hostname, gi->textinput.value);
10454
10455         network.server_host = setup.network_server_hostname;
10456       }
10457       else
10458       {
10459         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
10460
10461         network.server_host = NULL;
10462       }
10463
10464       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
10465         network.server_host = NULL;
10466
10467       execSetupGame_setNetworkServerText();
10468
10469       DrawSetupScreen();
10470
10471       break;
10472     }
10473
10474     default:
10475       break;
10476   }
10477 }
10478
10479 void DumpScreenIdentifiers(void)
10480 {
10481   int i;
10482
10483   Print("Active screen elements on current screen:\n");
10484
10485   for (i = 0; main_controls[i].nr != -1; i++)
10486   {
10487     struct MainControlInfo *mci = &main_controls[i];
10488
10489     if (mci->button_graphic != -1)
10490     {
10491       char *token = getTokenFromImageID(mci->button_graphic);
10492
10493       Print("- '%s'\n", token);
10494     }
10495   }
10496
10497   Print("Done.\n");
10498 }
10499
10500 boolean DoScreenAction(int image_id)
10501 {
10502   int i;
10503
10504   if (game_status != GAME_MODE_MAIN)
10505     return FALSE;
10506
10507   for (i = 0; main_controls[i].nr != -1; i++)
10508   {
10509     struct MainControlInfo *mci = &main_controls[i];
10510     struct MenuPosInfo *pos = mci->pos_button;
10511
10512     if (mci->button_graphic == image_id)
10513     {
10514       int x = mSX + pos->x;
10515       int y = mSY + pos->y;
10516
10517       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
10518
10519       return TRUE;
10520     }
10521   }
10522
10523   return FALSE;
10524 }
10525
10526 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
10527 {
10528   // get tree info node of newly added level or artwork set
10529   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
10530   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
10531                                                       tree_subdir_new);
10532   if (tree_node_new == NULL)    // should not happen
10533     return;
10534
10535   // if request dialog is active, do nothing
10536   if (game.request_active)
10537     return;
10538
10539   if (game_status == GAME_MODE_MAIN &&
10540       tree_type == TREE_TYPE_LEVEL_DIR)
10541   {
10542     // when adding new level set in main menu, select it as current level set
10543
10544     // change current level set to newly added level set from zip file
10545     leveldir_current = tree_node_new;
10546
10547     // change current level number to first level of newly added level set
10548     level_nr = leveldir_current->first_level;
10549
10550     // redraw screen to reflect changed level set
10551     DrawMainMenu();
10552
10553     // save this level set and level number as last selected level set
10554     SaveLevelSetup_LastSeries();
10555     SaveLevelSetup_SeriesInfo();
10556   }
10557   else if (game_status == GAME_MODE_LEVELS &&
10558            tree_type == TREE_TYPE_LEVEL_DIR)
10559   {
10560     // when adding new level set in level set menu, set cursor and update screen
10561
10562     leveldir_current = tree_node_new;
10563
10564     DrawChooseTree(&leveldir_current);
10565   }
10566   else if (game_status == GAME_MODE_SETUP)
10567   {
10568     // when adding new artwork set in setup menu, set cursor and update screen
10569
10570     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
10571         tree_type == TREE_TYPE_GRAPHICS_DIR)
10572     {
10573       artwork.gfx_current = tree_node_new;
10574
10575       DrawChooseTree(&artwork.gfx_current);
10576     }
10577     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
10578              tree_type == TREE_TYPE_SOUNDS_DIR)
10579     {
10580       artwork.snd_current = tree_node_new;
10581
10582       DrawChooseTree(&artwork.snd_current);
10583     }
10584     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
10585              tree_type == TREE_TYPE_MUSIC_DIR)
10586     {
10587       artwork.mus_current = tree_node_new;
10588
10589       DrawChooseTree(&artwork.mus_current);
10590     }
10591   }
10592 }
10593
10594 static int UploadTapes(void)
10595 {
10596   SetGameStatus(GAME_MODE_LOADING);
10597
10598   FadeSetEnterScreen();
10599   FadeOut(REDRAW_ALL);
10600
10601   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
10602
10603   FadeIn(REDRAW_ALL);
10604
10605   DrawInitTextHead("Uploading tapes");
10606
10607   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
10608   global.autoplay_leveldir = "ALL";
10609   global.autoplay_all = TRUE;
10610
10611   int num_tapes_uploaded = AutoPlayTapes();
10612
10613   global.autoplay_mode = AUTOPLAY_MODE_NONE;
10614   global.autoplay_leveldir = NULL;
10615   global.autoplay_all = FALSE;
10616
10617   SetGameStatus(GAME_MODE_MAIN);
10618
10619   DrawMainMenu();
10620
10621   return num_tapes_uploaded;
10622 }
10623
10624 static boolean OfferUploadTapes(void)
10625 {
10626   if (!Request(setup.has_remaining_tapes ?
10627                "Upload missing tapes to the high score server now?" :
10628                "Upload all your tapes to the high score server now?", REQ_ASK))
10629     return FALSE;
10630
10631   int num_tapes_uploaded = UploadTapes();
10632   char message[100];
10633
10634   if (num_tapes_uploaded < 0)
10635   {
10636     num_tapes_uploaded = -num_tapes_uploaded - 1;
10637
10638     if (num_tapes_uploaded == 0)
10639       sprintf(message, "Upload failed! No tapes uploaded!");
10640     else if (num_tapes_uploaded == 1)
10641       sprintf(message, "Upload failed! Only 1 tape uploaded!");
10642     else
10643       sprintf(message, "Upload failed! Only %d tapes uploaded!",
10644               num_tapes_uploaded);
10645
10646     Request(message, REQ_CONFIRM);
10647
10648     // if uploading tapes failed, add tape upload entry to setup menu
10649     setup.provide_uploading_tapes = TRUE;
10650     setup.has_remaining_tapes = TRUE;
10651
10652     SaveSetup_ServerSetup();
10653
10654     return FALSE;
10655   }
10656
10657   if (num_tapes_uploaded == 0)
10658     sprintf(message, "No tapes uploaded!");
10659   else if (num_tapes_uploaded == 1)
10660     sprintf(message, "1 tape uploaded!");
10661   else
10662     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
10663
10664   Request(message, REQ_CONFIRM);
10665
10666   if (num_tapes_uploaded > 0)
10667     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
10668
10669   // after all tapes have been uploaded, remove entry from setup menu
10670   setup.provide_uploading_tapes = FALSE;
10671   setup.has_remaining_tapes = FALSE;
10672
10673   SaveSetup_ServerSetup();
10674
10675   return TRUE;
10676 }
10677
10678 static void CheckUploadTapes(void)
10679 {
10680   if (!setup.ask_for_uploading_tapes)
10681     return;
10682
10683   // after asking for uploading tapes, do not ask again
10684   setup.ask_for_uploading_tapes = FALSE;
10685   setup.ask_for_remaining_tapes = FALSE;
10686
10687   if (directoryExists(getTapeDir(NULL)))
10688   {
10689     boolean tapes_uploaded = OfferUploadTapes();
10690
10691     if (!tapes_uploaded)
10692     {
10693       Request(setup.has_remaining_tapes ?
10694               "You can upload missing tapes from the setup menu later!" :
10695               "You can upload your tapes from the setup menu later!",
10696               REQ_CONFIRM);
10697     }
10698   }
10699   else
10700   {
10701     // if tapes directory does not exist yet, never offer uploading all tapes
10702     setup.provide_uploading_tapes = FALSE;
10703   }
10704
10705   SaveSetup_ServerSetup();
10706 }
10707
10708 static void UpgradePlayerUUID(void)
10709 {
10710   ApiResetUUIDAsThread(getUUID());
10711 }
10712
10713 static void CheckUpgradePlayerUUID(void)
10714 {
10715   if (setup.player_version > 1)
10716     return;
10717
10718   UpgradePlayerUUID();
10719 }
10720
10721 void CheckApiServerTasks(void)
10722 {
10723   // check if the player's UUID has to be upgraded
10724   CheckUpgradePlayerUUID();
10725
10726   // check if there are any tapes to be uploaded
10727   CheckUploadTapes();
10728 }