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