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