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