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