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