moved code to get rank string for hall of fame 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(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   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_SCOREINFO);
5879
5880   UnmapAllGadgets();
5881
5882   FadeOut(REDRAW_FIELD);
5883
5884   ClearField();
5885
5886   drawChooseTreeHead(score_entries);
5887   drawChooseTreeInfo(score_entries);
5888
5889   DrawTextSCentered(ystart, font_title, "Score Information:");
5890   ystart += ystep_title;
5891
5892   DrawTextF(xstart1, ystart, font_head, "Level Set");
5893   DrawTextF(xstart2, ystart, font_text, leveldir_current->name);
5894   ystart += ystep_line;
5895
5896   DrawTextF(xstart1, ystart, font_head, "Level Name");
5897   DrawTextF(xstart2, ystart, font_text, level.name);
5898   ystart += ystep_para;
5899
5900   DrawTextF(xstart1, ystart, font_head, "Rank");
5901   DrawTextF(xstart2, ystart, font_text, pos_text);
5902   ystart += ystep_line;
5903
5904   DrawTextF(xstart1, ystart, font_head, "Player");
5905   DrawTextF(xstart2, ystart, font_text, entry->name);
5906   ystart += ystep_line;
5907
5908   if (level.use_step_counter)
5909   {
5910     DrawTextF(xstart1, ystart, font_head, "Steps");
5911     DrawTextF(xstart2, ystart, font_text, int2str(entry->time, 5));
5912     ystart += ystep_line;
5913   }
5914   else
5915   {
5916     DrawTextF(xstart1, ystart, font_head, "Time");
5917     DrawTextF(xstart2, ystart, font_text, getHallOfFameTimeText(entry_nr));
5918     ystart += ystep_line;
5919   }
5920
5921   if (!level.rate_time_over_score || entry->score > 0)
5922   {
5923     DrawTextF(xstart1, ystart, font_head, "Score");
5924     DrawTextF(xstart2, ystart, font_text, int2str(entry->score, 5));
5925     ystart += ystep_line;
5926   }
5927
5928   DrawTextSCentered(ybottom, font_foot, "Press any key or button to go back");
5929
5930   FadeIn(REDRAW_FIELD);
5931 }
5932
5933 void HandleScoreInfo(int mx, int my, int dx, int dy, int button)
5934 {
5935   if (button == MB_MENU_LEAVE || button == MB_MENU_CHOICE)
5936   {
5937     PlaySound(SND_MENU_ITEM_SELECTING);
5938
5939     SetGameStatus(GAME_MODE_SCORES);
5940
5941     DrawHallOfFame(level_nr);
5942   }
5943 }
5944
5945
5946 // ============================================================================
5947 // setup screen functions
5948 // ============================================================================
5949
5950 static struct TokenInfo *setup_info;
5951 static int num_setup_info;      // number of setup entries shown on screen
5952 static int max_setup_info;      // total number of setup entries in list
5953
5954 static char *window_size_text;
5955 static char *scaling_type_text;
5956 static char *rendering_mode_text;
5957 static char *vsync_mode_text;
5958 static char *scroll_delay_text;
5959 static char *snapshot_mode_text;
5960 static char *game_speed_text;
5961 static char *scores_type_text;
5962 static char *network_server_text;
5963 static char *graphics_set_name;
5964 static char *sounds_set_name;
5965 static char *music_set_name;
5966 static char *volume_simple_text;
5967 static char *volume_loops_text;
5968 static char *volume_music_text;
5969 static char *touch_controls_text;
5970 static char *move_distance_text;
5971 static char *drop_distance_text;
5972 static char *transparency_text;
5973 static char *grid_size_text[2][2];
5974
5975 static void execSetupMain(void)
5976 {
5977   setup_mode = SETUP_MODE_MAIN;
5978
5979   DrawSetupScreen();
5980 }
5981
5982 static void execSetupGame_setScoresType(void)
5983 {
5984   if (scores_types == NULL)
5985   {
5986     int i;
5987
5988     for (i = 0; scores_types_list[i].value != NULL; i++)
5989     {
5990       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5991       char identifier[32], name[32];
5992       char *value = scores_types_list[i].value;
5993       char *text = scores_types_list[i].text;
5994
5995       ti->node_top = &scores_types;
5996       ti->sort_priority = i;
5997
5998       sprintf(identifier, "%s", value);
5999       sprintf(name, "%s", text);
6000
6001       setString(&ti->identifier, identifier);
6002       setString(&ti->name, name);
6003       setString(&ti->name_sorting, name);
6004       setString(&ti->infotext, STR_SETUP_CHOOSE_SCORES_TYPE);
6005
6006       pushTreeInfo(&scores_types, ti);
6007     }
6008
6009     // sort scores type values to start with lowest scores type value
6010     sortTreeInfo(&scores_types);
6011
6012     // set current scores type value to configured scores type value
6013     scores_type_current =
6014       getTreeInfoFromIdentifier(scores_types, setup.scores_in_highscore_list);
6015
6016     // if that fails, set current scores type to reliable default value
6017     if (scores_type_current == NULL)
6018       scores_type_current =
6019         getTreeInfoFromIdentifier(scores_types, STR_SCORES_TYPE_DEFAULT);
6020
6021     // if that also fails, set current scores type to first available value
6022     if (scores_type_current == NULL)
6023       scores_type_current = scores_types;
6024   }
6025
6026   setup.scores_in_highscore_list = scores_type_current->identifier;
6027
6028   // needed for displaying scores type text instead of identifier
6029   scores_type_text = scores_type_current->name;
6030 }
6031
6032 static void execSetupGame_setGameSpeeds(boolean update_value)
6033 {
6034   if (setup.game_speed_extended)
6035   {
6036     game_speeds_list = game_speeds_list_extended;
6037     game_speeds      = game_speeds_extended;
6038   }
6039   else
6040   {
6041     game_speeds_list = game_speeds_list_normal;
6042     game_speeds      = game_speeds_normal;
6043   }
6044
6045   if (game_speeds == NULL)
6046   {
6047     int i;
6048
6049     for (i = 0; game_speeds_list[i].value != -1; i++)
6050     {
6051       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6052       char identifier[32], name[32];
6053       int value = game_speeds_list[i].value;
6054       char *text = game_speeds_list[i].text;
6055
6056       ti->node_top = &game_speeds;
6057       ti->sort_priority = 10000 - value;
6058
6059       sprintf(identifier, "%d", value);
6060       sprintf(name, "%s", text);
6061
6062       setString(&ti->identifier, identifier);
6063       setString(&ti->name, name);
6064       setString(&ti->name_sorting, name);
6065       setString(&ti->infotext, STR_SETUP_CHOOSE_GAME_SPEED);
6066
6067       pushTreeInfo(&game_speeds, ti);
6068     }
6069
6070     // sort game speed values to start with slowest game speed
6071     sortTreeInfo(&game_speeds);
6072
6073     update_value = TRUE;
6074   }
6075
6076   if (update_value)
6077   {
6078     // set current game speed to configured game speed value
6079     game_speed_current =
6080       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
6081
6082     // if that fails, set current game speed to reliable default value
6083     if (game_speed_current == NULL)
6084       game_speed_current =
6085         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
6086
6087     // if that also fails, set current game speed to first available speed
6088     if (game_speed_current == NULL)
6089       game_speed_current = game_speeds;
6090
6091     if (setup.game_speed_extended)
6092       game_speeds_extended = game_speeds;
6093     else
6094       game_speeds_normal = game_speeds;
6095   }
6096
6097   setup.game_frame_delay = atoi(game_speed_current->identifier);
6098
6099   // needed for displaying game speed text instead of identifier
6100   game_speed_text = game_speed_current->name;
6101 }
6102
6103 static void execSetupGame_setScrollDelays(void)
6104 {
6105   if (scroll_delays == NULL)
6106   {
6107     int i;
6108
6109     for (i = 0; scroll_delays_list[i].value != -1; i++)
6110     {
6111       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6112       char identifier[32], name[32];
6113       int value = scroll_delays_list[i].value;
6114       char *text = scroll_delays_list[i].text;
6115
6116       ti->node_top = &scroll_delays;
6117       ti->sort_priority = value;
6118
6119       sprintf(identifier, "%d", value);
6120       sprintf(name, "%s", text);
6121
6122       setString(&ti->identifier, identifier);
6123       setString(&ti->name, name);
6124       setString(&ti->name_sorting, name);
6125       setString(&ti->infotext, STR_SETUP_CHOOSE_SCROLL_DELAY);
6126
6127       pushTreeInfo(&scroll_delays, ti);
6128     }
6129
6130     // sort scroll delay values to start with lowest scroll delay value
6131     sortTreeInfo(&scroll_delays);
6132
6133     // set current scroll delay value to configured scroll delay value
6134     scroll_delay_current =
6135       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
6136
6137     // if that fails, set current scroll delay to reliable default value
6138     if (scroll_delay_current == NULL)
6139       scroll_delay_current =
6140         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
6141
6142     // if that also fails, set current scroll delay to first available value
6143     if (scroll_delay_current == NULL)
6144       scroll_delay_current = scroll_delays;
6145   }
6146
6147   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
6148
6149   // needed for displaying scroll delay text instead of identifier
6150   scroll_delay_text = scroll_delay_current->name;
6151 }
6152
6153 static void execSetupGame_setSnapshotModes(void)
6154 {
6155   if (snapshot_modes == NULL)
6156   {
6157     int i;
6158
6159     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
6160     {
6161       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6162       char identifier[32], name[32];
6163       char *value = snapshot_modes_list[i].value;
6164       char *text = snapshot_modes_list[i].text;
6165
6166       ti->node_top = &snapshot_modes;
6167       ti->sort_priority = i;
6168
6169       sprintf(identifier, "%s", value);
6170       sprintf(name, "%s", text);
6171
6172       setString(&ti->identifier, identifier);
6173       setString(&ti->name, name);
6174       setString(&ti->name_sorting, name);
6175       setString(&ti->infotext, STR_SETUP_CHOOSE_SNAPSHOT_MODE);
6176
6177       pushTreeInfo(&snapshot_modes, ti);
6178     }
6179
6180     // sort snapshot mode values to start with lowest snapshot mode value
6181     sortTreeInfo(&snapshot_modes);
6182
6183     // set current snapshot mode value to configured snapshot mode value
6184     snapshot_mode_current =
6185       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
6186
6187     // if that fails, set current snapshot mode to reliable default value
6188     if (snapshot_mode_current == NULL)
6189       snapshot_mode_current =
6190         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
6191
6192     // if that also fails, set current snapshot mode to first available value
6193     if (snapshot_mode_current == NULL)
6194       snapshot_mode_current = snapshot_modes;
6195   }
6196
6197   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
6198
6199   // needed for displaying snapshot mode text instead of identifier
6200   snapshot_mode_text = snapshot_mode_current->name;
6201 }
6202
6203 static void execSetupGame_setNetworkServerText(void)
6204 {
6205   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
6206   {
6207     strcpy(network_server_hostname, STR_NETWORK_AUTO_DETECT_SETUP);
6208   }
6209   else
6210   {
6211     strncpy(network_server_hostname, setup.network_server_hostname,
6212             MAX_SETUP_TEXT_INPUT_LEN);
6213     network_server_hostname[MAX_SETUP_TEXT_INPUT_LEN] = '\0';
6214   }
6215
6216   // needed for displaying network server text instead of identifier
6217   network_server_text = network_server_hostname;
6218 }
6219
6220 static void execSetupGame(void)
6221 {
6222   boolean check_vsync_mode = (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED);
6223
6224   execSetupGame_setGameSpeeds(FALSE);
6225   execSetupGame_setScoresType();
6226   execSetupGame_setScrollDelays();
6227   execSetupGame_setSnapshotModes();
6228
6229   execSetupGame_setNetworkServerText();
6230
6231   if (!setup.provide_uploading_tapes)
6232     setHideSetupEntry(execOfferUploadTapes);
6233
6234   setup_mode = SETUP_MODE_GAME;
6235
6236   DrawSetupScreen();
6237
6238   // check if vsync needs to be disabled for this game speed to work
6239   if (check_vsync_mode)
6240     DisableVsyncIfNeeded();
6241 }
6242
6243 static void execSetupChooseScoresType(void)
6244 {
6245   setup_mode = SETUP_MODE_CHOOSE_SCORES_TYPE;
6246
6247   DrawSetupScreen();
6248 }
6249
6250 static void execSetupChooseGameSpeed(void)
6251 {
6252   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
6253
6254   DrawSetupScreen();
6255 }
6256
6257 static void execSetupChooseScrollDelay(void)
6258 {
6259   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
6260
6261   DrawSetupScreen();
6262 }
6263
6264 static void execSetupChooseSnapshotMode(void)
6265 {
6266   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
6267
6268   DrawSetupScreen();
6269 }
6270
6271 static void execSetupEngines(void)
6272 {
6273   setup_mode = SETUP_MODE_ENGINES;
6274
6275   DrawSetupScreen();
6276 }
6277
6278 static void execSetupEditor(void)
6279 {
6280   setup_mode = SETUP_MODE_EDITOR;
6281
6282   DrawSetupScreen();
6283 }
6284
6285 static void execSetupGraphics_setWindowSizes(boolean update_list)
6286 {
6287   if (window_sizes != NULL && update_list)
6288   {
6289     freeTreeInfo(window_sizes);
6290
6291     window_sizes = NULL;
6292   }
6293
6294   if (window_sizes == NULL)
6295   {
6296     boolean current_window_size_found = FALSE;
6297     int i;
6298
6299     for (i = 0; window_sizes_list[i].value != -1; i++)
6300     {
6301       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6302       char identifier[32], name[32];
6303       int value = window_sizes_list[i].value;
6304       char *text = window_sizes_list[i].text;
6305
6306       ti->node_top = &window_sizes;
6307       ti->sort_priority = value;
6308
6309       sprintf(identifier, "%d", value);
6310       sprintf(name, "%s", text);
6311
6312       setString(&ti->identifier, identifier);
6313       setString(&ti->name, name);
6314       setString(&ti->name_sorting, name);
6315       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6316
6317       pushTreeInfo(&window_sizes, ti);
6318
6319       if (value == setup.window_scaling_percent)
6320         current_window_size_found = TRUE;
6321     }
6322
6323     if (!current_window_size_found)
6324     {
6325       // add entry for non-preset window scaling value
6326
6327       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6328       char identifier[32], name[32];
6329       int value = setup.window_scaling_percent;
6330
6331       ti->node_top = &window_sizes;
6332       ti->sort_priority = value;
6333
6334       sprintf(identifier, "%d", value);
6335       sprintf(name, "%d %% (Current)", value);
6336
6337       setString(&ti->identifier, identifier);
6338       setString(&ti->name, name);
6339       setString(&ti->name_sorting, name);
6340       setString(&ti->infotext, STR_SETUP_CHOOSE_WINDOW_SIZE);
6341
6342       pushTreeInfo(&window_sizes, ti);
6343     }
6344
6345     // sort window size values to start with lowest window size value
6346     sortTreeInfo(&window_sizes);
6347
6348     // set current window size value to configured window size value
6349     window_size_current =
6350       getTreeInfoFromIdentifier(window_sizes,
6351                                 i_to_a(setup.window_scaling_percent));
6352
6353     // if that fails, set current window size to reliable default value
6354     if (window_size_current == NULL)
6355       window_size_current =
6356         getTreeInfoFromIdentifier(window_sizes,
6357                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
6358
6359     // if that also fails, set current window size to first available value
6360     if (window_size_current == NULL)
6361       window_size_current = window_sizes;
6362   }
6363
6364   setup.window_scaling_percent = atoi(window_size_current->identifier);
6365
6366   // needed for displaying window size text instead of identifier
6367   window_size_text = window_size_current->name;
6368 }
6369
6370 static void execSetupGraphics_setScalingTypes(void)
6371 {
6372   if (scaling_types == NULL)
6373   {
6374     int i;
6375
6376     for (i = 0; scaling_types_list[i].value != NULL; i++)
6377     {
6378       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6379       char identifier[32], name[32];
6380       char *value = scaling_types_list[i].value;
6381       char *text = scaling_types_list[i].text;
6382
6383       ti->node_top = &scaling_types;
6384       ti->sort_priority = i;
6385
6386       sprintf(identifier, "%s", value);
6387       sprintf(name, "%s", text);
6388
6389       setString(&ti->identifier, identifier);
6390       setString(&ti->name, name);
6391       setString(&ti->name_sorting, name);
6392       setString(&ti->infotext, STR_SETUP_CHOOSE_SCALING_TYPE);
6393
6394       pushTreeInfo(&scaling_types, ti);
6395     }
6396
6397     // sort scaling type values to start with lowest scaling type value
6398     sortTreeInfo(&scaling_types);
6399
6400     // set current scaling type value to configured scaling type value
6401     scaling_type_current =
6402       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
6403
6404     // if that fails, set current scaling type to reliable default value
6405     if (scaling_type_current == NULL)
6406       scaling_type_current =
6407         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
6408
6409     // if that also fails, set current scaling type to first available value
6410     if (scaling_type_current == NULL)
6411       scaling_type_current = scaling_types;
6412   }
6413
6414   setup.window_scaling_quality = scaling_type_current->identifier;
6415
6416   // needed for displaying scaling type text instead of identifier
6417   scaling_type_text = scaling_type_current->name;
6418 }
6419
6420 static void execSetupGraphics_setRenderingModes(void)
6421 {
6422   if (rendering_modes == NULL)
6423   {
6424     int i;
6425
6426     for (i = 0; rendering_modes_list[i].value != NULL; i++)
6427     {
6428       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6429       char identifier[32], name[32];
6430       char *value = rendering_modes_list[i].value;
6431       char *text = rendering_modes_list[i].text;
6432
6433       ti->node_top = &rendering_modes;
6434       ti->sort_priority = i;
6435
6436       sprintf(identifier, "%s", value);
6437       sprintf(name, "%s", text);
6438
6439       setString(&ti->identifier, identifier);
6440       setString(&ti->name, name);
6441       setString(&ti->name_sorting, name);
6442       setString(&ti->infotext, STR_SETUP_CHOOSE_RENDERING);
6443
6444       pushTreeInfo(&rendering_modes, ti);
6445     }
6446
6447     // sort rendering mode values to start with lowest rendering mode value
6448     sortTreeInfo(&rendering_modes);
6449
6450     // set current rendering mode value to configured rendering mode value
6451     rendering_mode_current =
6452       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
6453
6454     // if that fails, set current rendering mode to reliable default value
6455     if (rendering_mode_current == NULL)
6456       rendering_mode_current =
6457         getTreeInfoFromIdentifier(rendering_modes,
6458                                   STR_SPECIAL_RENDERING_DEFAULT);
6459
6460     // if that also fails, set current rendering mode to first available one
6461     if (rendering_mode_current == NULL)
6462       rendering_mode_current = rendering_modes;
6463   }
6464
6465   setup.screen_rendering_mode = rendering_mode_current->identifier;
6466
6467   // needed for displaying rendering mode text instead of identifier
6468   rendering_mode_text = rendering_mode_current->name;
6469 }
6470
6471 static void execSetupGraphics_setVsyncModes(boolean update_value)
6472 {
6473   if (vsync_modes == NULL)
6474   {
6475     int i;
6476
6477     for (i = 0; vsync_modes_list[i].value != NULL; i++)
6478     {
6479       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6480       char identifier[32], name[32];
6481       char *value = vsync_modes_list[i].value;
6482       char *text = vsync_modes_list[i].text;
6483
6484       ti->node_top = &vsync_modes;
6485       ti->sort_priority = i;
6486
6487       sprintf(identifier, "%s", value);
6488       sprintf(name, "%s", text);
6489
6490       setString(&ti->identifier, identifier);
6491       setString(&ti->name, name);
6492       setString(&ti->name_sorting, name);
6493       setString(&ti->infotext, STR_SETUP_CHOOSE_VSYNC);
6494
6495       pushTreeInfo(&vsync_modes, ti);
6496     }
6497
6498     // sort vsync mode values to start with lowest vsync mode value
6499     sortTreeInfo(&vsync_modes);
6500
6501     update_value = TRUE;
6502   }
6503
6504   if (update_value)
6505   {
6506     // set current vsync mode value to configured vsync mode value
6507     vsync_mode_current =
6508       getTreeInfoFromIdentifier(vsync_modes, setup.vsync_mode);
6509
6510     // if that fails, set current vsync mode to reliable default value
6511     if (vsync_mode_current == NULL)
6512       vsync_mode_current =
6513         getTreeInfoFromIdentifier(vsync_modes, STR_VSYNC_MODE_DEFAULT);
6514
6515     // if that also fails, set current vsync mode to first available one
6516     if (vsync_mode_current == NULL)
6517       vsync_mode_current = vsync_modes;
6518   }
6519
6520   setup.vsync_mode = vsync_mode_current->identifier;
6521
6522   // needed for displaying vsync mode text instead of identifier
6523   vsync_mode_text = vsync_mode_current->name;
6524 }
6525
6526 static void execSetupGraphics(void)
6527 {
6528   boolean check_game_speed = (setup_mode == SETUP_MODE_CHOOSE_VSYNC);
6529
6530   // update "setup.window_scaling_percent" from list selection
6531   // (in this case, window scaling was changed on setup screen)
6532   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6533     execSetupGraphics_setWindowSizes(FALSE);
6534
6535   // update "setup.vsync_mode" from list selection
6536   // (in this case, vsync mode was changed on setup screen)
6537   if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
6538     execSetupGraphics_setVsyncModes(FALSE);
6539
6540   // update list selection from "setup.window_scaling_percent"
6541   // (window scaling may have changed by resizing the window)
6542   execSetupGraphics_setWindowSizes(TRUE);
6543
6544   // update list selection from "setup.vsync_mode"
6545   // (vsync_mode may have changed by re-creating the renderer)
6546   execSetupGraphics_setVsyncModes(TRUE);
6547
6548   execSetupGraphics_setScalingTypes();
6549   execSetupGraphics_setRenderingModes();
6550
6551   setup_mode = SETUP_MODE_GRAPHICS;
6552
6553   DrawSetupScreen();
6554
6555   // check if game speed is high enough for 60 Hz vsync to work
6556   if (check_game_speed)
6557     ModifyGameSpeedIfNeeded();
6558
6559   // window scaling may have changed at this point
6560   ChangeWindowScalingIfNeeded();
6561
6562   // window scaling quality may have changed at this point
6563   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
6564     SDLSetWindowScalingQuality(setup.window_scaling_quality);
6565
6566   // screen rendering mode may have changed at this point
6567   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
6568
6569   int setup_vsync_mode = VSYNC_MODE_STR_TO_INT(setup.vsync_mode);
6570   int video_vsync_mode = video.vsync_mode;
6571
6572   // screen vsync mode may have changed at this point
6573   ChangeVsyncModeIfNeeded();
6574
6575   // check if setting vsync mode to selected value failed
6576   if (setup_vsync_mode != video_vsync_mode &&
6577       setup_vsync_mode != video.vsync_mode)
6578   {
6579     // changing vsync mode to selected value failed -- reset displayed value
6580     execSetupGraphics_setVsyncModes(TRUE);
6581
6582     Request("Setting VSync failed!", REQ_CONFIRM);
6583
6584     DrawSetupScreen();
6585   }
6586 }
6587
6588 static void execSetupChooseWindowSize(void)
6589 {
6590   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
6591
6592   DrawSetupScreen();
6593 }
6594
6595 static void execSetupChooseScalingType(void)
6596 {
6597   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
6598
6599   DrawSetupScreen();
6600 }
6601
6602 static void execSetupChooseRenderingMode(void)
6603 {
6604   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
6605
6606   DrawSetupScreen();
6607 }
6608
6609 static void execSetupChooseVsyncMode(void)
6610 {
6611   setup_mode = SETUP_MODE_CHOOSE_VSYNC;
6612
6613   DrawSetupScreen();
6614 }
6615
6616 static void execSetupChooseVolumeSimple(void)
6617 {
6618   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
6619
6620   DrawSetupScreen();
6621 }
6622
6623 static void execSetupChooseVolumeLoops(void)
6624 {
6625   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
6626
6627   DrawSetupScreen();
6628 }
6629
6630 static void execSetupChooseVolumeMusic(void)
6631 {
6632   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
6633
6634   DrawSetupScreen();
6635 }
6636
6637 static void execSetupSound(void)
6638 {
6639   if (volumes_simple == NULL)
6640   {
6641     boolean current_volume_simple_found = FALSE;
6642     int i;
6643
6644     for (i = 0; volumes_list[i].value != -1; i++)
6645     {
6646       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6647       char identifier[32], name[32];
6648       int value = volumes_list[i].value;
6649       char *text = volumes_list[i].text;
6650
6651       ti->node_top = &volumes_simple;
6652       ti->sort_priority = value;
6653
6654       sprintf(identifier, "%d", value);
6655       sprintf(name, "%s", text);
6656
6657       setString(&ti->identifier, identifier);
6658       setString(&ti->name, name);
6659       setString(&ti->name_sorting, name);
6660       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6661
6662       pushTreeInfo(&volumes_simple, ti);
6663
6664       if (value == setup.volume_simple)
6665         current_volume_simple_found = TRUE;
6666     }
6667
6668     if (!current_volume_simple_found)
6669     {
6670       // add entry for non-preset volume value
6671
6672       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6673       char identifier[32], name[32];
6674       int value = setup.volume_simple;
6675
6676       ti->node_top = &volumes_simple;
6677       ti->sort_priority = value;
6678
6679       sprintf(identifier, "%d", value);
6680       sprintf(name, "%d %% (Current)", value);
6681
6682       setString(&ti->identifier, identifier);
6683       setString(&ti->name, name);
6684       setString(&ti->name_sorting, name);
6685       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_SIMPLE);
6686
6687       pushTreeInfo(&volumes_simple, ti);
6688     }
6689
6690     // sort volume values to start with lowest volume value
6691     sortTreeInfo(&volumes_simple);
6692
6693     // set current volume value to configured volume value
6694     volume_simple_current =
6695       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
6696
6697     // if that fails, set current volume to reliable default value
6698     if (volume_simple_current == NULL)
6699       volume_simple_current =
6700         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
6701
6702     // if that also fails, set current volume to first available value
6703     if (volume_simple_current == NULL)
6704       volume_simple_current = volumes_simple;
6705   }
6706
6707   if (volumes_loops == NULL)
6708   {
6709     boolean current_volume_loops_found = FALSE;
6710     int i;
6711
6712     for (i = 0; volumes_list[i].value != -1; i++)
6713     {
6714       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6715       char identifier[32], name[32];
6716       int value = volumes_list[i].value;
6717       char *text = volumes_list[i].text;
6718
6719       ti->node_top = &volumes_loops;
6720       ti->sort_priority = value;
6721
6722       sprintf(identifier, "%d", value);
6723       sprintf(name, "%s", text);
6724
6725       setString(&ti->identifier, identifier);
6726       setString(&ti->name, name);
6727       setString(&ti->name_sorting, name);
6728       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6729
6730       pushTreeInfo(&volumes_loops, ti);
6731
6732       if (value == setup.volume_loops)
6733         current_volume_loops_found = TRUE;
6734     }
6735
6736     if (!current_volume_loops_found)
6737     {
6738       // add entry for non-preset volume value
6739
6740       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6741       char identifier[32], name[32];
6742       int value = setup.volume_loops;
6743
6744       ti->node_top = &volumes_loops;
6745       ti->sort_priority = value;
6746
6747       sprintf(identifier, "%d", value);
6748       sprintf(name, "%d %% (Current)", value);
6749
6750       setString(&ti->identifier, identifier);
6751       setString(&ti->name, name);
6752       setString(&ti->name_sorting, name);
6753       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_LOOPS);
6754
6755       pushTreeInfo(&volumes_loops, ti);
6756     }
6757
6758     // sort volume values to start with lowest volume value
6759     sortTreeInfo(&volumes_loops);
6760
6761     // set current volume value to configured volume value
6762     volume_loops_current =
6763       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
6764
6765     // if that fails, set current volume to reliable default value
6766     if (volume_loops_current == NULL)
6767       volume_loops_current =
6768         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
6769
6770     // if that also fails, set current volume to first available value
6771     if (volume_loops_current == NULL)
6772       volume_loops_current = volumes_loops;
6773   }
6774
6775   if (volumes_music == NULL)
6776   {
6777     boolean current_volume_music_found = FALSE;
6778     int i;
6779
6780     for (i = 0; volumes_list[i].value != -1; i++)
6781     {
6782       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6783       char identifier[32], name[32];
6784       int value = volumes_list[i].value;
6785       char *text = volumes_list[i].text;
6786
6787       ti->node_top = &volumes_music;
6788       ti->sort_priority = value;
6789
6790       sprintf(identifier, "%d", value);
6791       sprintf(name, "%s", text);
6792
6793       setString(&ti->identifier, identifier);
6794       setString(&ti->name, name);
6795       setString(&ti->name_sorting, name);
6796       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6797
6798       pushTreeInfo(&volumes_music, ti);
6799
6800       if (value == setup.volume_music)
6801         current_volume_music_found = TRUE;
6802     }
6803
6804     if (!current_volume_music_found)
6805     {
6806       // add entry for non-preset volume value
6807
6808       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6809       char identifier[32], name[32];
6810       int value = setup.volume_music;
6811
6812       ti->node_top = &volumes_music;
6813       ti->sort_priority = value;
6814
6815       sprintf(identifier, "%d", value);
6816       sprintf(name, "%d %% (Current)", value);
6817
6818       setString(&ti->identifier, identifier);
6819       setString(&ti->name, name);
6820       setString(&ti->name_sorting, name);
6821       setString(&ti->infotext, STR_SETUP_CHOOSE_VOLUME_MUSIC);
6822
6823       pushTreeInfo(&volumes_music, ti);
6824     }
6825
6826     // sort volume values to start with lowest volume value
6827     sortTreeInfo(&volumes_music);
6828
6829     // set current volume value to configured volume value
6830     volume_music_current =
6831       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
6832
6833     // if that fails, set current volume to reliable default value
6834     if (volume_music_current == NULL)
6835       volume_music_current =
6836         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
6837
6838     // if that also fails, set current volume to first available value
6839     if (volume_music_current == NULL)
6840       volume_music_current = volumes_music;
6841   }
6842
6843   setup.volume_simple = atoi(volume_simple_current->identifier);
6844   setup.volume_loops  = atoi(volume_loops_current->identifier);
6845   setup.volume_music  = atoi(volume_music_current->identifier);
6846
6847   // needed for displaying volume text instead of identifier
6848   volume_simple_text = volume_simple_current->name;
6849   volume_loops_text = volume_loops_current->name;
6850   volume_music_text = volume_music_current->name;
6851
6852   setup_mode = SETUP_MODE_SOUND;
6853
6854   DrawSetupScreen();
6855 }
6856
6857 static void execSetupChooseTouchControls(void)
6858 {
6859   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
6860
6861   DrawSetupScreen();
6862 }
6863
6864 static void execSetupChooseMoveDistance(void)
6865 {
6866   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
6867
6868   DrawSetupScreen();
6869 }
6870
6871 static void execSetupChooseDropDistance(void)
6872 {
6873   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
6874
6875   DrawSetupScreen();
6876 }
6877
6878 static void execSetupChooseTransparency(void)
6879 {
6880   setup_mode = SETUP_MODE_CHOOSE_TRANSPARENCY;
6881
6882   DrawSetupScreen();
6883 }
6884
6885 static void execSetupChooseGridXSize_0(void)
6886 {
6887   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_0;
6888
6889   DrawSetupScreen();
6890 }
6891
6892 static void execSetupChooseGridYSize_0(void)
6893 {
6894   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_0;
6895
6896   DrawSetupScreen();
6897 }
6898
6899 static void execSetupChooseGridXSize_1(void)
6900 {
6901   setup_mode = SETUP_MODE_CHOOSE_GRID_XSIZE_1;
6902
6903   DrawSetupScreen();
6904 }
6905
6906 static void execSetupChooseGridYSize_1(void)
6907 {
6908   setup_mode = SETUP_MODE_CHOOSE_GRID_YSIZE_1;
6909
6910   DrawSetupScreen();
6911 }
6912
6913 static void execSetupConfigureVirtualButtons(void)
6914 {
6915   setup_mode = SETUP_MODE_CONFIG_VIRT_BUTTONS;
6916
6917   ConfigureVirtualButtons();
6918
6919   setup_mode = SETUP_MODE_TOUCH;
6920
6921   DrawSetupScreen();
6922 }
6923
6924 static void execSetupTouch(void)
6925 {
6926   int i, j, k;
6927
6928   if (touch_controls == NULL)
6929   {
6930     for (i = 0; touch_controls_list[i].value != NULL; i++)
6931     {
6932       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6933       char identifier[32], name[32];
6934       char *value = touch_controls_list[i].value;
6935       char *text = touch_controls_list[i].text;
6936
6937       ti->node_top = &touch_controls;
6938       ti->sort_priority = i;
6939
6940       sprintf(identifier, "%s", value);
6941       sprintf(name, "%s", text);
6942
6943       setString(&ti->identifier, identifier);
6944       setString(&ti->name, name);
6945       setString(&ti->name_sorting, name);
6946       setString(&ti->infotext, STR_SETUP_CHOOSE_TOUCH_CONTROL);
6947
6948       pushTreeInfo(&touch_controls, ti);
6949     }
6950
6951     // sort touch control values to start with lowest touch control value
6952     sortTreeInfo(&touch_controls);
6953
6954     // set current touch control value to configured touch control value
6955     touch_control_current =
6956       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
6957
6958     // if that fails, set current touch control to reliable default value
6959     if (touch_control_current == NULL)
6960       touch_control_current =
6961         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
6962
6963     // if that also fails, set current touch control to first available value
6964     if (touch_control_current == NULL)
6965       touch_control_current = touch_controls;
6966   }
6967
6968   if (move_distances == NULL)
6969   {
6970     for (i = 0; distances_list[i].value != -1; i++)
6971     {
6972       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
6973       char identifier[32], name[32];
6974       int value = distances_list[i].value;
6975       char *text = distances_list[i].text;
6976
6977       ti->node_top = &move_distances;
6978       ti->sort_priority = value;
6979
6980       sprintf(identifier, "%d", value);
6981       sprintf(name, "%s", text);
6982
6983       setString(&ti->identifier, identifier);
6984       setString(&ti->name, name);
6985       setString(&ti->name_sorting, name);
6986       setString(&ti->infotext, STR_SETUP_CHOOSE_MOVE_DISTANCE);
6987
6988       pushTreeInfo(&move_distances, ti);
6989     }
6990
6991     // sort distance values to start with lowest distance value
6992     sortTreeInfo(&move_distances);
6993
6994     // set current distance value to configured distance value
6995     move_distance_current =
6996       getTreeInfoFromIdentifier(move_distances,
6997                                 i_to_a(setup.touch.move_distance));
6998
6999     // if that fails, set current distance to reliable default value
7000     if (move_distance_current == NULL)
7001       move_distance_current =
7002         getTreeInfoFromIdentifier(move_distances,
7003                                   i_to_a(TOUCH_MOVE_DISTANCE_DEFAULT));
7004
7005     // if that also fails, set current distance to first available value
7006     if (move_distance_current == NULL)
7007       move_distance_current = move_distances;
7008   }
7009
7010   if (drop_distances == NULL)
7011   {
7012     for (i = 0; distances_list[i].value != -1; i++)
7013     {
7014       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7015       char identifier[32], name[32];
7016       int value = distances_list[i].value;
7017       char *text = distances_list[i].text;
7018
7019       ti->node_top = &drop_distances;
7020       ti->sort_priority = value;
7021
7022       sprintf(identifier, "%d", value);
7023       sprintf(name, "%s", text);
7024
7025       setString(&ti->identifier, identifier);
7026       setString(&ti->name, name);
7027       setString(&ti->name_sorting, name);
7028       setString(&ti->infotext, STR_SETUP_CHOOSE_DROP_DISTANCE);
7029
7030       pushTreeInfo(&drop_distances, ti);
7031     }
7032
7033     // sort distance values to start with lowest distance value
7034     sortTreeInfo(&drop_distances);
7035
7036     // set current distance value to configured distance value
7037     drop_distance_current =
7038       getTreeInfoFromIdentifier(drop_distances,
7039                                 i_to_a(setup.touch.drop_distance));
7040
7041     // if that fails, set current distance to reliable default value
7042     if (drop_distance_current == NULL)
7043       drop_distance_current =
7044         getTreeInfoFromIdentifier(drop_distances,
7045                                   i_to_a(TOUCH_DROP_DISTANCE_DEFAULT));
7046
7047     // if that also fails, set current distance to first available value
7048     if (drop_distance_current == NULL)
7049       drop_distance_current = drop_distances;
7050   }
7051
7052   if (transparencies == NULL)
7053   {
7054     for (i = 0; transparencies_list[i].value != -1; i++)
7055     {
7056       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7057       char identifier[32], name[32];
7058       int value = transparencies_list[i].value;
7059       char *text = transparencies_list[i].text;
7060
7061       ti->node_top = &transparencies;
7062       ti->sort_priority = value;
7063
7064       sprintf(identifier, "%d", value);
7065       sprintf(name, "%s", text);
7066
7067       setString(&ti->identifier, identifier);
7068       setString(&ti->name, name);
7069       setString(&ti->name_sorting, name);
7070       setString(&ti->infotext, STR_SETUP_CHOOSE_TRANSPARENCY);
7071
7072       pushTreeInfo(&transparencies, ti);
7073     }
7074
7075     // sort transparency values to start with lowest transparency value
7076     sortTreeInfo(&transparencies);
7077
7078     // set current transparency value to configured transparency value
7079     transparency_current =
7080       getTreeInfoFromIdentifier(transparencies,
7081                                 i_to_a(setup.touch.transparency));
7082
7083     // if that fails, set current transparency to reliable default value
7084     if (transparency_current == NULL)
7085       transparency_current =
7086         getTreeInfoFromIdentifier(transparencies,
7087                                   i_to_a(TOUCH_TRANSPARENCY_DEFAULT));
7088
7089     // if that also fails, set current transparency to first available value
7090     if (transparency_current == NULL)
7091       transparency_current = transparencies;
7092   }
7093
7094   for (i = 0; i < 2; i++)
7095   {
7096     for (j = 0; j < 2; j++)
7097     {
7098       if (grid_sizes[i][j] == NULL)
7099       {
7100         for (k = 0; grid_sizes_list[k].value != -1; k++)
7101         {
7102           TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
7103           char identifier[32], name[32];
7104           int value = grid_sizes_list[k].value;
7105           char *text = grid_sizes_list[k].text;
7106
7107           ti->node_top = &grid_sizes[i][j];
7108           ti->sort_priority = value;
7109
7110           sprintf(identifier, "%d", value);
7111           sprintf(name, "%s", text);
7112
7113           setString(&ti->identifier, identifier);
7114           setString(&ti->name, name);
7115           setString(&ti->name_sorting, name);
7116           setString(&ti->infotext,
7117                     (i == 0 ?
7118                      (j == 0 ?
7119                       STR_SETUP_CHOOSE_GRID_XSIZE_0 :
7120                       STR_SETUP_CHOOSE_GRID_YSIZE_0) :
7121                      (j == 0 ?
7122                       STR_SETUP_CHOOSE_GRID_XSIZE_1 :
7123                       STR_SETUP_CHOOSE_GRID_YSIZE_1)));
7124
7125           pushTreeInfo(&grid_sizes[i][j], ti);
7126         }
7127
7128         // sort grid size values to start with lowest grid size value
7129         sortTreeInfo(&grid_sizes[i][j]);
7130
7131         // set current grid size value to configured grid size value
7132         grid_size_current[i][j] =
7133           getTreeInfoFromIdentifier(grid_sizes[i][j],
7134                                     i_to_a(j == 0 ?
7135                                            setup.touch.grid_xsize[i] :
7136                                            setup.touch.grid_ysize[i]));
7137
7138         // if that fails, set current grid size to reliable default value
7139         if (grid_size_current[i][j] == NULL)
7140           grid_size_current[i][j] =
7141             getTreeInfoFromIdentifier(grid_sizes[i][j],
7142                                       i_to_a(j == 0 ?
7143                                              DEFAULT_GRID_XSIZE(i) :
7144                                              DEFAULT_GRID_YSIZE(i)));
7145
7146         // if that also fails, set current grid size to first available value
7147         if (grid_size_current[i][j] == NULL)
7148           grid_size_current[i][j] = grid_sizes[i][j];
7149       }
7150     }
7151   }
7152
7153   setup.touch.control_type = touch_control_current->identifier;
7154   setup.touch.move_distance = atoi(move_distance_current->identifier);
7155   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
7156   setup.touch.transparency = atoi(transparency_current->identifier);
7157
7158   for (i = 0; i < 2; i++)
7159   {
7160     setup.touch.grid_xsize[i] = atoi(grid_size_current[i][0]->identifier);
7161     setup.touch.grid_ysize[i] = atoi(grid_size_current[i][1]->identifier);
7162
7163     if (i == GRID_ACTIVE_NR())
7164     {
7165       overlay.grid_xsize = setup.touch.grid_xsize[i];
7166       overlay.grid_ysize = setup.touch.grid_ysize[i];
7167     }
7168   }
7169
7170   // needed for displaying value text instead of identifier
7171   touch_controls_text = touch_control_current->name;
7172   move_distance_text = move_distance_current->name;
7173   drop_distance_text = drop_distance_current->name;
7174   transparency_text = transparency_current->name;
7175
7176   for (i = 0; i < 2; i++)
7177     for (j = 0; j < 2; j++)
7178       grid_size_text[i][j] = grid_size_current[i][j]->name;
7179
7180   setup_mode = SETUP_MODE_TOUCH;
7181
7182   DrawSetupScreen();
7183 }
7184
7185 static void execSetupArtwork(void)
7186 {
7187   static ArtworkDirTree *gfx_last_valid = NULL;
7188   static ArtworkDirTree *snd_last_valid = NULL;
7189   static ArtworkDirTree *mus_last_valid = NULL;
7190
7191   // current artwork directory may be invalid (level group, parent link)
7192   if (!validLevelSeries(artwork.gfx_current))
7193     artwork.gfx_current = getFirstValidTreeInfoEntry(gfx_last_valid);
7194   if (!validLevelSeries(artwork.snd_current))
7195     artwork.snd_current = getFirstValidTreeInfoEntry(snd_last_valid);
7196   if (!validLevelSeries(artwork.mus_current))
7197     artwork.mus_current = getFirstValidTreeInfoEntry(mus_last_valid);
7198
7199   // store valid artwork directory information
7200   gfx_last_valid = artwork.gfx_current;
7201   snd_last_valid = artwork.snd_current;
7202   mus_last_valid = artwork.mus_current;
7203
7204 #if 0
7205   Debug("screens:execSetupArtwork", "'%s', '%s', '%s'",
7206         artwork.gfx_current->subdir,
7207         artwork.gfx_current->fullpath,
7208         artwork.gfx_current->basepath);
7209 #endif
7210
7211   setup.graphics_set = artwork.gfx_current->identifier;
7212   setup.sounds_set = artwork.snd_current->identifier;
7213   setup.music_set = artwork.mus_current->identifier;
7214
7215   // needed if last screen (setup choice) changed graphics, sounds or music
7216   ReloadCustomArtwork(0);
7217
7218   // needed for displaying artwork name instead of artwork identifier
7219   graphics_set_name = artwork.gfx_current->name;
7220   sounds_set_name = artwork.snd_current->name;
7221   music_set_name = artwork.mus_current->name;
7222
7223   setup_mode = SETUP_MODE_ARTWORK;
7224
7225   DrawSetupScreen();
7226 }
7227
7228 static void execSetupChooseGraphics(void)
7229 {
7230   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
7231
7232   DrawSetupScreen();
7233 }
7234
7235 static void execSetupChooseSounds(void)
7236 {
7237   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
7238
7239   DrawSetupScreen();
7240 }
7241
7242 static void execSetupChooseMusic(void)
7243 {
7244   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
7245
7246   DrawSetupScreen();
7247 }
7248
7249 static void execSetupInput(void)
7250 {
7251   setup_mode = SETUP_MODE_INPUT;
7252
7253   DrawSetupScreen();
7254 }
7255
7256 static void execSetupShortcuts(void)
7257 {
7258   setup_mode = SETUP_MODE_SHORTCUTS;
7259
7260   DrawSetupScreen();
7261 }
7262
7263 static void execSetupShortcuts1(void)
7264 {
7265   setup_mode = SETUP_MODE_SHORTCUTS_1;
7266
7267   DrawSetupScreen();
7268 }
7269
7270 static void execSetupShortcuts2(void)
7271 {
7272   setup_mode = SETUP_MODE_SHORTCUTS_2;
7273
7274   DrawSetupScreen();
7275 }
7276
7277 static void execSetupShortcuts3(void)
7278 {
7279   setup_mode = SETUP_MODE_SHORTCUTS_3;
7280
7281   DrawSetupScreen();
7282 }
7283
7284 static void execSetupShortcuts4(void)
7285 {
7286   setup_mode = SETUP_MODE_SHORTCUTS_4;
7287
7288   DrawSetupScreen();
7289 }
7290
7291 static void execSetupShortcuts5(void)
7292 {
7293   setup_mode = SETUP_MODE_SHORTCUTS_5;
7294
7295   DrawSetupScreen();
7296 }
7297
7298 static void execExitSetup(void)
7299 {
7300   SetGameStatus(GAME_MODE_MAIN);
7301
7302   DrawMainMenu();
7303 }
7304
7305 static void execSaveAndExitSetup(void)
7306 {
7307   SaveSetup();
7308   execExitSetup();
7309 }
7310
7311 static void execGadgetNetworkServer(void)
7312 {
7313   int gadget_id = SCREEN_CTRL_ID_NETWORK_SERVER;
7314   struct GadgetInfo *gi = screen_gadget[gadget_id];
7315
7316   if (strEqual(setup.network_server_hostname, STR_NETWORK_AUTO_DETECT))
7317     network_server_hostname[0] = '\0';
7318
7319   ModifyGadget(gi, GDI_TEXT_VALUE, network_server_hostname, GDI_END);
7320
7321   MapGadget(gi);
7322
7323   ClickOnGadget(gi, MB_LEFTBUTTON);
7324 }
7325
7326 static void execOfferUploadTapes(void)
7327 {
7328   OfferUploadTapes();
7329 }
7330
7331 static void ToggleNetworkModeIfNeeded(void)
7332 {
7333   int font_title = FONT_TITLE_1;
7334   int font_foot = FC_BLUE;
7335   int ystart  = mSY - SY + 16;
7336   int ybottom = mSY - SY + SYSIZE - 20;
7337   char *text = (setup.network_mode ? "Start Network" : "Stop Network");
7338
7339   if (setup.network_mode == network.enabled)
7340     return;
7341
7342   network.enabled = setup.network_mode;
7343
7344   FadeOut(REDRAW_ALL);
7345
7346   ClearField();
7347
7348   DrawTextSCentered(ystart, font_title, text);
7349
7350   FadeIn(REDRAW_ALL);
7351
7352   if (network.enabled)
7353     InitNetworkServer();
7354   else
7355     DisconnectFromNetworkServer();
7356
7357   DrawTextSCentered(ybottom, font_foot,
7358                     "Press any key or button for setup menu");
7359
7360   WaitForEventToContinue();
7361
7362   DrawSetupScreen();
7363 }
7364
7365 static void ToggleGameSpeedsListIfNeeded(void)
7366 {
7367   boolean using_game_speeds_extended = (game_speeds == game_speeds_extended);
7368
7369   if (setup.game_speed_extended == using_game_speeds_extended)
7370     return;
7371
7372   // try to match similar values when changing game speeds list
7373   if (setup.game_speed_extended)
7374     setup.game_frame_delay = (setup.game_frame_delay == 15 ? 16 :
7375                               setup.game_frame_delay == 30 ? 29 :
7376                               setup.game_frame_delay);
7377   else
7378     setup.game_frame_delay = (setup.game_frame_delay == 14 ? 15 :
7379                               setup.game_frame_delay == 16 ? 15 :
7380                               setup.game_frame_delay >= 29 ? 30 :
7381                               setup.game_frame_delay <= 10 ? 10 :
7382                               setup.game_frame_delay);
7383
7384   execSetupGame_setGameSpeeds(TRUE);
7385
7386   DrawSetupScreen();
7387 }
7388
7389 static void ToggleUseApiServerIfNeeded(void)
7390 {
7391   if (runtime.use_api_server == setup.use_api_server)
7392     return;
7393
7394   runtime.use_api_server = setup.use_api_server;
7395
7396   if (runtime.use_api_server)
7397     CheckApiServerTasks();
7398 }
7399
7400 static void ModifyGameSpeedIfNeeded(void)
7401 {
7402   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7403       setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY)
7404     return;
7405
7406   char message[100];
7407   char *game_speed_text = "Fast";
7408   int game_speed_value = 15;
7409
7410   if (setup.game_speed_extended)
7411   {
7412     game_speed_text = "60 fps";
7413     game_speed_value = 16;
7414   }
7415
7416   sprintf(message, "Game speed set to %s for VSync to work!", game_speed_text);
7417
7418   // set game speed to existing list value that is fast enough for vsync
7419   setup.game_frame_delay = game_speed_value;
7420
7421   execSetupGame_setGameSpeeds(TRUE);
7422
7423   Request(message, REQ_CONFIRM);
7424 }
7425
7426 static void DisableVsyncIfNeeded(void)
7427 {
7428   if (strEqual(setup.vsync_mode, STR_VSYNC_MODE_OFF) ||
7429       (setup.game_frame_delay >= MIN_VSYNC_FRAME_DELAY &&
7430        setup.game_frame_delay <= MAX_VSYNC_FRAME_DELAY))
7431     return;
7432
7433   // disable vsync for the selected game speed to work
7434   setup.vsync_mode = STR_VSYNC_MODE_OFF;
7435
7436   execSetupGraphics_setVsyncModes(TRUE);
7437
7438   Request("VSync disabled for this game speed to work!", REQ_CONFIRM);
7439 }
7440
7441 static struct
7442 {
7443   void *value;
7444   void *related_value;
7445 } hide_related_entry_list[] =
7446 {
7447   { &setup.scores_in_highscore_list,    execSetupChooseScoresType       },
7448   { &setup.scores_in_highscore_list,    &scores_type_text               },
7449
7450   { &setup.game_frame_delay,            execSetupChooseGameSpeed        },
7451   { &setup.game_frame_delay,            &game_speed_text                },
7452
7453   { &setup.scroll_delay_value,          execSetupChooseScrollDelay      },
7454   { &setup.scroll_delay_value,          &scroll_delay_text              },
7455
7456   { &setup.engine_snapshot_mode,        execSetupChooseSnapshotMode     },
7457   { &setup.engine_snapshot_mode,        &snapshot_mode_text             },
7458
7459   { &setup.window_scaling_percent,      execSetupChooseWindowSize       },
7460   { &setup.window_scaling_percent,      &window_size_text               },
7461
7462   { &setup.window_scaling_quality,      execSetupChooseScalingType      },
7463   { &setup.window_scaling_quality,      &scaling_type_text              },
7464
7465   { &setup.screen_rendering_mode,       execSetupChooseRenderingMode    },
7466   { &setup.screen_rendering_mode,       &rendering_mode_text            },
7467
7468   { &setup.vsync_mode,                  execSetupChooseVsyncMode        },
7469   { &setup.vsync_mode,                  &vsync_mode_text                },
7470
7471   { &setup.graphics_set,                execSetupChooseGraphics         },
7472   { &setup.graphics_set,                &graphics_set_name              },
7473
7474   { &setup.sounds_set,                  execSetupChooseSounds           },
7475   { &setup.sounds_set,                  &sounds_set_name                },
7476
7477   { &setup.music_set,                   execSetupChooseMusic            },
7478   { &setup.music_set,                   &music_set_name                 },
7479
7480   { &setup.volume_simple,               execSetupChooseVolumeSimple     },
7481   { &setup.volume_simple,               &volume_simple_text             },
7482
7483   { &setup.volume_loops,                execSetupChooseVolumeLoops      },
7484   { &setup.volume_loops,                &volume_loops_text              },
7485
7486   { &setup.volume_music,                execSetupChooseVolumeMusic      },
7487   { &setup.volume_music,                &volume_music_text              },
7488
7489   { &setup.touch.control_type,          execSetupChooseTouchControls    },
7490   { &setup.touch.control_type,          &touch_controls_text            },
7491
7492   { &setup.touch.move_distance,         execSetupChooseMoveDistance     },
7493   { &setup.touch.move_distance,         &move_distance_text             },
7494
7495   { &setup.touch.drop_distance,         execSetupChooseDropDistance     },
7496   { &setup.touch.drop_distance,         &drop_distance_text             },
7497
7498   { &setup.touch.transparency,          execSetupChooseTransparency     },
7499   { &setup.touch.transparency,          &transparency_text              },
7500
7501   { &setup.touch.grid_xsize[0],         execSetupChooseGridXSize_0      },
7502   { &setup.touch.grid_xsize[0],         &grid_size_text[0][0]           },
7503
7504   { &setup.touch.grid_ysize[0],         execSetupChooseGridYSize_0      },
7505   { &setup.touch.grid_ysize[0],         &grid_size_text[0][1]           },
7506
7507   { &setup.touch.grid_xsize[1],         execSetupChooseGridXSize_1      },
7508   { &setup.touch.grid_xsize[1],         &grid_size_text[1][0]           },
7509
7510   { &setup.touch.grid_ysize[1],         execSetupChooseGridYSize_1      },
7511   { &setup.touch.grid_ysize[1],         &grid_size_text[1][1]           },
7512
7513   { &setup.internal.menu_game,          execSetupGame                   },
7514   { &setup.internal.menu_engines,       execSetupEngines                },
7515   { &setup.internal.menu_editor,        execSetupEditor                 },
7516   { &setup.internal.menu_graphics,      execSetupGraphics               },
7517   { &setup.internal.menu_sound,         execSetupSound                  },
7518   { &setup.internal.menu_artwork,       execSetupArtwork                },
7519   { &setup.internal.menu_input,         execSetupInput                  },
7520   { &setup.internal.menu_touch,         execSetupTouch                  },
7521   { &setup.internal.menu_shortcuts,     execSetupShortcuts              },
7522   { &setup.internal.menu_exit,          execExitSetup                   },
7523   { &setup.internal.menu_save_and_exit, execSaveAndExitSetup            },
7524
7525   { NULL,                               NULL                            }
7526 };
7527
7528 void setHideRelatedSetupEntries(void)
7529 {
7530   int i;
7531
7532   for (i = 0; hide_related_entry_list[i].value != NULL; i++)
7533     if (hideSetupEntry(hide_related_entry_list[i].value))
7534       setHideSetupEntry(hide_related_entry_list[i].related_value);
7535 }
7536
7537 static struct TokenInfo setup_info_main[] =
7538 {
7539   { TYPE_ENTER_MENU,    execSetupGame,          STR_SETUP_GAME          },
7540   { TYPE_ENTER_MENU,    execSetupEngines,       STR_SETUP_ENGINES       },
7541   { TYPE_ENTER_MENU,    execSetupEditor,        STR_SETUP_EDITOR        },
7542   { TYPE_ENTER_MENU,    execSetupGraphics,      STR_SETUP_GRAPHICS      },
7543   { TYPE_ENTER_MENU,    execSetupSound,         STR_SETUP_SOUND         },
7544   { TYPE_ENTER_MENU,    execSetupArtwork,       STR_SETUP_ARTWORK       },
7545   { TYPE_ENTER_MENU,    execSetupInput,         STR_SETUP_INPUT         },
7546   { TYPE_ENTER_MENU,    execSetupTouch,         STR_SETUP_TOUCH         },
7547   { TYPE_ENTER_MENU,    execSetupShortcuts,     STR_SETUP_SHORTCUTS     },
7548   { TYPE_EMPTY,         NULL,                   ""                      },
7549   { TYPE_LEAVE_MENU,    execExitSetup,          STR_SETUP_EXIT          },
7550   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   STR_SETUP_SAVE_AND_EXIT },
7551
7552   { 0,                  NULL,                   NULL                    }
7553 };
7554
7555 static struct TokenInfo setup_info_game[] =
7556 {
7557   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
7558   { TYPE_SWITCH,        &setup.network_mode,    "Network Multi-Player Mode:" },
7559   { TYPE_PLAYER,        &setup.network_player_nr,"Preferred Network Player:" },
7560   { TYPE_TEXT_INPUT,    execGadgetNetworkServer, "Network Server Hostname:" },
7561   { TYPE_STRING,        &network_server_text,   ""                      },
7562   { TYPE_SWITCH,        &setup.use_api_server,  "Use Highscore Server:" },
7563   { TYPE_ENTER_LIST,    execSetupChooseScoresType,"Scores in Highscore List:" },
7564   { TYPE_STRING,        &scores_type_text,      ""                      },
7565   { TYPE_ENTER_LIST,    execOfferUploadTapes,   "Upload Tapes to Server" },
7566   { TYPE_SWITCH,        &setup.multiple_users,  "Multiple Users/Teams:" },
7567   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
7568   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
7569   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
7570   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
7571   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
7572   { TYPE_SWITCH,        &setup.auto_play_next_level,"Auto-play Next Level:" },
7573   { TYPE_SWITCH,        &setup.count_score_after_game,"Count Score After Game:" },
7574   { TYPE_SWITCH,        &setup.show_scores_after_game,"Show Scores After Game:" },
7575   { TYPE_YES_NO,        &setup.ask_on_game_over, "Ask on Game Over:"    },
7576   { TYPE_YES_NO,        &setup.ask_on_quit_game, "Ask on Quit Game:"    },
7577   { TYPE_YES_NO,        &setup.ask_on_quit_program, "Ask on Quit Program:" },
7578   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
7579   { TYPE_SWITCH,        &setup.auto_pause_on_start, "Start Game in Pause Mode:" },
7580   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
7581   { TYPE_STRING,        &game_speed_text,       ""                      },
7582   { TYPE_SWITCH,        &setup.game_speed_extended, "Game Speed Extended List:" },
7583 #if 1
7584   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7585   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7586 #endif
7587   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
7588   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
7589   { TYPE_SWITCH,        &setup.show_load_save_buttons,"Show Load/Save Buttons:" },
7590   { TYPE_SWITCH,        &setup.show_undo_redo_buttons,"Show Undo/Redo Buttons:" },
7591   { TYPE_EMPTY,         NULL,                   ""                      },
7592   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7593
7594   { 0,                  NULL,                   NULL                    }
7595 };
7596
7597 static struct TokenInfo setup_info_engines[] =
7598 {
7599   { TYPE_HEADLINE,      NULL,                   "Emerald Mine"          },
7600   { TYPE_SWITCH,        &setup.forced_scroll_delay, "Scroll Delay:"     },
7601   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics, "Amiga Graphics Chipset:" },
7602   { TYPE_SWITCH,        &setup.prefer_lowpass_sounds,"Low-Pass Filter Sounds:" },
7603   { TYPE_SWITCH,        &setup.prefer_extra_panel_items,"Show Dynamite and Keys:" },
7604   { TYPE_EMPTY,         NULL,                   ""                      },
7605   { TYPE_HEADLINE,      NULL,                   "Supaplex"              },
7606   { TYPE_SWITCH,        &setup.sp_show_border_elements, "Border Elements:" },
7607   { TYPE_EMPTY,         NULL,                   ""                      },
7608   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7609
7610   { 0,                  NULL,                   NULL                    }
7611 };
7612
7613 static struct TokenInfo setup_info_editor[] =
7614 {
7615 #if 0
7616   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
7617   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
7618   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
7619   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
7620   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
7621   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
7622   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
7623   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
7624   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
7625   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
7626 #endif
7627   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
7628   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
7629 #if 0
7630   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
7631 #endif
7632   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
7633   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
7634   { TYPE_EMPTY,         NULL,                   ""                      },
7635 #if 0
7636   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
7637   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
7638   { TYPE_EMPTY,         NULL,                   ""                      },
7639 #endif
7640   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
7641   { TYPE_EMPTY,         NULL,                   ""                      },
7642   { TYPE_SWITCH, &setup.editor.show_read_only_warning,  "Show read-only warning:" },
7643   { TYPE_EMPTY,         NULL,                   ""                      },
7644   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7645
7646   { 0,                  NULL,                   NULL                    }
7647 };
7648
7649 static struct TokenInfo setup_info_graphics[] =
7650 {
7651 #if !defined(PLATFORM_ANDROID)
7652   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
7653   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
7654   { TYPE_STRING,        &window_size_text,      ""                      },
7655   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
7656   { TYPE_STRING,        &scaling_type_text,     ""                      },
7657   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
7658   { TYPE_STRING,        &rendering_mode_text,   ""                      },
7659 #endif
7660 #if 0
7661   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
7662   { TYPE_STRING,        &scroll_delay_text,     ""                      },
7663 #endif
7664   { TYPE_ENTER_LIST,    execSetupChooseVsyncMode, "Vertical Sync (VSync):" },
7665   { TYPE_STRING,        &vsync_mode_text,       ""                      },
7666   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
7667   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
7668   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
7669   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
7670   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
7671   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
7672   { TYPE_YES_NO_AUTO,   &setup.debug.xsn_mode,  debug_xsn_mode          },
7673   { TYPE_EMPTY,         NULL,                   ""                      },
7674   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7675
7676   { 0,                  NULL,                   NULL                    }
7677 };
7678
7679 static struct TokenInfo setup_info_sound[] =
7680 {
7681   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
7682   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
7683   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
7684   { TYPE_EMPTY,         NULL,                   ""                      },
7685   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
7686   { TYPE_STRING,        &volume_simple_text,    ""                      },
7687   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
7688   { TYPE_STRING,        &volume_loops_text,     ""                      },
7689   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
7690   { TYPE_STRING,        &volume_music_text,     ""                      },
7691   { TYPE_EMPTY,         NULL,                   ""                      },
7692   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7693
7694   { 0,                  NULL,                   NULL                    }
7695 };
7696
7697 static struct TokenInfo setup_info_artwork[] =
7698 {
7699   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
7700   { TYPE_STRING,        &graphics_set_name,     ""                      },
7701   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
7702   { TYPE_STRING,        &sounds_set_name,       ""                      },
7703   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
7704   { TYPE_STRING,        &music_set_name,        ""                      },
7705   { TYPE_EMPTY,         NULL,                   ""                      },
7706   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
7707   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
7708   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
7709   { TYPE_EMPTY,         NULL,                   ""                      },
7710   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7711
7712   { 0,                  NULL,                   NULL                    }
7713 };
7714
7715 static struct TokenInfo setup_info_input[] =
7716 {
7717   { TYPE_SWITCH,        NULL,                   "Player:"               },
7718   { TYPE_SWITCH,        NULL,                   "Device:"               },
7719   { TYPE_SWITCH,        NULL,                   ""                      },
7720   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7721   { TYPE_EMPTY,         NULL,                   ""                      },
7722   { TYPE_EMPTY,         NULL,                   ""                      },
7723   { TYPE_EMPTY,         NULL,                   ""                      },
7724   { TYPE_EMPTY,         NULL,                   ""                      },
7725   { TYPE_EMPTY,         NULL,                   ""                      },
7726   { TYPE_EMPTY,         NULL,                   ""                      },
7727   { TYPE_EMPTY,         NULL,                   ""                      },
7728   { TYPE_EMPTY,         NULL,                   ""                      },
7729   { TYPE_SKIPPABLE,     NULL,                   ""                      },
7730   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7731
7732   { 0,                  NULL,                   NULL                    }
7733 };
7734
7735 static struct TokenInfo setup_info_touch[] =
7736 {
7737   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7738   { TYPE_STRING,        &touch_controls_text,   ""                      },
7739   { TYPE_EMPTY,         NULL,                   ""                      },
7740   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7741
7742   { 0,                  NULL,                   NULL                    }
7743 };
7744
7745 static struct TokenInfo setup_info_touch_virtual_buttons_0[] =
7746 {
7747   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7748   { TYPE_STRING,        &touch_controls_text,   ""                      },
7749   { TYPE_EMPTY,         NULL,                   ""                      },
7750   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_0, "Horizontal Buttons (Landscape):"   },
7751   { TYPE_STRING,        &grid_size_text[0][0],  ""                      },
7752   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_0, "Vertical Buttons (Landscape):"     },
7753   { TYPE_STRING,        &grid_size_text[0][1],  ""                      },
7754   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7755   { TYPE_STRING,        &transparency_text,     ""                      },
7756   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7757   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7758   { TYPE_EMPTY,         NULL,                   ""                      },
7759   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7760   { TYPE_EMPTY,         NULL,                   ""                      },
7761   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7762
7763   { 0,                  NULL,                   NULL                    }
7764 };
7765
7766 static struct TokenInfo setup_info_touch_virtual_buttons_1[] =
7767 {
7768   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7769   { TYPE_STRING,        &touch_controls_text,   ""                      },
7770   { TYPE_EMPTY,         NULL,                   ""                      },
7771   { TYPE_ENTER_LIST,    execSetupChooseGridXSize_1, "Horizontal Buttons (Portrait):"    },
7772   { TYPE_STRING,        &grid_size_text[1][0],  ""                      },
7773   { TYPE_ENTER_LIST,    execSetupChooseGridYSize_1, "Vertical Buttons (Portrait):"      },
7774   { TYPE_STRING,        &grid_size_text[1][1],  ""                      },
7775   { TYPE_ENTER_LIST,    execSetupChooseTransparency, "Button Transparency:" },
7776   { TYPE_STRING,        &transparency_text,     ""                      },
7777   { TYPE_SWITCH,        &setup.touch.draw_outlined, "Draw Buttons Outlined:" },
7778   { TYPE_SWITCH,        &setup.touch.draw_pressed, "Highlight Pressed Buttons:" },
7779   { TYPE_EMPTY,         NULL,                   ""                      },
7780   { TYPE_ENTER_LIST,    execSetupConfigureVirtualButtons, "Configure Virtual Buttons" },
7781   { TYPE_EMPTY,         NULL,                   ""                      },
7782   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7783
7784   { 0,                  NULL,                   NULL                    }
7785 };
7786
7787 static struct TokenInfo *setup_info_touch_virtual_buttons[] =
7788 {
7789   setup_info_touch_virtual_buttons_0,
7790   setup_info_touch_virtual_buttons_1
7791 };
7792
7793 static struct TokenInfo setup_info_touch_wipe_gestures[] =
7794 {
7795   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
7796   { TYPE_STRING,        &touch_controls_text,   ""                      },
7797   { TYPE_EMPTY,         NULL,                   ""                      },
7798   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
7799   { TYPE_STRING,        &move_distance_text,    ""                      },
7800   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
7801   { TYPE_STRING,        &drop_distance_text,    ""                      },
7802   { TYPE_EMPTY,         NULL,                   ""                      },
7803   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7804
7805   { 0,                  NULL,                   NULL                    }
7806 };
7807
7808 static struct TokenInfo setup_info_shortcuts[] =
7809 {
7810   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
7811   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
7812   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
7813   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
7814   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
7815   { TYPE_EMPTY,         NULL,                   ""                      },
7816   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
7817
7818   { 0,                  NULL,                   NULL                    }
7819 };
7820
7821 static struct TokenInfo setup_info_shortcuts_1[] =
7822 {
7823   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
7824   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
7825   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
7826   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
7827   { TYPE_KEYTEXT,       NULL,           "Restart Game:",                },
7828   { TYPE_KEY,           &setup.shortcut.restart_game, ""                },
7829   { TYPE_KEYTEXT,       NULL,           "Replay & Pause Before End:",   },
7830   { TYPE_KEY,           &setup.shortcut.pause_before_end, ""            },
7831   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
7832   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
7833   { TYPE_EMPTY,         NULL,                   ""                      },
7834   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
7835   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
7836   { TYPE_EMPTY,         NULL,                   ""                      },
7837   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7838
7839   { 0,                  NULL,                   NULL                    }
7840 };
7841
7842 static struct TokenInfo setup_info_shortcuts_2[] =
7843 {
7844   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
7845   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
7846   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
7847   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
7848   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
7849   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
7850   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
7851   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
7852   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
7853   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
7854   { TYPE_EMPTY,         NULL,                   ""                      },
7855   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7856
7857   { 0,                  NULL,                   NULL                    }
7858 };
7859
7860 static struct TokenInfo setup_info_shortcuts_3[] =
7861 {
7862   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
7863   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
7864   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
7865   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
7866   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
7867   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
7868   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
7869   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
7870   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
7871   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
7872   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
7873   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
7874   { TYPE_EMPTY,         NULL,                   ""                      },
7875   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7876
7877   { 0,                  NULL,                   NULL                    }
7878 };
7879
7880 static struct TokenInfo setup_info_shortcuts_4[] =
7881 {
7882   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
7883   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
7884   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
7885   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
7886   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
7887   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
7888   { TYPE_EMPTY,         NULL,                   ""                      },
7889   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7890
7891   { 0,                  NULL,                   NULL                    }
7892 };
7893
7894 static struct TokenInfo setup_info_shortcuts_5[] =
7895 {
7896   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
7897   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
7898   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
7899   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
7900   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
7901   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
7902   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
7903   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
7904   { TYPE_EMPTY,         NULL,                   ""                      },
7905   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
7906
7907   { 0,                  NULL,                   NULL                    }
7908 };
7909
7910 static Key getSetupKey(void)
7911 {
7912   Key key = KSYM_UNDEFINED;
7913   boolean got_key_event = FALSE;
7914
7915   while (!got_key_event)
7916   {
7917     Event event;
7918
7919     if (NextValidEvent(&event))
7920     {
7921       switch (event.type)
7922       {
7923         case EVENT_KEYPRESS:
7924           {
7925             key = GetEventKey((KeyEvent *)&event, TRUE);
7926
7927             // press 'Escape' or 'Enter' to keep the existing key binding
7928             if (key == KSYM_Escape || key == KSYM_Return)
7929               key = KSYM_UNDEFINED;     // keep old value
7930
7931             got_key_event = TRUE;
7932           }
7933           break;
7934
7935         case EVENT_KEYRELEASE:
7936           key_joystick_mapping = 0;
7937           break;
7938
7939         default:
7940           HandleOtherEvents(&event);
7941           break;
7942       }
7943     }
7944
7945     BackToFront();
7946   }
7947
7948   return key;
7949 }
7950
7951 static int getSetupValueFont(int type, void *value)
7952 {
7953   if (type & TYPE_GHOSTED)
7954     return FONT_OPTION_OFF;
7955   else if (type & TYPE_KEY)
7956     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
7957   else if (type & TYPE_STRING)
7958     return FONT_VALUE_2;
7959   else if (type & TYPE_ECS_AGA)
7960     return FONT_VALUE_1;
7961   else if (type & TYPE_BOOLEAN_STYLE)
7962     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
7963   else if (type & TYPE_YES_NO_AUTO)
7964     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
7965             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
7966   else if (type & TYPE_PLAYER)
7967     return FONT_VALUE_1;
7968   else
7969     return FONT_VALUE_1;
7970 }
7971
7972 static int getSetupValueFontNarrow(int type, int font_nr)
7973 {
7974   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
7975           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
7976           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
7977           font_nr);
7978 }
7979
7980 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
7981 {
7982   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
7983   struct TokenInfo *si = &setup_info[si_pos];
7984   boolean font_draw_xoffset_modified = FALSE;
7985   boolean scrollbar_needed = (num_setup_info < max_setup_info);
7986   int font_draw_xoffset_old = -1;
7987   int xoffset = (scrollbar_needed ? -1 : 0);
7988   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
7989   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
7990   int xpos = menu_screen_value_xpos;
7991   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
7992   int startx = mSX + xpos * 32;
7993   int starty = mSY + ypos * 32;
7994   int type = si->type;
7995   void *value = si->value;
7996   char *value_string = getSetupValue(type, value);
7997   int font_nr_default = getSetupValueFont(type, value);
7998   int font_width_default = getFontWidth(font_nr_default);
7999   int font_nr = font_nr_default;
8000   int i;
8001
8002   if (value_string == NULL)
8003     return;
8004
8005   if (type & TYPE_KEY)
8006   {
8007     xpos = MENU_SCREEN_START_XPOS;
8008
8009     if (type & TYPE_QUERY)
8010       value_string = "<press key>";
8011   }
8012   else if (type & TYPE_STRING)
8013   {
8014     int max_value_len = (SXSIZE - 2 * TILEX) / font_width_default;
8015
8016     xpos = MENU_SCREEN_START_XPOS;
8017
8018     if (strlen(value_string) > max_value_len)
8019       value_string[max_value_len] = '\0';
8020   }
8021   else if (type & TYPE_YES_NO_AUTO)
8022   {
8023     xpos = menu_screen_value_xpos - 1;
8024   }
8025   else if (type & TYPE_PLAYER)
8026   {
8027     int displayed_player_nr = *(int *)value + 1;
8028
8029     value_string = getSetupValue(TYPE_INTEGER, (void *)&displayed_player_nr);
8030   }
8031
8032   startx = mSX + xpos * 32;
8033   starty = mSY + ypos * 32;
8034
8035   // special check if right-side setup values moved left due to scrollbar
8036   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
8037   {
8038     int max_menu_text_length = 26;      // maximum text length for classic menu
8039     int font_xoffset = getFontDrawOffsetX(font_nr);
8040     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8041     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8042     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8043     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
8044
8045     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
8046     {
8047       // when using narrow font, left-shifting text "auto" not needed
8048       if (type & TYPE_YES_NO_AUTO)
8049         xpos += 1;
8050
8051       xpos += 1;
8052       startx = mSX + xpos * 32;
8053
8054       font_nr = getSetupValueFontNarrow(type, font_nr);
8055     }
8056   }
8057
8058   // downward compatibility correction for Juergen Bonhagen's menu settings
8059   if (setup_mode != SETUP_MODE_INPUT)
8060   {
8061     int max_menu_text_length_big = (menu_screen_value_xpos -
8062                                     MENU_SCREEN_START_XPOS);
8063     int max_menu_text_length_medium = max_menu_text_length_big * 2;
8064     int check_font_nr = FONT_OPTION_ON; // known font that needs correction
8065     int font1_xoffset = getFontDrawOffsetX(font_nr);
8066     int font2_xoffset = getFontDrawOffsetX(check_font_nr);
8067     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
8068     int text_font_nr = getMenuTextFont(FONT_MENU_2);
8069     int text_font_xoffset = getFontDrawOffsetX(text_font_nr);
8070     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
8071     boolean correct_font_draw_xoffset = FALSE;
8072
8073     if (xpos == MENU_SCREEN_START_XPOS &&
8074         startx + font1_xoffset < text_startx + text_font_xoffset)
8075       correct_font_draw_xoffset = TRUE;
8076
8077     if (xpos == menu_screen_value_xpos &&
8078         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
8079       correct_font_draw_xoffset = TRUE;
8080
8081     // check if setup value would overlap with setup text when printed
8082     // (this can happen for extreme/wrong values for font draw offset)
8083     if (correct_font_draw_xoffset)
8084     {
8085       font_draw_xoffset_old = getFontDrawOffsetX(font_nr);
8086       font_draw_xoffset_modified = TRUE;
8087
8088       if (type & TYPE_KEY)
8089         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
8090       else if (!(type & TYPE_STRING))
8091         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
8092           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
8093     }
8094   }
8095
8096   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
8097     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
8098
8099   DrawText(startx, starty, value_string, font_nr);
8100
8101   if (type & TYPE_PLAYER)
8102   {
8103     struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
8104     int player_nr = *(int *)value;
8105     int xoff = font->draw_xoffset + getFontWidth(font_nr);
8106     int yoff = font->draw_yoffset + (getFontHeight(font_nr) - TILEY) / 2;
8107     int startx2 = startx + xoff;
8108     int starty2 = starty + yoff;
8109
8110     if (DrawingOnBackground(startx2, starty2))
8111       ClearRectangleOnBackground(drawto, startx2, starty2, TILEX, TILEY);
8112
8113     DrawFixedGraphicThruMaskExt(drawto, startx2, starty2,
8114                                 PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8115   }
8116
8117   if (font_draw_xoffset_modified)
8118     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
8119 }
8120
8121 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
8122 {
8123   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
8124   struct TokenInfo *si = &setup_info[si_pos];
8125
8126   if (si->type & TYPE_BOOLEAN_STYLE)
8127   {
8128     *(boolean *)si->value ^= TRUE;
8129   }
8130   else if (si->type & TYPE_YES_NO_AUTO)
8131   {
8132     *(int *)si->value =
8133       (dx == -1 ?
8134        (*(int *)si->value == AUTO ? TRUE :
8135         *(int *)si->value == TRUE ? FALSE : AUTO) :
8136        (*(int *)si->value == TRUE ? AUTO :
8137         *(int *)si->value == AUTO ? FALSE : TRUE));
8138   }
8139   else if (si->type & TYPE_KEY)
8140   {
8141     Key key;
8142
8143     si->type |= TYPE_QUERY;
8144     drawSetupValue(screen_pos, setup_info_pos_raw);
8145     si->type &= ~TYPE_QUERY;
8146
8147     key = getSetupKey();
8148     if (key != KSYM_UNDEFINED)
8149       *(Key *)si->value = key;
8150   }
8151   else if (si->type & TYPE_PLAYER)
8152   {
8153     int player_nr = *(int *)si->value;
8154
8155     if (dx)
8156       player_nr += dx;
8157     else
8158       player_nr = Request("Choose player", REQ_PLAYER) - 1;
8159
8160     *(int *)si->value = MIN(MAX(0, player_nr), MAX_PLAYERS - 1);
8161   }
8162
8163   drawSetupValue(screen_pos, setup_info_pos_raw);
8164
8165   // fullscreen state may have changed at this point
8166   if (si->value == &setup.fullscreen)
8167     ToggleFullscreenIfNeeded();
8168
8169   // network mode may have changed at this point
8170   if (si->value == &setup.network_mode)
8171     ToggleNetworkModeIfNeeded();
8172
8173   // API server mode may have changed at this point
8174   if (si->value == &setup.use_api_server)
8175     ToggleUseApiServerIfNeeded();
8176
8177   // game speed list may have changed at this point
8178   if (si->value == &setup.game_speed_extended)
8179     ToggleGameSpeedsListIfNeeded();
8180 }
8181
8182 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
8183 {
8184   static struct TokenInfo *setup_info_final = NULL;
8185   int list_size = 0;
8186   int list_pos = 0;
8187   int i;
8188
8189   // determine maximum list size of target list
8190   while (setup_info_orig[list_size++].type != 0);
8191
8192   // free, allocate and clear memory for target list
8193   checked_free(setup_info_final);
8194   setup_info_final = checked_calloc(list_size * sizeof(struct TokenInfo));
8195
8196   // copy setup info list without setup entries marked as hidden
8197   for (i = 0; setup_info_orig[i].type != 0; i++)
8198   {
8199     // skip setup entries configured to be hidden
8200     if (hideSetupEntry(setup_info_orig[i].value))
8201       continue;
8202
8203     // skip skippable setup entries if screen is lower than usual
8204     if (SCR_FIELDY < SCR_FIELDY_DEFAULT &&
8205         setup_info_orig[i].type == TYPE_SKIPPABLE)
8206       continue;
8207
8208     setup_info_final[list_pos++] = setup_info_orig[i];
8209   }
8210
8211   return setup_info_final;
8212 }
8213
8214 static void DrawSetupScreen_Generic(void)
8215 {
8216   int fade_mask = REDRAW_FIELD;
8217   boolean redraw_all = FALSE;
8218   char *title_string = NULL;
8219   int i;
8220
8221   if (CheckFadeAll())
8222     fade_mask = REDRAW_ALL;
8223
8224   UnmapAllGadgets();
8225   FadeMenuSoundsAndMusic();
8226
8227   FreeScreenGadgets();
8228   CreateScreenGadgets();
8229
8230   if (redraw_mask & REDRAW_ALL)
8231     redraw_all = TRUE;
8232
8233   FadeOut(fade_mask);
8234
8235   // needed if different viewport properties defined for setup screen
8236   ChangeViewportPropertiesIfNeeded();
8237
8238   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
8239
8240   ClearField();
8241
8242   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
8243
8244   if (setup_mode == SETUP_MODE_MAIN)
8245   {
8246     setup_info = setup_info_main;
8247     title_string = STR_SETUP_MAIN;
8248   }
8249   else if (setup_mode == SETUP_MODE_GAME)
8250   {
8251     setup_info = setup_info_game;
8252     title_string = STR_SETUP_GAME;
8253   }
8254   else if (setup_mode == SETUP_MODE_ENGINES)
8255   {
8256     setup_info = setup_info_engines;
8257     title_string = STR_SETUP_ENGINES;
8258   }
8259   else if (setup_mode == SETUP_MODE_EDITOR)
8260   {
8261     setup_info = setup_info_editor;
8262     title_string = STR_SETUP_EDITOR;
8263   }
8264   else if (setup_mode == SETUP_MODE_GRAPHICS)
8265   {
8266     setup_info = setup_info_graphics;
8267     title_string = STR_SETUP_GRAPHICS;
8268   }
8269   else if (setup_mode == SETUP_MODE_SOUND)
8270   {
8271     setup_info = setup_info_sound;
8272     title_string = STR_SETUP_SOUND;
8273   }
8274   else if (setup_mode == SETUP_MODE_ARTWORK)
8275   {
8276     setup_info = setup_info_artwork;
8277     title_string = STR_SETUP_ARTWORK;
8278   }
8279   else if (setup_mode == SETUP_MODE_TOUCH)
8280   {
8281     setup_info = setup_info_touch;
8282     title_string = STR_SETUP_TOUCH;
8283
8284     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_VIRTUAL_BUTTONS))
8285       setup_info = setup_info_touch_virtual_buttons[GRID_ACTIVE_NR()];
8286     else if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
8287       setup_info = setup_info_touch_wipe_gestures;
8288   }
8289   else if (setup_mode == SETUP_MODE_SHORTCUTS)
8290   {
8291     setup_info = setup_info_shortcuts;
8292     title_string = STR_SETUP_SHORTCUTS;
8293   }
8294   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
8295   {
8296     setup_info = setup_info_shortcuts_1;
8297     title_string = STR_SETUP_SHORTCUTS;
8298   }
8299   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
8300   {
8301     setup_info = setup_info_shortcuts_2;
8302     title_string = STR_SETUP_SHORTCUTS;
8303   }
8304   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
8305   {
8306     setup_info = setup_info_shortcuts_3;
8307     title_string = STR_SETUP_SHORTCUTS;
8308   }
8309   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
8310   {
8311     setup_info = setup_info_shortcuts_4;
8312     title_string = STR_SETUP_SHORTCUTS;
8313   }
8314   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
8315   {
8316     setup_info = setup_info_shortcuts_5;
8317     title_string = STR_SETUP_SHORTCUTS;
8318   }
8319
8320   // use modified setup info without setup entries marked as hidden
8321   setup_info = getSetupInfoFinal(setup_info);
8322
8323   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
8324
8325   // determine maximal number of setup entries that can be displayed on screen
8326   num_setup_info = 0;
8327   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
8328     num_setup_info++;
8329
8330   // determine maximal number of setup entries available for this setup screen
8331   max_setup_info = 0;
8332   for (i = 0; setup_info[i].type != 0; i++)
8333     max_setup_info++;
8334
8335   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
8336
8337   MapScreenGadgets(max_setup_info);
8338
8339   if (redraw_all)
8340     redraw_mask = fade_mask = REDRAW_ALL;
8341
8342   DrawMaskedBorder(fade_mask);
8343
8344   FadeIn(fade_mask);
8345 }
8346
8347 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
8348 {
8349   menu_info = setup_info;
8350
8351   HandleMenuScreen(mx, my, dx, dy, button,
8352                    setup_mode, num_setup_info, max_setup_info);
8353 }
8354
8355 static void DrawSetupScreen_Input(void)
8356 {
8357   int i;
8358
8359   FadeOut(REDRAW_FIELD);
8360
8361   ClearField();
8362
8363   setup_info = getSetupInfoFinal(setup_info_input);
8364
8365   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, STR_SETUP_INPUT);
8366
8367   for (i = 0; setup_info[i].type != 0; i++)
8368   {
8369     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
8370       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
8371     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
8372       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
8373     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
8374       initCursor(i, IMG_MENU_BUTTON);
8375
8376     DrawCursorAndText_Setup(i, -1, FALSE);
8377   }
8378
8379   // create gadgets for setup input menu screen
8380   FreeScreenGadgets();
8381   CreateScreenGadgets();
8382
8383   // map gadgets for setup input menu screen
8384   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
8385
8386   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
8387
8388   FadeIn(REDRAW_FIELD);
8389 }
8390
8391 static void setJoystickDeviceToNr(char *device_name, int device_nr)
8392 {
8393   if (device_name == NULL)
8394     return;
8395
8396   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
8397     device_nr = 0;
8398
8399   if (strlen(device_name) > 1)
8400   {
8401     char c1 = device_name[strlen(device_name) - 1];
8402     char c2 = device_name[strlen(device_name) - 2];
8403
8404     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
8405       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
8406   }
8407   else
8408     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
8409             strlen(device_name));
8410 }
8411
8412 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
8413 {
8414   int i;
8415   static struct SetupKeyboardInfo custom_key;
8416   static struct
8417   {
8418     Key *key;
8419     char *text;
8420   } custom[] =
8421   {
8422     { &custom_key.left,  "Axis/Pad Left"  },
8423     { &custom_key.right, "Axis/Pad Right" },
8424     { &custom_key.up,    "Axis/Pad Up"    },
8425     { &custom_key.down,  "Axis/Pad Down"  },
8426     { &custom_key.snap,  "Button 1/A/X"   },
8427     { &custom_key.drop,  "Button 2/B/Y"   }
8428   };
8429   static char *joystick_name[MAX_PLAYERS] =
8430   {
8431     "Joystick1",
8432     "Joystick2",
8433     "Joystick3",
8434     "Joystick4"
8435   };
8436   int font_nr_menu = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
8437   int font_nr_info = FONT_MENU_1;
8438   int font_nr_name = FONT_VALUE_OLD;
8439   int font_nr_on   = FONT_VALUE_1;
8440   int font_nr_off  = FONT_VALUE_OLD;
8441   int pos = 4;
8442
8443   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8444   {
8445     font_nr_info = FONT_MENU_2;
8446     font_nr_on   = FONT_VALUE_NARROW;
8447     font_nr_off  = FONT_VALUE_OLD_NARROW;
8448   }
8449
8450   custom_key = setup.input[player_nr].key;
8451
8452   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
8453            FONT_INPUT_1_ACTIVE);
8454
8455   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8456                              TILEX, TILEY);
8457   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
8458                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
8459
8460   if (setup.input[player_nr].use_joystick)
8461   {
8462     char *device_name = setup.input[player_nr].joy.device_name;
8463     int joystick_nr = getJoystickNrFromDeviceName(device_name);
8464     boolean joystick_active = CheckJoystickOpened(joystick_nr);
8465     char *text = joystick_name[joystick_nr];
8466     int font_nr = (joystick_active ? font_nr_on : font_nr_off);
8467
8468     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
8469     DrawText(mSX + 32, mSY + 4 * 32, "Configure", font_nr_menu);
8470   }
8471   else
8472   {
8473     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", font_nr_on);
8474     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", font_nr_menu);
8475   }
8476
8477   if (SCR_FIELDY >= SCR_FIELDY_DEFAULT)
8478     DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", font_nr_info);
8479   else
8480     pos = 3;
8481
8482   drawCursorXY(1, pos + 0, IMG_MENU_BUTTON_LEFT);
8483   drawCursorXY(1, pos + 1, IMG_MENU_BUTTON_RIGHT);
8484   drawCursorXY(1, pos + 2, IMG_MENU_BUTTON_UP);
8485   drawCursorXY(1, pos + 3, IMG_MENU_BUTTON_DOWN);
8486
8487   DrawText(mSX + 2 * 32, mSY + (pos + 2) * 32, ":", font_nr_name);
8488   DrawText(mSX + 2 * 32, mSY + (pos + 3) * 32, ":", font_nr_name);
8489   DrawText(mSX + 2 * 32, mSY + (pos + 4) * 32, ":", font_nr_name);
8490   DrawText(mSX + 2 * 32, mSY + (pos + 5) * 32, ":", font_nr_name);
8491   DrawText(mSX + 1 * 32, mSY + (pos + 6) * 32, "Snap Field:", font_nr_name);
8492   DrawText(mSX + 1 * 32, mSY + (pos + 8) * 32, "Drop Element:", font_nr_name);
8493
8494   for (i = 0; i < 6; i++)
8495   {
8496     int ypos = (pos + 2) + i + (i > 3 ? i - 3 : 0);
8497
8498     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8499              "              ", font_nr_on);
8500     DrawText(mSX + 3 * 32, mSY + ypos * 32,
8501              (setup.input[player_nr].use_joystick ?
8502               custom[i].text :
8503               getKeyNameFromKey(*custom[i].key)), font_nr_on);
8504   }
8505 }
8506
8507 static int input_player_nr = 0;
8508
8509 static void HandleSetupScreen_Input_Player(int step, int direction)
8510 {
8511   int old_player_nr = input_player_nr;
8512   int new_player_nr;
8513
8514   new_player_nr = old_player_nr + step * direction;
8515   if (new_player_nr < 0)
8516     new_player_nr = 0;
8517   if (new_player_nr > MAX_PLAYERS - 1)
8518     new_player_nr = MAX_PLAYERS - 1;
8519
8520   if (new_player_nr != old_player_nr)
8521   {
8522     input_player_nr = new_player_nr;
8523
8524     drawPlayerSetupInputInfo(input_player_nr, FALSE);
8525   }
8526 }
8527
8528 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
8529 {
8530   static int choice = 0;
8531   int x = 0;
8532   int y = choice;
8533   int pos_start  = SETUPINPUT_SCREEN_POS_START;
8534   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
8535   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
8536   int pos_end    = SETUPINPUT_SCREEN_POS_END;
8537
8538   if (SCR_FIELDY < SCR_FIELDY_DEFAULT)
8539   {
8540     int i;
8541
8542     for (i = 0; setup_info_input[i].type != 0; i++)
8543     {
8544       // adjust menu structure according to skipped setup entries
8545       if (setup_info_input[i].type == TYPE_SKIPPABLE)
8546       {
8547         pos_empty2--;
8548         pos_end--;
8549       }
8550     }
8551   }
8552
8553   if (button == MB_MENU_INITIALIZE)
8554   {
8555     // input setup menu may have changed size due to graphics configuration
8556     if (choice >= pos_empty1)
8557       choice = pos_end;
8558
8559     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
8560
8561     DrawCursorAndText_Setup(choice, -1, TRUE);
8562
8563     return;
8564   }
8565   else if (button == MB_MENU_LEAVE)
8566   {
8567     setup_mode = SETUP_MODE_MAIN;
8568     DrawSetupScreen();
8569     InitJoysticks();
8570
8571     return;
8572   }
8573
8574   if (mx || my)         // mouse input
8575   {
8576     x = (mx - mSX) / 32;
8577     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
8578   }
8579   else if (dx || dy)    // keyboard input
8580   {
8581     if (dx && choice == 0)
8582       x = (dx < 0 ? 10 : 12);
8583     else if ((dx && choice == 1) ||
8584              (dx == -1 && choice == pos_end))
8585       button = MB_MENU_CHOICE;
8586     else if (dy)
8587       y = choice + dy;
8588
8589     if (y >= pos_empty1 && y <= pos_empty2)
8590       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
8591   }
8592
8593   if (y == 0 && dx != 0 && button)
8594   {
8595     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
8596   }
8597   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
8598            y >= pos_start && y <= pos_end &&
8599            !(y >= pos_empty1 && y <= pos_empty2))
8600   {
8601     if (button)
8602     {
8603       if (y != choice)
8604       {
8605         DrawCursorAndText_Setup(choice, -1, FALSE);
8606         DrawCursorAndText_Setup(y, -1, TRUE);
8607
8608         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
8609
8610         choice = y;
8611       }
8612     }
8613     else
8614     {
8615       if (y == 1)
8616       {
8617         char *device_name = setup.input[input_player_nr].joy.device_name;
8618
8619         if (!setup.input[input_player_nr].use_joystick)
8620         {
8621           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
8622
8623           setJoystickDeviceToNr(device_name, new_device_nr);
8624           setup.input[input_player_nr].use_joystick = TRUE;
8625         }
8626         else
8627         {
8628           int device_nr = getJoystickNrFromDeviceName(device_name);
8629           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
8630
8631           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
8632             setup.input[input_player_nr].use_joystick = FALSE;
8633           else
8634             setJoystickDeviceToNr(device_name, new_device_nr);
8635         }
8636
8637         drawPlayerSetupInputInfo(input_player_nr, FALSE);
8638       }
8639       else if (y == 2)
8640       {
8641         if (setup.input[input_player_nr].use_joystick)
8642           ConfigureJoystick(input_player_nr);
8643         else
8644           CustomizeKeyboard(input_player_nr);
8645       }
8646       else if (y == pos_end)
8647       {
8648         InitJoysticks();
8649
8650         FadeSetLeaveMenu();
8651
8652         setup_mode = SETUP_MODE_MAIN;
8653         DrawSetupScreen();
8654       }
8655     }
8656   }
8657 }
8658
8659 static boolean CustomizeKeyboardMain(int player_nr)
8660 {
8661   int i;
8662   int step_nr;
8663   boolean finished = FALSE;
8664   static struct SetupKeyboardInfo custom_key;
8665   static struct
8666   {
8667     Key *key;
8668     char *text;
8669   } customize_step[] =
8670   {
8671     { &custom_key.left,  "Move Left"    },
8672     { &custom_key.right, "Move Right"   },
8673     { &custom_key.up,    "Move Up"      },
8674     { &custom_key.down,  "Move Down"    },
8675     { &custom_key.snap,  "Snap Field"   },
8676     { &custom_key.drop,  "Drop Element" }
8677   };
8678   int font_nr_old = FONT_VALUE_OLD;
8679   int font_nr_new = FONT_VALUE_1;
8680   boolean success = FALSE;
8681
8682   if (SCR_FIELDX < SCR_FIELDX_DEFAULT)
8683   {
8684     font_nr_old = FONT_VALUE_OLD_NARROW;
8685     font_nr_new = FONT_VALUE_NARROW;
8686   }
8687
8688   // read existing key bindings from player setup
8689   custom_key = setup.input[player_nr].key;
8690
8691   FadeSetEnterMenu();
8692   FadeOut(REDRAW_FIELD);
8693
8694   ClearField();
8695
8696   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
8697
8698   step_nr = 0;
8699   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8700            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8701   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8702            "Key:", FONT_INPUT_1_ACTIVE);
8703   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8704            getKeyNameFromKey(*customize_step[step_nr].key), font_nr_old);
8705
8706   FadeIn(REDRAW_FIELD);
8707
8708   while (!finished)
8709   {
8710     Event event;
8711
8712     if (NextValidEvent(&event))
8713     {
8714       switch (event.type)
8715       {
8716         case EVENT_KEYPRESS:
8717           {
8718             Key key = GetEventKey((KeyEvent *)&event, FALSE);
8719
8720             // press 'Escape' to abort and keep the old key bindings
8721             if (key == KSYM_Escape)
8722             {
8723               FadeSkipNextFadeIn();
8724
8725               finished = TRUE;
8726
8727               break;
8728             }
8729
8730             // press 'Enter' to keep the existing key binding
8731             if (key == KSYM_Return)
8732               key = *customize_step[step_nr].key;
8733
8734             // check if key already used
8735             for (i = 0; i < step_nr; i++)
8736               if (*customize_step[i].key == key)
8737                 break;
8738             if (i < step_nr)
8739               break;
8740
8741             // got new key binding
8742             *customize_step[step_nr].key = key;
8743             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8744                      "             ", font_nr_new);
8745             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8746                      getKeyNameFromKey(key), font_nr_new);
8747             step_nr++;
8748
8749             // un-highlight last query
8750             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
8751                      customize_step[step_nr - 1].text, FONT_MENU_1);
8752             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
8753                      "Key:", FONT_MENU_1);
8754
8755             // all keys configured
8756             if (step_nr == 6)
8757             {
8758               finished = TRUE;
8759               success = TRUE;
8760
8761               break;
8762             }
8763
8764             // query next key binding
8765             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
8766                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
8767             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
8768                      "Key:", FONT_INPUT_1_ACTIVE);
8769             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
8770                      getKeyNameFromKey(*customize_step[step_nr].key),
8771                      font_nr_old);
8772           }
8773           break;
8774
8775         case EVENT_KEYRELEASE:
8776           key_joystick_mapping = 0;
8777           break;
8778
8779         default:
8780           HandleOtherEvents(&event);
8781           break;
8782       }
8783     }
8784
8785     BackToFront();
8786   }
8787
8788   // write new key bindings back to player setup, if successfully finished
8789   if (success)
8790     setup.input[player_nr].key = custom_key;
8791
8792   return success;
8793 }
8794
8795 void CustomizeKeyboard(int player_nr)
8796 {
8797   boolean success = CustomizeKeyboardMain(player_nr);
8798
8799   if (success)
8800   {
8801     int font_nr = FONT_TITLE_1;
8802     int font_height = getFontHeight(font_nr);
8803     int ypos1 = SYSIZE / 2 - font_height * 2;
8804     int ypos2 = SYSIZE / 2 - font_height * 1;
8805     unsigned int wait_frame_delay = 0;
8806     unsigned int wait_frame_delay_value = 2000;
8807
8808     ResetDelayCounter(&wait_frame_delay);
8809
8810     ClearField();
8811
8812     DrawTextSCentered(ypos1, font_nr, "Keyboard");
8813     DrawTextSCentered(ypos2, font_nr, "configured!");
8814
8815     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
8816       BackToFront();
8817
8818     ClearEventQueue();
8819   }
8820
8821   DrawSetupScreen_Input();
8822 }
8823
8824 // game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com>
8825
8826 #define MARKER_BUTTON           1
8827 #define MARKER_AXIS_X           2
8828 #define MARKER_AXIS_Y           3
8829
8830 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
8831 {
8832   static boolean bitmaps_initialized = FALSE;
8833   boolean screen_initialized = FALSE;
8834   static Bitmap *controller, *button, *axis_x, *axis_y;
8835   char *name;
8836   boolean success = TRUE;
8837   boolean done = FALSE, next = FALSE;
8838   Event event;
8839   int alpha = 200, alpha_step = -1;
8840   int alpha_ticks = 0;
8841   char mapping[4096], temp[256];
8842   int font_name = MENU_SETUP_FONT_TITLE;
8843   int font_info = MENU_SETUP_FONT_TEXT;
8844   int spacing_name = menu.line_spacing_setup[SETUP_MODE_INPUT];
8845   int spacing_line = menu.line_spacing_setup[SETUP_MODE_INPUT];
8846   int spacing_para = menu.paragraph_spacing_setup[SETUP_MODE_INPUT];
8847   int ystep_name = getMenuTextStep(spacing_name, font_name);
8848   int ystep_line = getMenuTextStep(spacing_line, font_info);
8849   int ystep_para = getMenuTextStep(spacing_para, font_info);
8850   int i, j;
8851
8852   struct
8853   {
8854     int x, y;
8855     int marker;
8856     char *field;
8857     int axis, button, hat, hat_value;
8858     char mapping[4096];
8859   }
8860   *step, *prev_step, steps[] =
8861   {
8862     { 356, 155, MARKER_BUTTON, "a",             },
8863     { 396, 122, MARKER_BUTTON, "b",             },
8864     { 320, 125, MARKER_BUTTON, "x",             },
8865     { 358,  95, MARKER_BUTTON, "y",             },
8866     { 162, 125, MARKER_BUTTON, "back",          },
8867     { 216, 125, MARKER_BUTTON, "guide",         },
8868     { 271, 125, MARKER_BUTTON, "start",         },
8869     { 110, 200, MARKER_BUTTON, "dpleft",        },
8870     { 146, 228, MARKER_BUTTON, "dpdown",        },
8871     { 178, 200, MARKER_BUTTON, "dpright",       },
8872     { 146, 172, MARKER_BUTTON, "dpup",          },
8873     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
8874     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
8875     { 382,  40, MARKER_BUTTON, "rightshoulder", },
8876     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
8877     {  73, 141, MARKER_BUTTON, "leftstick",     },
8878     { 282, 210, MARKER_BUTTON, "rightstick",    },
8879     {  73, 141, MARKER_AXIS_X, "leftx",         },
8880     {  73, 141, MARKER_AXIS_Y, "lefty",         },
8881     { 282, 210, MARKER_AXIS_X, "rightx",        },
8882     { 282, 210, MARKER_AXIS_Y, "righty",        },
8883   };
8884
8885   unsigned int event_frame_delay = 0;
8886   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
8887
8888   ResetDelayCounter(&event_frame_delay);
8889
8890   if (!bitmaps_initialized)
8891   {
8892     controller = LoadCustomImage("joystick/controller.png");
8893     button     = LoadCustomImage("joystick/button.png");
8894     axis_x     = LoadCustomImage("joystick/axis_x.png");
8895     axis_y     = LoadCustomImage("joystick/axis_y.png");
8896
8897     bitmaps_initialized = TRUE;
8898   }
8899
8900   name = getFormattedJoystickName(SDL_JoystickName(joystick));
8901
8902 #if DEBUG_JOYSTICKS
8903   // print info about the joystick we are watching
8904   Debug("joystick", "watching joystick %d: (%s)",
8905         SDL_JoystickInstanceID(joystick), name);
8906   Debug("joystick", "joystick has %d axes, %d hats, %d balls, and %d buttons",
8907         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
8908         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
8909 #endif
8910
8911   // initialize mapping with GUID and name
8912   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
8913
8914   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
8915            temp, name, SDL_GetPlatform());
8916
8917   // loop through all steps (buttons and axes), getting joystick events
8918   for (i = 0; i < SDL_arraysize(steps) && !done;)
8919   {
8920     Bitmap *marker = button;    // initialize with reliable default value
8921
8922     step = &steps[i];
8923     strcpy(step->mapping, mapping);
8924     step->axis = -1;
8925     step->button = -1;
8926     step->hat = -1;
8927     step->hat_value = -1;
8928
8929     marker = (step->marker == MARKER_BUTTON ? button :
8930               step->marker == MARKER_AXIS_X ? axis_x :
8931               step->marker == MARKER_AXIS_Y ? axis_y : marker);
8932
8933     next = FALSE;
8934
8935     while (!done && !next)
8936     {
8937       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
8938       alpha_ticks = SDL_GetTicks();
8939
8940       if (alpha >= 255)
8941       {
8942         alpha = 255;
8943         alpha_step = -1;
8944       }
8945       else if (alpha < 128)
8946       {
8947         alpha = 127;
8948         alpha_step = 1;
8949       }
8950
8951       int controller_x = SX + (SXSIZE - controller->width) / 2;
8952       int controller_y = SY + ystep_line;
8953
8954       int marker_x = controller_x + step->x;
8955       int marker_y = controller_y + step->y;
8956
8957       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
8958       int ystart2 = ystart1 + ystep_name + ystep_line;
8959
8960       ClearField();
8961
8962       DrawTextSCentered(ystart1, font_name, name);
8963
8964       DrawTextSCentered(ystart2, font_info,
8965                         "Press buttons and move axes on");
8966       ystart2 += ystep_line;
8967       DrawTextSCentered(ystart2, font_info,
8968                         "your controller when indicated.");
8969       ystart2 += ystep_line;
8970       DrawTextSCentered(ystart2, font_info,
8971                         "(Your controller may look different.)");
8972       ystart2 += ystep_para;
8973
8974 #if defined(PLATFORM_ANDROID)
8975       DrawTextSCentered(ystart2, font_info,
8976                         "To correct a mistake,");
8977       ystart2 += ystep_line;
8978       DrawTextSCentered(ystart2, font_info,
8979                         "press the 'back' button.");
8980       ystart2 += ystep_line;
8981       DrawTextSCentered(ystart2, font_info,
8982                         "To skip a button or axis,");
8983       ystart2 += ystep_line;
8984       DrawTextSCentered(ystart2, font_info,
8985                         "press the 'menu' button.");
8986 #else
8987       DrawTextSCentered(ystart2, font_info,
8988                         "To correct a mistake,");
8989       ystart2 += ystep_line;
8990       DrawTextSCentered(ystart2, font_info,
8991                         "press the 'backspace' key.");
8992       ystart2 += ystep_line;
8993       DrawTextSCentered(ystart2, font_info,
8994                         "To skip a button or axis,");
8995       ystart2 += ystep_line;
8996       DrawTextSCentered(ystart2, font_info,
8997                         "press the 'return' key.");
8998       ystart2 += ystep_line;
8999       DrawTextSCentered(ystart2, font_info,
9000                         "To exit, press the 'escape' key.");
9001 #endif
9002
9003       BlitBitmapMasked(controller, drawto, 0, 0,
9004                        controller->width, controller->height,
9005                        controller_x, controller_y);
9006
9007       SDL_SetSurfaceBlendMode(marker->surface_masked, SDL_BLENDMODE_BLEND);
9008       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
9009
9010       BlitBitmapMasked(marker, drawto, 0, 0,
9011                        marker->width, marker->height,
9012                        marker_x, marker_y);
9013
9014       if (!screen_initialized)
9015         FadeIn(REDRAW_FIELD);
9016       else
9017         BackToFront();
9018
9019       screen_initialized = TRUE;
9020
9021       while (NextValidEvent(&event))
9022       {
9023         switch (event.type)
9024         {
9025           case SDL_JOYAXISMOTION:
9026             if (event.jaxis.value > 20000 ||
9027                 event.jaxis.value < -20000)
9028             {
9029               for (j = 0; j < i; j++)
9030                 if (steps[j].axis == event.jaxis.axis)
9031                   break;
9032
9033               if (j == i)
9034               {
9035                 if (step->marker != MARKER_AXIS_X &&
9036                     step->marker != MARKER_AXIS_Y)
9037                   break;
9038
9039                 step->axis = event.jaxis.axis;
9040                 strcat(mapping, step->field);
9041                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
9042                 strcat(mapping, temp);
9043                 i++;
9044                 next = TRUE;
9045               }
9046             }
9047
9048             break;
9049
9050           case SDL_JOYHATMOTION:
9051             // ignore centering; we're probably just coming back
9052             // to the center from the previous item we set
9053             if (event.jhat.value == SDL_HAT_CENTERED)
9054               break;
9055
9056             for (j = 0; j < i; j++)
9057               if (steps[j].hat == event.jhat.hat &&
9058                   steps[j].hat_value == event.jhat.value)
9059                 break;
9060
9061             if (j == i)
9062             {
9063               step->hat = event.jhat.hat;
9064               step->hat_value = event.jhat.value;
9065               strcat(mapping, step->field);
9066               snprintf(temp, sizeof(temp), ":h%u.%u,",
9067                        event.jhat.hat, event.jhat.value );
9068               strcat(mapping, temp);
9069               i++;
9070               next = TRUE;
9071             }
9072
9073             break;
9074
9075           case SDL_JOYBALLMOTION:
9076             break;
9077
9078           case SDL_JOYBUTTONUP:
9079             for (j = 0; j < i; j++)
9080               if (steps[j].button == event.jbutton.button)
9081                 break;
9082
9083             if (j == i)
9084             {
9085               step->button = event.jbutton.button;
9086               strcat(mapping, step->field);
9087               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
9088               strcat(mapping, temp);
9089               i++;
9090               next = TRUE;
9091             }
9092
9093             break;
9094
9095           case SDL_FINGERDOWN:
9096           case SDL_MOUSEBUTTONDOWN:
9097             // skip this step
9098             i++;
9099             next = TRUE;
9100
9101             break;
9102
9103           case SDL_KEYDOWN:
9104             if (event.key.keysym.sym == KSYM_BackSpace ||
9105                 event.key.keysym.sym == KSYM_Back)
9106             {
9107               if (i == 0)
9108               {
9109                 // leave screen
9110                 success = FALSE;
9111                 done = TRUE;
9112
9113                 break;
9114               }
9115
9116               // undo this step
9117               prev_step = &steps[i - 1];
9118               strcpy(mapping, prev_step->mapping);
9119               i--;
9120               next = TRUE;
9121
9122               break;
9123             }
9124
9125             if (event.key.keysym.sym == KSYM_space ||
9126                 event.key.keysym.sym == KSYM_Return ||
9127                 event.key.keysym.sym == KSYM_Menu)
9128             {
9129               // skip this step
9130               i++;
9131               next = TRUE;
9132
9133               break;
9134             }
9135
9136             if (event.key.keysym.sym == KSYM_Escape)
9137             {
9138               // leave screen
9139               success = FALSE;
9140               done = TRUE;
9141             }
9142
9143             break;
9144
9145           case SDL_QUIT:
9146             program.exit_function(0);
9147             break;
9148
9149           default:
9150             break;
9151         }
9152
9153         // do not handle events for longer than standard frame delay period
9154         if (DelayReached(&event_frame_delay, event_frame_delay_value))
9155           break;
9156       }
9157     }
9158   }
9159
9160   if (success)
9161   {
9162 #if DEBUG_JOYSTICKS
9163     Debug("joystick", "New game controller mapping:\n\n%s\n\n", mapping);
9164 #endif
9165
9166     // activate mapping for this game
9167     SDL_GameControllerAddMapping(mapping);
9168
9169     // save mapping to personal mappings
9170     SaveSetup_AddGameControllerMapping(mapping);
9171   }
9172
9173   // wait until the last pending event was removed from event queue
9174   while (NextValidEvent(&event));
9175
9176   return success;
9177 }
9178
9179 static int ConfigureJoystickMain(int player_nr)
9180 {
9181   char *device_name = setup.input[player_nr].joy.device_name;
9182   int joystick_nr = getJoystickNrFromDeviceName(device_name);
9183   boolean joystick_active = CheckJoystickOpened(joystick_nr);
9184   int success = FALSE;
9185   int i;
9186
9187   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
9188     return JOYSTICK_NOT_AVAILABLE;
9189
9190   if (!joystick_active || !setup.input[player_nr].use_joystick)
9191     return JOYSTICK_NOT_AVAILABLE;
9192
9193   FadeSetEnterMenu();
9194   FadeOut(REDRAW_FIELD);
9195
9196   // close all joystick devices (potentially opened as game controllers)
9197   for (i = 0; i < SDL_NumJoysticks(); i++)
9198     SDLCloseJoystick(i);
9199
9200   // open joystick device as plain joystick to configure as game controller
9201   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
9202
9203   // as the joystick was successfully opened before, this should not happen
9204   if (joystick == NULL)
9205     return FALSE;
9206
9207   // create new game controller mapping (buttons and axes) for joystick device
9208   success = ConfigureJoystickMapButtonsAndAxes(joystick);
9209
9210   // close joystick (and maybe re-open as configured game controller later)
9211   SDL_JoystickClose(joystick);
9212
9213   // re-open all joystick devices (potentially as game controllers)
9214   for (i = 0; i < SDL_NumJoysticks(); i++)
9215     SDLOpenJoystick(i);
9216
9217   // clear all joystick input actions for all joystick devices
9218   SDLClearJoystickState();
9219
9220   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
9221 }
9222
9223 void ConfigureJoystick(int player_nr)
9224 {
9225   boolean state = ConfigureJoystickMain(player_nr);
9226
9227   if (state != JOYSTICK_NOT_CONFIGURED)
9228   {
9229     boolean success = (state == JOYSTICK_CONFIGURED);
9230     char message1[MAX_OUTPUT_LINESIZE + 1];
9231     char *message2 = (success ? "configured!" : "not available!");
9232     char *device_name = setup.input[player_nr].joy.device_name;
9233     int nr = getJoystickNrFromDeviceName(device_name) + 1;
9234     int font_nr = FONT_TITLE_1;
9235     int font_height = getFontHeight(font_nr);
9236     int ypos1 = SYSIZE / 2 - font_height * 2;
9237     int ypos2 = SYSIZE / 2 - font_height * 1;
9238     unsigned int wait_frame_delay = 0;
9239     unsigned int wait_frame_delay_value = 2000;
9240
9241     ResetDelayCounter(&wait_frame_delay);
9242
9243     ClearField();
9244
9245     sprintf(message1, "Joystick %d", nr);
9246
9247     DrawTextSCentered(ypos1, font_nr, message1);
9248     DrawTextSCentered(ypos2, font_nr, message2);
9249
9250     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9251       BackToFront();
9252
9253     ClearEventQueue();
9254   }
9255
9256   DrawSetupScreen_Input();
9257 }
9258
9259 static void MapScreenMenuGadgets_OverlayTouchButtons(int y)
9260 {
9261   if (y < video.screen_height / 3)
9262   {
9263     // remap touch gadgets to access upper part of the screen
9264     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9265     MapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9266   }
9267   else if (y > 2 * video.screen_height / 3)
9268   {
9269     // remap touch gadgets to access lower part of the screen
9270     MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9271     UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH2);
9272   }
9273 }
9274
9275 static boolean ConfigureVirtualButtonsMain(void)
9276 {
9277   static char *customize_step_text[] =
9278   {
9279     "Move Left",
9280     "Move Right",
9281     "Move Up",
9282     "Move Down",
9283     "Snap Field",
9284     "Drop Element"
9285   };
9286   char grid_button[] =
9287   {
9288     CHAR_GRID_BUTTON_LEFT,
9289     CHAR_GRID_BUTTON_RIGHT,
9290     CHAR_GRID_BUTTON_UP,
9291     CHAR_GRID_BUTTON_DOWN,
9292     CHAR_GRID_BUTTON_SNAP,
9293     CHAR_GRID_BUTTON_DROP
9294   };
9295   enum
9296   {
9297     ACTION_NONE,
9298     ACTION_ESCAPE,
9299     ACTION_BACK,
9300     ACTION_NEXT
9301   };
9302   int font_nr = FONT_INPUT_1_ACTIVE;
9303   int font_height = getFontHeight(font_nr);
9304   int ypos1 = SYSIZE / 2 - font_height * 2;
9305   int ypos2 = SYSIZE / 2 - font_height * 1;
9306   boolean success = FALSE;
9307   boolean finished = FALSE;
9308   int step_nr = 0;
9309   char grid_button_draw = CHAR_GRID_BUTTON_NONE;
9310   char grid_button_old[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9311   char grid_button_tmp[MAX_GRID_XSIZE][MAX_GRID_YSIZE];
9312   boolean set_grid_button = FALSE;
9313   int nr = GRID_ACTIVE_NR();
9314   int x, y;
9315
9316   for (x = 0; x < MAX_GRID_XSIZE; x++)
9317     for (y = 0; y < MAX_GRID_YSIZE; y++)
9318       grid_button_old[x][y] = grid_button_tmp[x][y] = overlay.grid_button[x][y];
9319
9320   overlay.grid_button_highlight = grid_button[step_nr];
9321
9322   UnmapAllGadgets();
9323
9324   FadeSetEnterMenu();
9325   FadeOut(REDRAW_FIELD);
9326
9327   ClearField();
9328
9329   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9330   DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9331   DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9332
9333   FadeIn(REDRAW_FIELD);
9334
9335   SetOverlayShowGrid(TRUE);
9336
9337   // map gadgets for setup touch buttons menu screen
9338   MapScreenMenuGadgets(SCREEN_MASK_TOUCH);
9339
9340   while (!finished)
9341   {
9342     Event event;
9343
9344     while (NextValidEvent(&event))
9345     {
9346       int action = ACTION_NONE;
9347
9348       // ---------- handle events and set the resulting action ----------
9349
9350       switch (event.type)
9351       {
9352         case EVENT_USER:
9353           {
9354             UserEvent *user = (UserEvent *)&event;
9355             int id = user->value1;
9356
9357             action = (id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE ||
9358                       id == SCREEN_CTRL_ID_TOUCH_PREV_PAGE2 ? ACTION_BACK :
9359                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE ||
9360                       id == SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2 ? ACTION_NEXT :
9361                       ACTION_NONE);
9362           }
9363           break;
9364
9365         case EVENT_KEYPRESS:
9366           {
9367             Key key = GetEventKey((KeyEvent *)&event, FALSE);
9368
9369             action = (key == KSYM_Escape ?      ACTION_ESCAPE :
9370                       key == KSYM_BackSpace ||
9371                       key == KSYM_Back ?        ACTION_BACK :
9372                       key == KSYM_Return ||
9373                       key == KSYM_Menu ||
9374                       key == KSYM_space ?       ACTION_NEXT :
9375                       ACTION_NONE);
9376           }
9377           break;
9378
9379         case EVENT_KEYRELEASE:
9380           key_joystick_mapping = 0;
9381           break;
9382
9383         case EVENT_BUTTONPRESS:
9384         case EVENT_BUTTONRELEASE:
9385           {
9386             ButtonEvent *button = (ButtonEvent *)&event;
9387
9388             motion_status = FALSE;
9389
9390             if (button->type == EVENT_BUTTONPRESS)
9391               button_status = button->button;
9392             else
9393               button_status = MB_RELEASED;
9394
9395             if (HandleGadgets(button->x, button->y, button_status))
9396             {
9397               // do not handle this button event anymore
9398               break;
9399             }
9400
9401             button->x += video.screen_xoffset;
9402             button->y += video.screen_yoffset;
9403
9404             x = button->x * overlay.grid_xsize / video.screen_width;
9405             y = button->y * overlay.grid_ysize / video.screen_height;
9406
9407             if (button->type == EVENT_BUTTONPRESS)
9408             {
9409               grid_button_draw =
9410                 (overlay.grid_button[x][y] != grid_button[step_nr] ?
9411                  grid_button[step_nr] : CHAR_GRID_BUTTON_NONE);
9412
9413               set_grid_button = TRUE;
9414             }
9415
9416             MapScreenMenuGadgets_OverlayTouchButtons(button->y);
9417           }
9418           break;
9419
9420         case EVENT_MOTIONNOTIFY:
9421           {
9422             MotionEvent *motion = (MotionEvent *)&event;
9423
9424             motion_status = TRUE;
9425
9426             if (HandleGadgets(motion->x, motion->y, button_status))
9427             {
9428               // do not handle this button event anymore
9429               break;
9430             }
9431
9432             motion->x += video.screen_xoffset;
9433             motion->y += video.screen_yoffset;
9434
9435             x = motion->x * overlay.grid_xsize / video.screen_width;
9436             y = motion->y * overlay.grid_ysize / video.screen_height;
9437
9438             set_grid_button = TRUE;
9439
9440             MapScreenMenuGadgets_OverlayTouchButtons(motion->y);
9441           }
9442           break;
9443
9444         case SDL_WINDOWEVENT:
9445           HandleWindowEvent((WindowEvent *) &event);
9446
9447           // check if device has been rotated
9448           if (nr != GRID_ACTIVE_NR())
9449           {
9450             nr = GRID_ACTIVE_NR();
9451
9452             for (x = 0; x < MAX_GRID_XSIZE; x++)
9453               for (y = 0; y < MAX_GRID_YSIZE; y++)
9454                 grid_button_old[x][y] = grid_button_tmp[x][y] =
9455                   overlay.grid_button[x][y];
9456           }
9457
9458           break;
9459
9460         case SDL_APP_WILLENTERBACKGROUND:
9461         case SDL_APP_DIDENTERBACKGROUND:
9462         case SDL_APP_WILLENTERFOREGROUND:
9463         case SDL_APP_DIDENTERFOREGROUND:
9464           HandlePauseResumeEvent((PauseResumeEvent *) &event);
9465           break;
9466
9467         default:
9468           HandleOtherEvents(&event);
9469           break;
9470       }
9471
9472       // ---------- perform action set by handling events ----------
9473
9474       if (action == ACTION_ESCAPE)
9475       {
9476         // abort and restore the old key bindings
9477
9478         for (x = 0; x < MAX_GRID_XSIZE; x++)
9479           for (y = 0; y < MAX_GRID_YSIZE; y++)
9480             overlay.grid_button[x][y] = grid_button_old[x][y];
9481
9482         FadeSkipNextFadeIn();
9483
9484         finished = TRUE;
9485       }
9486       else if (action == ACTION_BACK)
9487       {
9488         // keep the configured key bindings and go to previous page
9489
9490         step_nr--;
9491
9492         if (step_nr < 0)
9493         {
9494           FadeSkipNextFadeIn();
9495
9496           finished = TRUE;
9497         }
9498       }
9499       else if (action == ACTION_NEXT)
9500       {
9501         // keep the configured key bindings and go to next page
9502
9503         step_nr++;
9504
9505         // all virtual buttons configured
9506         if (step_nr == 6)
9507         {
9508           finished = TRUE;
9509           success = TRUE;
9510         }
9511       }
9512
9513       if (action != ACTION_NONE && !finished)
9514       {
9515         for (x = 0; x < MAX_GRID_XSIZE; x++)
9516           for (y = 0; y < MAX_GRID_YSIZE; y++)
9517             grid_button_tmp[x][y] = overlay.grid_button[x][y];
9518
9519         overlay.grid_button_highlight = grid_button[step_nr];
9520
9521         // configure next virtual button
9522
9523         ClearField();
9524
9525         DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Virtual Buttons");
9526         DrawTextSCentered(ypos1, font_nr, "Select tiles to");
9527         DrawTextSCentered(ypos2, font_nr, customize_step_text[step_nr]);
9528       }
9529
9530       if (set_grid_button)
9531       {
9532         overlay.grid_button[x][y] =
9533           (grid_button_draw != CHAR_GRID_BUTTON_NONE ? grid_button_draw :
9534            grid_button_tmp[x][y] == grid_button[step_nr] ? CHAR_GRID_BUTTON_NONE :
9535            grid_button_tmp[x][y]);
9536
9537         set_grid_button = FALSE;
9538       }
9539     }
9540
9541     BackToFront();
9542   }
9543
9544   for (x = 0; x < MAX_GRID_XSIZE; x++)
9545     for (y = 0; y < MAX_GRID_YSIZE; y++)
9546       setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9547
9548   overlay.grid_button_highlight = CHAR_GRID_BUTTON_NONE;
9549
9550   SetOverlayShowGrid(FALSE);
9551
9552   return success;
9553 }
9554
9555 void ConfigureVirtualButtons(void)
9556 {
9557   boolean success = ConfigureVirtualButtonsMain();
9558
9559   UnmapScreenMenuGadgets(SCREEN_MASK_TOUCH |
9560                          SCREEN_MASK_TOUCH2);
9561
9562   if (success)
9563   {
9564     int font_nr = FONT_TITLE_1;
9565     int font_height = getFontHeight(font_nr);
9566     int ypos1 = SYSIZE / 2 - font_height * 2;
9567     int ypos2 = SYSIZE / 2 - font_height * 1;
9568     unsigned int wait_frame_delay = 0;
9569     unsigned int wait_frame_delay_value = 2000;
9570
9571     ResetDelayCounter(&wait_frame_delay);
9572
9573     ClearField();
9574
9575     DrawTextSCentered(ypos1, font_nr, "Virtual buttons");
9576     DrawTextSCentered(ypos2, font_nr, "configured!");
9577
9578     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
9579       BackToFront();
9580
9581     ClearEventQueue();
9582   }
9583 }
9584
9585 void DrawSetupScreen(void)
9586 {
9587   align_xoffset = 0;
9588   align_yoffset = 0;
9589
9590   if (setup_mode == SETUP_MODE_INPUT)
9591     DrawSetupScreen_Input();
9592   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9593     DrawChooseTree(&scores_type_current);
9594   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9595     DrawChooseTree(&game_speed_current);
9596   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9597     DrawChooseTree(&scroll_delay_current);
9598   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9599     DrawChooseTree(&snapshot_mode_current);
9600   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9601     DrawChooseTree(&window_size_current);
9602   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9603     DrawChooseTree(&scaling_type_current);
9604   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9605     DrawChooseTree(&rendering_mode_current);
9606   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9607     DrawChooseTree(&vsync_mode_current);
9608   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9609     DrawChooseTree(&artwork.gfx_current);
9610   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9611     DrawChooseTree(&artwork.snd_current);
9612   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9613     DrawChooseTree(&artwork.mus_current);
9614   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9615     DrawChooseTree(&volume_simple_current);
9616   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9617     DrawChooseTree(&volume_loops_current);
9618   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9619     DrawChooseTree(&volume_music_current);
9620   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9621     DrawChooseTree(&touch_control_current);
9622   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9623     DrawChooseTree(&move_distance_current);
9624   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9625     DrawChooseTree(&drop_distance_current);
9626   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9627     DrawChooseTree(&transparency_current);
9628   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9629     DrawChooseTree(&grid_size_current[0][0]);
9630   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9631     DrawChooseTree(&grid_size_current[0][1]);
9632   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9633     DrawChooseTree(&grid_size_current[1][0]);
9634   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9635     DrawChooseTree(&grid_size_current[1][1]);
9636   else
9637     DrawSetupScreen_Generic();
9638
9639   PlayMenuSoundsAndMusic();
9640 }
9641
9642 void RedrawSetupScreenAfterFullscreenToggle(void)
9643 {
9644   if (setup_mode == SETUP_MODE_GRAPHICS ||
9645       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9646   {
9647     // update list selection from "setup.window_scaling_percent"
9648     execSetupGraphics_setWindowSizes(TRUE);
9649
9650     DrawSetupScreen();
9651   }
9652 }
9653
9654 void RedrawSetupScreenAfterScreenRotation(int nr)
9655 {
9656   int x, y;
9657
9658   if (setup_mode == SETUP_MODE_TOUCH)
9659   {
9660     // update virtual button settings (depending on screen orientation)
9661     DrawSetupScreen();
9662   }
9663   else if (setup_mode == SETUP_MODE_CONFIG_VIRT_BUTTONS)
9664   {
9665     // save already configured virtual buttons
9666     for (x = 0; x < MAX_GRID_XSIZE; x++)
9667       for (y = 0; y < MAX_GRID_YSIZE; y++)
9668         setup.touch.grid_button[nr][x][y] = overlay.grid_button[x][y];
9669   }
9670 }
9671
9672 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
9673 {
9674   if (setup_mode == SETUP_MODE_INPUT)
9675     HandleSetupScreen_Input(mx, my, dx, dy, button);
9676   else if (setup_mode == SETUP_MODE_CHOOSE_SCORES_TYPE)
9677     HandleChooseTree(mx, my, dx, dy, button, &scores_type_current);
9678   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
9679     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
9680   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
9681     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
9682   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
9683     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
9684   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
9685     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
9686   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
9687     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
9688   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
9689     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
9690   else if (setup_mode == SETUP_MODE_CHOOSE_VSYNC)
9691     HandleChooseTree(mx, my, dx, dy, button, &vsync_mode_current);
9692   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
9693     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
9694   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
9695     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
9696   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
9697     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
9698   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
9699     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
9700   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
9701     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
9702   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
9703     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
9704   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
9705     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
9706   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
9707     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
9708   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
9709     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
9710   else if (setup_mode == SETUP_MODE_CHOOSE_TRANSPARENCY)
9711     HandleChooseTree(mx, my, dx, dy, button, &transparency_current);
9712   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_0)
9713     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][0]);
9714   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_0)
9715     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[0][1]);
9716   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_XSIZE_1)
9717     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][0]);
9718   else if (setup_mode == SETUP_MODE_CHOOSE_GRID_YSIZE_1)
9719     HandleChooseTree(mx, my, dx, dy, button, &grid_size_current[1][1]);
9720   else
9721     HandleSetupScreen_Generic(mx, my, dx, dy, button);
9722 }
9723
9724 void HandleGameActions(void)
9725 {
9726   if (setup.ask_on_game_over)
9727     CheckGameOver();
9728
9729   if (game.restart_game_message != NULL)
9730   {
9731     RequestRestartGame(game.restart_game_message);
9732
9733     return;
9734   }
9735
9736   if (game_status != GAME_MODE_PLAYING)
9737     return;
9738
9739   GameActions();                // main game loop
9740
9741   if (tape.auto_play && !tape.playing)
9742     AutoPlayTapesContinue();    // continue automatically playing next tape
9743 }
9744
9745
9746 // ---------- new screen button stuff --------------------------------------
9747
9748 static struct
9749 {
9750   int gfx_unpressed, gfx_pressed;
9751   struct MenuPosInfo *pos;
9752   boolean *check_value;
9753   int gadget_id;
9754   int screen_mask;
9755   unsigned int event_mask;
9756   boolean is_touch_button;
9757   char *infotext;
9758 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
9759 {
9760   {
9761     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
9762     &menu.main.button.prev_level, NULL,
9763     SCREEN_CTRL_ID_PREV_LEVEL,
9764     SCREEN_MASK_MAIN,
9765     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9766     FALSE, "previous level"
9767   },
9768   {
9769     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
9770     &menu.main.button.next_level, NULL,
9771     SCREEN_CTRL_ID_NEXT_LEVEL,
9772     SCREEN_MASK_MAIN,
9773     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9774     FALSE, "next level"
9775   },
9776   {
9777     IMG_MENU_BUTTON_PREV_LEVEL2, IMG_MENU_BUTTON_PREV_LEVEL2_ACTIVE,
9778     &menu.scores.button.prev_level, NULL,
9779     SCREEN_CTRL_ID_PREV_LEVEL2,
9780     SCREEN_MASK_SCORES,
9781     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9782     FALSE, "previous level"
9783   },
9784   {
9785     IMG_MENU_BUTTON_NEXT_LEVEL2, IMG_MENU_BUTTON_NEXT_LEVEL2_ACTIVE,
9786     &menu.scores.button.next_level, NULL,
9787     SCREEN_CTRL_ID_NEXT_LEVEL2,
9788     SCREEN_MASK_SCORES,
9789     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9790     FALSE, "next level"
9791   },
9792   {
9793     IMG_MENU_BUTTON_FIRST_LEVEL, IMG_MENU_BUTTON_FIRST_LEVEL_ACTIVE,
9794     &menu.main.button.first_level, NULL,
9795     SCREEN_CTRL_ID_FIRST_LEVEL,
9796     SCREEN_MASK_MAIN,
9797     GD_EVENT_RELEASED,
9798     FALSE, "first level"
9799   },
9800   {
9801     IMG_MENU_BUTTON_LAST_LEVEL, IMG_MENU_BUTTON_LAST_LEVEL_ACTIVE,
9802     &menu.main.button.last_level, NULL,
9803     SCREEN_CTRL_ID_LAST_LEVEL,
9804     SCREEN_MASK_MAIN,
9805     GD_EVENT_RELEASED,
9806     FALSE, "last level"
9807   },
9808   {
9809     IMG_MENU_BUTTON_LEVEL_NUMBER, IMG_MENU_BUTTON_LEVEL_NUMBER_ACTIVE,
9810     &menu.main.button.level_number, NULL,
9811     SCREEN_CTRL_ID_LEVEL_NUMBER,
9812     SCREEN_MASK_MAIN,
9813     GD_EVENT_RELEASED,
9814     FALSE, "level number"
9815   },
9816   {
9817     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
9818     &menu.setup.button.prev_player, NULL,
9819     SCREEN_CTRL_ID_PREV_PLAYER,
9820     SCREEN_MASK_INPUT,
9821     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9822     FALSE, "previous player"
9823   },
9824   {
9825     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
9826     &menu.setup.button.next_player, NULL,
9827     SCREEN_CTRL_ID_NEXT_PLAYER,
9828     SCREEN_MASK_INPUT,
9829     GD_EVENT_PRESSED | GD_EVENT_REPEATED,
9830     FALSE, "next player"
9831   },
9832   {
9833     IMG_MENU_BUTTON_INSERT_SOLUTION, IMG_MENU_BUTTON_INSERT_SOLUTION_ACTIVE,
9834     &menu.main.button.insert_solution, NULL,
9835     SCREEN_CTRL_ID_INSERT_SOLUTION,
9836     SCREEN_MASK_MAIN_HAS_SOLUTION,
9837     GD_EVENT_RELEASED,
9838     FALSE, "insert solution tape"
9839   },
9840   {
9841     IMG_MENU_BUTTON_PLAY_SOLUTION, IMG_MENU_BUTTON_PLAY_SOLUTION_ACTIVE,
9842     &menu.main.button.play_solution, NULL,
9843     SCREEN_CTRL_ID_PLAY_SOLUTION,
9844     SCREEN_MASK_MAIN_HAS_SOLUTION,
9845     GD_EVENT_RELEASED,
9846     FALSE, "play solution tape"
9847   },
9848   {
9849     IMG_MENU_BUTTON_SWITCH_ECS_AGA, IMG_MENU_BUTTON_SWITCH_ECS_AGA_ACTIVE,
9850     &menu.main.button.switch_ecs_aga, &setup.prefer_aga_graphics,
9851     SCREEN_CTRL_ID_SWITCH_ECS_AGA,
9852     SCREEN_MASK_MAIN,
9853     GD_EVENT_RELEASED | GD_EVENT_OFF_BORDERS,
9854     FALSE, "switch ECS/AGA chipset"
9855   },
9856   {
9857     IMG_MENU_BUTTON_TOUCH_BACK, IMG_MENU_BUTTON_TOUCH_BACK,
9858     &menu.setup.button.touch_back, NULL,
9859     SCREEN_CTRL_ID_TOUCH_PREV_PAGE,
9860     SCREEN_MASK_TOUCH,
9861     GD_EVENT_RELEASED,
9862     TRUE, "previous page"
9863   },
9864   {
9865     IMG_MENU_BUTTON_TOUCH_NEXT, IMG_MENU_BUTTON_TOUCH_NEXT,
9866     &menu.setup.button.touch_next, NULL,
9867     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE,
9868     SCREEN_MASK_TOUCH,
9869     GD_EVENT_RELEASED,
9870     TRUE, "next page"
9871   },
9872   {
9873     IMG_MENU_BUTTON_TOUCH_BACK2, IMG_MENU_BUTTON_TOUCH_BACK2,
9874     &menu.setup.button.touch_back2, NULL,
9875     SCREEN_CTRL_ID_TOUCH_PREV_PAGE2,
9876     SCREEN_MASK_TOUCH2,
9877     GD_EVENT_RELEASED,
9878     TRUE, "previous page"
9879   },
9880   {
9881     IMG_MENU_BUTTON_TOUCH_NEXT2, IMG_MENU_BUTTON_TOUCH_NEXT2,
9882     &menu.setup.button.touch_next2, NULL,
9883     SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2,
9884     SCREEN_MASK_TOUCH2,
9885     GD_EVENT_RELEASED,
9886     TRUE, "next page"
9887   },
9888 };
9889
9890 static struct
9891 {
9892   int gfx_unpressed, gfx_pressed;
9893   int x, y;
9894   int gadget_id;
9895   char *infotext;
9896 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
9897 {
9898   {
9899     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
9900     -1, -1,     // these values are not constant, but can change at runtime
9901     SCREEN_CTRL_ID_SCROLL_UP,
9902     "scroll up"
9903   },
9904   {
9905     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
9906     -1, -1,     // these values are not constant, but can change at runtime
9907     SCREEN_CTRL_ID_SCROLL_DOWN,
9908     "scroll down"
9909   }
9910 };
9911
9912 static struct
9913 {
9914   int gfx_unpressed, gfx_pressed;
9915   int x, y;
9916   int width, height;
9917   int type;
9918   int gadget_id;
9919   char *infotext;
9920 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
9921 {
9922   {
9923     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
9924     -1, -1,     // these values are not constant, but can change at runtime
9925     -1, -1,     // these values are not constant, but can change at runtime
9926     GD_TYPE_SCROLLBAR_VERTICAL,
9927     SCREEN_CTRL_ID_SCROLL_VERTICAL,
9928     "scroll level series vertically"
9929   }
9930 };
9931
9932 static struct
9933 {
9934   int graphic;
9935   int gadget_id;
9936   int x, y;
9937   int size;
9938   char *value;
9939   char *infotext;
9940 } textinput_info[NUM_SCREEN_TEXTINPUT] =
9941 {
9942   {
9943     IMG_SETUP_INPUT_TEXT,
9944     SCREEN_CTRL_ID_NETWORK_SERVER,
9945     -1, -1,     // these values are not constant, but can change at runtime
9946     MAX_SETUP_TEXT_INPUT_LEN,
9947     network_server_hostname,
9948     "Network Server Hostname / IP"
9949   },
9950 };
9951
9952 static void CreateScreenMenubuttons(void)
9953 {
9954   struct GadgetInfo *gi;
9955   unsigned int event_mask;
9956   int i;
9957
9958   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
9959   {
9960     struct MenuPosInfo *pos = menubutton_info[i].pos;
9961     int screen_mask = menubutton_info[i].screen_mask;
9962     boolean is_touch_button = menubutton_info[i].is_touch_button;
9963     boolean is_check_button = menubutton_info[i].check_value != NULL;
9964     boolean is_score_button = (screen_mask == SCREEN_MASK_SCORES);
9965     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
9966     int gfx_unpressed, gfx_pressed;
9967     int x, y, width, height;
9968     int gd_x1, gd_x2, gd_y1, gd_y2;
9969     int gd_x1a, gd_x2a, gd_y1a, gd_y2a;
9970     int id = menubutton_info[i].gadget_id;
9971     int type = GD_TYPE_NORMAL_BUTTON;
9972     boolean checked = FALSE;
9973
9974     event_mask = menubutton_info[i].event_mask;
9975
9976     x = (is_touch_button ? pos->x : mSX + GDI_ACTIVE_POS(pos->x));
9977     y = (is_touch_button ? pos->y : mSY + GDI_ACTIVE_POS(pos->y));
9978
9979     width  = graphic_info[menubutton_info[i].gfx_pressed].width;
9980     height = graphic_info[menubutton_info[i].gfx_pressed].height;
9981
9982     gfx_unpressed = menubutton_info[i].gfx_unpressed;
9983     gfx_pressed   = menubutton_info[i].gfx_pressed;
9984     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
9985     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
9986     gd_x1 = graphic_info[gfx_unpressed].src_x;
9987     gd_y1 = graphic_info[gfx_unpressed].src_y;
9988     gd_x2 = graphic_info[gfx_pressed].src_x;
9989     gd_y2 = graphic_info[gfx_pressed].src_y;
9990     gd_x1a = gd_x1;
9991     gd_y1a = gd_y1;
9992     gd_x2a = gd_x2;
9993     gd_y2a = gd_y2;
9994
9995     if (is_touch_button)
9996     {
9997       gd_x2 += graphic_info[gfx_pressed].pressed_xoffset;
9998       gd_y2 += graphic_info[gfx_pressed].pressed_yoffset;
9999     }
10000
10001     if (is_check_button)
10002     {
10003       gd_x1a += graphic_info[gfx_unpressed].active_xoffset;
10004       gd_y1a += graphic_info[gfx_unpressed].active_yoffset;
10005       gd_x2a += graphic_info[gfx_pressed].active_xoffset;
10006       gd_y2a += graphic_info[gfx_pressed].active_yoffset;
10007
10008       type = GD_TYPE_CHECK_BUTTON;
10009       checked = *menubutton_info[i].check_value;
10010     }
10011
10012     if (is_score_button)
10013     {
10014       // if x/y set to -1, dynamically place buttons next to title text
10015       int title_width = getTextWidth(INFOTEXT_SCORE_ENTRY, FONT_TITLE_1);
10016
10017       if (pos->x == -1)
10018         x = (id == SCREEN_CTRL_ID_PREV_LEVEL2 ?
10019              SX + (SXSIZE - title_width) / 2 - width * 3 / 2 :
10020              id == SCREEN_CTRL_ID_NEXT_LEVEL2 ?
10021              SX + (SXSIZE + title_width) / 2 + width / 2 : 0);
10022
10023       if (pos->y == -1)
10024         y = mSY + MENU_TITLE1_YPOS;
10025     }
10026
10027     gi = CreateGadget(GDI_CUSTOM_ID, id,
10028                       GDI_CUSTOM_TYPE_ID, i,
10029                       GDI_IMAGE_ID, gfx_unpressed,
10030                       GDI_INFO_TEXT, menubutton_info[i].infotext,
10031                       GDI_X, x,
10032                       GDI_Y, y,
10033                       GDI_WIDTH, width,
10034                       GDI_HEIGHT, height,
10035                       GDI_TYPE, type,
10036                       GDI_STATE, GD_BUTTON_UNPRESSED,
10037                       GDI_CHECKED, checked,
10038                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10039                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10040                       GDI_ALT_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1a, gd_y1a,
10041                       GDI_ALT_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2a, gd_y2a,
10042                       GDI_DIRECT_DRAW, FALSE,
10043                       GDI_OVERLAY_TOUCH_BUTTON, is_touch_button,
10044                       GDI_EVENT_MASK, event_mask,
10045                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10046                       GDI_END);
10047
10048     if (gi == NULL)
10049       Fail("cannot create gadget");
10050
10051     screen_gadget[id] = gi;
10052   }
10053 }
10054
10055 static void CreateScreenScrollbuttons(void)
10056 {
10057   struct GadgetInfo *gi;
10058   unsigned int event_mask;
10059   int i;
10060
10061   // these values are not constant, but can change at runtime
10062   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
10063   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
10064   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
10065   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
10066
10067   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10068   {
10069     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10070     int gfx_unpressed, gfx_pressed;
10071     int x, y, width, height;
10072     int gd_x1, gd_x2, gd_y1, gd_y2;
10073     int id = scrollbutton_info[i].gadget_id;
10074
10075     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
10076
10077     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
10078     y = mSY + scrollbutton_info[i].y;
10079     width = SC_SCROLLBUTTON_XSIZE;
10080     height = SC_SCROLLBUTTON_YSIZE;
10081
10082     // correct scrollbar position if placed outside menu (playfield) area
10083     if (x > SX + SC_SCROLL_UP_XPOS)
10084       x = SX + SC_SCROLL_UP_XPOS;
10085
10086     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
10087       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
10088                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
10089
10090     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
10091     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
10092     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10093     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10094     gd_x1 = graphic_info[gfx_unpressed].src_x;
10095     gd_y1 = graphic_info[gfx_unpressed].src_y;
10096     gd_x2 = graphic_info[gfx_pressed].src_x;
10097     gd_y2 = graphic_info[gfx_pressed].src_y;
10098
10099     gi = CreateGadget(GDI_CUSTOM_ID, id,
10100                       GDI_CUSTOM_TYPE_ID, i,
10101                       GDI_IMAGE_ID, gfx_unpressed,
10102                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
10103                       GDI_X, x,
10104                       GDI_Y, y,
10105                       GDI_WIDTH, width,
10106                       GDI_HEIGHT, height,
10107                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
10108                       GDI_STATE, GD_BUTTON_UNPRESSED,
10109                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10110                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10111                       GDI_DIRECT_DRAW, FALSE,
10112                       GDI_EVENT_MASK, event_mask,
10113                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10114                       GDI_END);
10115
10116     if (gi == NULL)
10117       Fail("cannot create gadget");
10118
10119     screen_gadget[id] = gi;
10120   }
10121 }
10122
10123 static void CreateScreenScrollbars(void)
10124 {
10125   int i;
10126
10127   // these values are not constant, but can change at runtime
10128   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
10129   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
10130   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
10131   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
10132
10133   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10134   {
10135     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
10136     int gfx_unpressed, gfx_pressed;
10137     int x, y, width, height;
10138     int gd_x1, gd_x2, gd_y1, gd_y2;
10139     struct GadgetInfo *gi;
10140     int items_max, items_visible, item_position;
10141     unsigned int event_mask;
10142     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
10143     int id = scrollbar_info[i].gadget_id;
10144
10145     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
10146
10147     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
10148     y = mSY + scrollbar_info[i].y;
10149     width  = scrollbar_info[i].width;
10150     height = scrollbar_info[i].height;
10151
10152     // correct scrollbar position if placed outside menu (playfield) area
10153     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
10154       x = SX + SC_SCROLL_VERTICAL_XPOS;
10155
10156     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
10157       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
10158
10159     items_max = num_page_entries;
10160     items_visible = num_page_entries;
10161     item_position = 0;
10162
10163     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
10164     gfx_pressed   = scrollbar_info[i].gfx_pressed;
10165     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
10166     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
10167     gd_x1 = graphic_info[gfx_unpressed].src_x;
10168     gd_y1 = graphic_info[gfx_unpressed].src_y;
10169     gd_x2 = graphic_info[gfx_pressed].src_x;
10170     gd_y2 = graphic_info[gfx_pressed].src_y;
10171
10172     gi = CreateGadget(GDI_CUSTOM_ID, id,
10173                       GDI_CUSTOM_TYPE_ID, i,
10174                       GDI_IMAGE_ID, gfx_unpressed,
10175                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
10176                       GDI_X, x,
10177                       GDI_Y, y,
10178                       GDI_WIDTH, width,
10179                       GDI_HEIGHT, height,
10180                       GDI_TYPE, scrollbar_info[i].type,
10181                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
10182                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
10183                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
10184                       GDI_WHEEL_AREA_X, SX,
10185                       GDI_WHEEL_AREA_Y, SY,
10186                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
10187                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
10188                       GDI_STATE, GD_BUTTON_UNPRESSED,
10189                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
10190                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
10191                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
10192                       GDI_DIRECT_DRAW, FALSE,
10193                       GDI_EVENT_MASK, event_mask,
10194                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10195                       GDI_END);
10196
10197     if (gi == NULL)
10198       Fail("cannot create gadget");
10199
10200     screen_gadget[id] = gi;
10201   }
10202 }
10203
10204 static void CreateScreenTextInputGadgets(void)
10205 {
10206   int i;
10207
10208   for (i = 0; i < NUM_SCREEN_TEXTINPUT; i++)
10209   {
10210     int graphic = textinput_info[i].graphic;
10211     struct GraphicInfo *gd = &graphic_info[graphic];
10212     int gd_x1 = gd->src_x;
10213     int gd_y1 = gd->src_y;
10214     int gd_x2 = gd->src_x + gd->active_xoffset;
10215     int gd_y2 = gd->src_y + gd->active_yoffset;
10216     struct GadgetInfo *gi;
10217     unsigned int event_mask;
10218     int id = textinput_info[i].gadget_id;
10219     int x = textinput_info[i].x;
10220     int y = textinput_info[i].y;
10221
10222     event_mask = GD_EVENT_TEXT_RETURN | GD_EVENT_TEXT_LEAVING;
10223
10224     gi = CreateGadget(GDI_CUSTOM_ID, id,
10225                       GDI_CUSTOM_TYPE_ID, i,
10226                       GDI_INFO_TEXT, textinput_info[i].infotext,
10227                       GDI_X, SX + x,
10228                       GDI_Y, SY + y,
10229                       GDI_TYPE, GD_TYPE_TEXT_INPUT_ALPHANUMERIC,
10230                       GDI_TEXT_VALUE, textinput_info[i].value,
10231                       GDI_TEXT_SIZE, textinput_info[i].size,
10232                       GDI_TEXT_FONT, getSetupValueFont(TYPE_STRING, NULL),
10233                       GDI_TEXT_FONT_ACTIVE, FONT_TEXT_1,
10234                       GDI_DESIGN_UNPRESSED, gd->bitmap, gd_x1, gd_y1,
10235                       GDI_DESIGN_PRESSED, gd->bitmap, gd_x2, gd_y2,
10236                       GDI_BORDER_SIZE, gd->border_size, gd->border_size,
10237                       GDI_DESIGN_WIDTH, gd->width,
10238                       GDI_EVENT_MASK, event_mask,
10239                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
10240                       GDI_CALLBACK_ACTION_ALWAYS, TRUE,
10241                       GDI_END);
10242
10243     if (gi == NULL)
10244       Fail("cannot create gadget");
10245
10246     screen_gadget[id] = gi;
10247   }
10248 }
10249
10250 void CreateScreenGadgets(void)
10251 {
10252   CreateScreenMenubuttons();
10253
10254   CreateScreenScrollbuttons();
10255   CreateScreenScrollbars();
10256
10257   CreateScreenTextInputGadgets();
10258 }
10259
10260 void FreeScreenGadgets(void)
10261 {
10262   int i;
10263
10264   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
10265     FreeGadget(screen_gadget[i]);
10266 }
10267
10268 static void RedrawScreenMenuGadgets(int screen_mask)
10269 {
10270   int i;
10271
10272   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10273     if (screen_mask & menubutton_info[i].screen_mask)
10274       RedrawGadget(screen_gadget[menubutton_info[i].gadget_id]);
10275 }
10276
10277 static void MapScreenMenuGadgets(int screen_mask)
10278 {
10279   int i;
10280
10281   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10282     if (screen_mask & menubutton_info[i].screen_mask)
10283       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10284 }
10285
10286 static void UnmapScreenMenuGadgets(int screen_mask)
10287 {
10288   int i;
10289
10290   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
10291   {
10292     if (screen_mask & menubutton_info[i].screen_mask)
10293     {
10294       UnmapGadget(screen_gadget[menubutton_info[i].gadget_id]);
10295
10296       if (screen_mask & SCREEN_MASK_MAIN_HAS_SOLUTION)
10297         DrawBackground(screen_gadget[menubutton_info[i].gadget_id]->x,
10298                        screen_gadget[menubutton_info[i].gadget_id]->y,
10299                        screen_gadget[menubutton_info[i].gadget_id]->width,
10300                        screen_gadget[menubutton_info[i].gadget_id]->height);
10301     }
10302   }
10303 }
10304
10305 static void UpdateScreenMenuGadgets(int screen_mask, boolean map_gadgets)
10306 {
10307   if (map_gadgets)
10308     MapScreenMenuGadgets(screen_mask);
10309   else
10310     UnmapScreenMenuGadgets(screen_mask);
10311 }
10312
10313 static void MapScreenGadgets(int num_entries)
10314 {
10315   int i;
10316
10317   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
10318     return;
10319
10320   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10321     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10322
10323   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10324     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10325 }
10326
10327 static void UnmapScreenGadgets()
10328 {
10329   int i;
10330
10331   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
10332     UnmapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
10333
10334   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
10335     UnmapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
10336 }
10337
10338 static void MapScreenTreeGadgets(TreeInfo *ti)
10339 {
10340   MapScreenGadgets(numTreeInfoInGroup(ti));
10341 }
10342
10343 static void UnmapScreenTreeGadgets(void)
10344 {
10345   UnmapScreenGadgets();
10346 }
10347
10348 static void HandleScreenGadgets(struct GadgetInfo *gi)
10349 {
10350   int id = gi->custom_id;
10351   int button = gi->event.button;
10352   int step = (button == MB_LEFTBUTTON   ? 1 :
10353               button == MB_MIDDLEBUTTON ? 5 :
10354               button == MB_RIGHTBUTTON  ? 10 : 1);
10355
10356   switch (id)
10357   {
10358     case SCREEN_CTRL_ID_PREV_LEVEL:
10359       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
10360       break;
10361
10362     case SCREEN_CTRL_ID_NEXT_LEVEL:
10363       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
10364       break;
10365
10366     case SCREEN_CTRL_ID_PREV_LEVEL2:
10367       HandleHallOfFame_SelectLevel(step, -1);
10368       break;
10369
10370     case SCREEN_CTRL_ID_NEXT_LEVEL2:
10371       HandleHallOfFame_SelectLevel(step, +1);
10372       break;
10373
10374     case SCREEN_CTRL_ID_FIRST_LEVEL:
10375       HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
10376       break;
10377
10378     case SCREEN_CTRL_ID_LAST_LEVEL:
10379       HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
10380       break;
10381
10382     case SCREEN_CTRL_ID_LEVEL_NUMBER:
10383       CloseDoor(DOOR_CLOSE_2);
10384       SetGameStatus(GAME_MODE_LEVELNR);
10385       DrawChooseLevelNr();
10386       break;
10387
10388     case SCREEN_CTRL_ID_PREV_PLAYER:
10389       HandleSetupScreen_Input_Player(step, -1);
10390       break;
10391
10392     case SCREEN_CTRL_ID_NEXT_PLAYER:
10393       HandleSetupScreen_Input_Player(step, +1);
10394       break;
10395
10396     case SCREEN_CTRL_ID_INSERT_SOLUTION:
10397       InsertSolutionTape();
10398       break;
10399
10400     case SCREEN_CTRL_ID_PLAY_SOLUTION:
10401       PlaySolutionTape();
10402       break;
10403
10404     case SCREEN_CTRL_ID_SWITCH_ECS_AGA:
10405       setup.prefer_aga_graphics = !setup.prefer_aga_graphics;
10406       DrawMainMenu();
10407       break;
10408
10409     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE:
10410     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE:
10411     case SCREEN_CTRL_ID_TOUCH_PREV_PAGE2:
10412     case SCREEN_CTRL_ID_TOUCH_NEXT_PAGE2:
10413       PushUserEvent(USEREVENT_GADGET_PRESSED, id, 0);
10414       break;
10415
10416     case SCREEN_CTRL_ID_SCROLL_UP:
10417       if (game_status == GAME_MODE_NAMES)
10418         HandleChoosePlayerName(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10419       else if (game_status == GAME_MODE_LEVELS)
10420         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10421       else if (game_status == GAME_MODE_LEVELNR)
10422         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10423       else if (game_status == GAME_MODE_SETUP)
10424         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10425       else if (game_status == GAME_MODE_INFO)
10426         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10427       else if (game_status == GAME_MODE_SCORES)
10428         HandleHallOfFame(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
10429       break;
10430
10431     case SCREEN_CTRL_ID_SCROLL_DOWN:
10432       if (game_status == GAME_MODE_NAMES)
10433         HandleChoosePlayerName(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10434       else if (game_status == GAME_MODE_LEVELS)
10435         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10436       else if (game_status == GAME_MODE_LEVELNR)
10437         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10438       else if (game_status == GAME_MODE_SETUP)
10439         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10440       else if (game_status == GAME_MODE_INFO)
10441         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10442       else if (game_status == GAME_MODE_SCORES)
10443         HandleHallOfFame(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
10444       break;
10445
10446     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
10447       if (game_status == GAME_MODE_NAMES)
10448         HandleChoosePlayerName(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10449       else if (game_status == GAME_MODE_LEVELS)
10450         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10451       else if (game_status == GAME_MODE_LEVELNR)
10452         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
10453       else if (game_status == GAME_MODE_SETUP)
10454         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10455       else if (game_status == GAME_MODE_INFO)
10456         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10457       else if (game_status == GAME_MODE_SCORES)
10458         HandleHallOfFame(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
10459       break;
10460
10461     case SCREEN_CTRL_ID_NETWORK_SERVER:
10462     {
10463       if (!strEqual(gi->textinput.value, ""))
10464       {
10465         setString(&setup.network_server_hostname, gi->textinput.value);
10466
10467         network.server_host = setup.network_server_hostname;
10468       }
10469       else
10470       {
10471         setString(&setup.network_server_hostname, STR_NETWORK_AUTO_DETECT);
10472
10473         network.server_host = NULL;
10474       }
10475
10476       if (strEqual(network.server_host, STR_NETWORK_AUTO_DETECT))
10477         network.server_host = NULL;
10478
10479       execSetupGame_setNetworkServerText();
10480
10481       DrawSetupScreen();
10482
10483       break;
10484     }
10485
10486     default:
10487       break;
10488   }
10489 }
10490
10491 void DumpScreenIdentifiers(void)
10492 {
10493   int i;
10494
10495   Print("Active screen elements on current screen:\n");
10496
10497   for (i = 0; main_controls[i].nr != -1; i++)
10498   {
10499     struct MainControlInfo *mci = &main_controls[i];
10500
10501     if (mci->button_graphic != -1)
10502     {
10503       char *token = getTokenFromImageID(mci->button_graphic);
10504
10505       Print("- '%s'\n", token);
10506     }
10507   }
10508
10509   Print("Done.\n");
10510 }
10511
10512 boolean DoScreenAction(int image_id)
10513 {
10514   int i;
10515
10516   if (game_status != GAME_MODE_MAIN)
10517     return FALSE;
10518
10519   for (i = 0; main_controls[i].nr != -1; i++)
10520   {
10521     struct MainControlInfo *mci = &main_controls[i];
10522     struct MenuPosInfo *pos = mci->pos_button;
10523
10524     if (mci->button_graphic == image_id)
10525     {
10526       int x = mSX + pos->x;
10527       int y = mSY + pos->y;
10528
10529       HandleMainMenu(x, y, 0, 0, MB_MENU_CHOICE);
10530
10531       return TRUE;
10532     }
10533   }
10534
10535   return FALSE;
10536 }
10537
10538 void DrawScreenAfterAddingSet(char *tree_subdir_new, int tree_type)
10539 {
10540   // get tree info node of newly added level or artwork set
10541   TreeInfo *tree_node_first = TREE_FIRST_NODE(tree_type);
10542   TreeInfo *tree_node_new = getTreeInfoFromIdentifier(tree_node_first,
10543                                                       tree_subdir_new);
10544   if (tree_node_new == NULL)    // should not happen
10545     return;
10546
10547   // if request dialog is active, do nothing
10548   if (game.request_active)
10549     return;
10550
10551   if (game_status == GAME_MODE_MAIN &&
10552       tree_type == TREE_TYPE_LEVEL_DIR)
10553   {
10554     // when adding new level set in main menu, select it as current level set
10555
10556     // change current level set to newly added level set from zip file
10557     leveldir_current = tree_node_new;
10558
10559     // change current level number to first level of newly added level set
10560     level_nr = leveldir_current->first_level;
10561
10562     // redraw screen to reflect changed level set
10563     DrawMainMenu();
10564
10565     // save this level set and level number as last selected level set
10566     SaveLevelSetup_LastSeries();
10567     SaveLevelSetup_SeriesInfo();
10568   }
10569   else if (game_status == GAME_MODE_LEVELS &&
10570            tree_type == TREE_TYPE_LEVEL_DIR)
10571   {
10572     // when adding new level set in level set menu, set cursor and update screen
10573
10574     leveldir_current = tree_node_new;
10575
10576     DrawChooseTree(&leveldir_current);
10577   }
10578   else if (game_status == GAME_MODE_SETUP)
10579   {
10580     // when adding new artwork set in setup menu, set cursor and update screen
10581
10582     if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS &&
10583         tree_type == TREE_TYPE_GRAPHICS_DIR)
10584     {
10585       artwork.gfx_current = tree_node_new;
10586
10587       DrawChooseTree(&artwork.gfx_current);
10588     }
10589     else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS &&
10590              tree_type == TREE_TYPE_SOUNDS_DIR)
10591     {
10592       artwork.snd_current = tree_node_new;
10593
10594       DrawChooseTree(&artwork.snd_current);
10595     }
10596     else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC &&
10597              tree_type == TREE_TYPE_MUSIC_DIR)
10598     {
10599       artwork.mus_current = tree_node_new;
10600
10601       DrawChooseTree(&artwork.mus_current);
10602     }
10603   }
10604 }
10605
10606 static int UploadTapes(void)
10607 {
10608   SetGameStatus(GAME_MODE_LOADING);
10609
10610   FadeSetEnterScreen();
10611   FadeOut(REDRAW_ALL);
10612
10613   ClearRectangle(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
10614
10615   FadeIn(REDRAW_ALL);
10616
10617   DrawInitTextHead("Uploading tapes");
10618
10619   global.autoplay_mode = AUTOPLAY_MODE_UPLOAD;
10620   global.autoplay_leveldir = "ALL";
10621   global.autoplay_all = TRUE;
10622
10623   int num_tapes_uploaded = AutoPlayTapes();
10624
10625   global.autoplay_mode = AUTOPLAY_MODE_NONE;
10626   global.autoplay_leveldir = NULL;
10627   global.autoplay_all = FALSE;
10628
10629   SetGameStatus(GAME_MODE_MAIN);
10630
10631   DrawMainMenu();
10632
10633   return num_tapes_uploaded;
10634 }
10635
10636 static boolean OfferUploadTapes(void)
10637 {
10638   if (!Request(setup.has_remaining_tapes ?
10639                "Upload missing tapes to the high score server now?" :
10640                "Upload all your tapes to the high score server now?", REQ_ASK))
10641     return FALSE;
10642
10643   int num_tapes_uploaded = UploadTapes();
10644   char message[100];
10645
10646   if (num_tapes_uploaded < 0)
10647   {
10648     num_tapes_uploaded = -num_tapes_uploaded - 1;
10649
10650     if (num_tapes_uploaded == 0)
10651       sprintf(message, "Upload failed! No tapes uploaded!");
10652     else if (num_tapes_uploaded == 1)
10653       sprintf(message, "Upload failed! Only 1 tape uploaded!");
10654     else
10655       sprintf(message, "Upload failed! Only %d tapes uploaded!",
10656               num_tapes_uploaded);
10657
10658     Request(message, REQ_CONFIRM);
10659
10660     // if uploading tapes failed, add tape upload entry to setup menu
10661     setup.provide_uploading_tapes = TRUE;
10662     setup.has_remaining_tapes = TRUE;
10663
10664     SaveSetup_ServerSetup();
10665
10666     return FALSE;
10667   }
10668
10669   if (num_tapes_uploaded == 0)
10670     sprintf(message, "No tapes uploaded!");
10671   else if (num_tapes_uploaded == 1)
10672     sprintf(message, "1 tape uploaded!");
10673   else
10674     sprintf(message, "%d tapes uploaded!", num_tapes_uploaded);
10675
10676   Request(message, REQ_CONFIRM);
10677
10678   if (num_tapes_uploaded > 0)
10679     Request("New scores will be visible after a few minutes!", REQ_CONFIRM);
10680
10681   // after all tapes have been uploaded, remove entry from setup menu
10682   setup.provide_uploading_tapes = FALSE;
10683   setup.has_remaining_tapes = FALSE;
10684
10685   SaveSetup_ServerSetup();
10686
10687   return TRUE;
10688 }
10689
10690 static void CheckUploadTapes(void)
10691 {
10692   if (!setup.ask_for_uploading_tapes)
10693     return;
10694
10695   // after asking for uploading tapes, do not ask again
10696   setup.ask_for_uploading_tapes = FALSE;
10697   setup.ask_for_remaining_tapes = FALSE;
10698
10699   if (directoryExists(getTapeDir(NULL)))
10700   {
10701     boolean tapes_uploaded = OfferUploadTapes();
10702
10703     if (!tapes_uploaded)
10704     {
10705       Request(setup.has_remaining_tapes ?
10706               "You can upload missing tapes from the setup menu later!" :
10707               "You can upload your tapes from the setup menu later!",
10708               REQ_CONFIRM);
10709     }
10710   }
10711   else
10712   {
10713     // if tapes directory does not exist yet, never offer uploading all tapes
10714     setup.provide_uploading_tapes = FALSE;
10715   }
10716
10717   SaveSetup_ServerSetup();
10718 }
10719
10720 static void UpgradePlayerUUID(void)
10721 {
10722   ApiResetUUIDAsThread(getUUID());
10723 }
10724
10725 static void CheckUpgradePlayerUUID(void)
10726 {
10727   if (setup.player_version > 1)
10728     return;
10729
10730   UpgradePlayerUUID();
10731 }
10732
10733 void CheckApiServerTasks(void)
10734 {
10735   // check if the player's UUID has to be upgraded
10736   CheckUpgradePlayerUUID();
10737
10738   // check if there are any tapes to be uploaded
10739   CheckUploadTapes();
10740 }