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