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