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