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