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