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