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