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