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