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