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