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