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