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