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