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