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