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