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