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