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