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