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