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