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