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