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