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