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