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