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