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