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