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