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