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