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