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