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