renamed function 'NextEvent' to 'WaitEvent'
[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 //                  http://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_EDITOR               2
48 #define SETUP_MODE_GRAPHICS             3
49 #define SETUP_MODE_SOUND                4
50 #define SETUP_MODE_ARTWORK              5
51 #define SETUP_MODE_INPUT                6
52 #define SETUP_MODE_TOUCH                7
53 #define SETUP_MODE_SHORTCUTS            8
54 #define SETUP_MODE_SHORTCUTS_1          9
55 #define SETUP_MODE_SHORTCUTS_2          10
56 #define SETUP_MODE_SHORTCUTS_3          11
57 #define SETUP_MODE_SHORTCUTS_4          12
58 #define SETUP_MODE_SHORTCUTS_5          13
59
60 /* sub-screens on the setup screen (generic) */
61 #define SETUP_MODE_CHOOSE_ARTWORK       14
62 #define SETUP_MODE_CHOOSE_OTHER         15
63
64 /* sub-screens on the setup screen (specific) */
65 #define SETUP_MODE_CHOOSE_GAME_SPEED    16
66 #define SETUP_MODE_CHOOSE_SCROLL_DELAY  17
67 #define SETUP_MODE_CHOOSE_SNAPSHOT_MODE 18
68 #define SETUP_MODE_CHOOSE_WINDOW_SIZE   19
69 #define SETUP_MODE_CHOOSE_SCALING_TYPE  20
70 #define SETUP_MODE_CHOOSE_RENDERING     21
71 #define SETUP_MODE_CHOOSE_GRAPHICS      22
72 #define SETUP_MODE_CHOOSE_SOUNDS        23
73 #define SETUP_MODE_CHOOSE_MUSIC         24
74 #define SETUP_MODE_CHOOSE_VOLUME_SIMPLE 25
75 #define SETUP_MODE_CHOOSE_VOLUME_LOOPS  26
76 #define SETUP_MODE_CHOOSE_VOLUME_MUSIC  27
77 #define SETUP_MODE_CHOOSE_TOUCH_CONTROL 28
78 #define SETUP_MODE_CHOOSE_MOVE_DISTANCE 29
79 #define SETUP_MODE_CHOOSE_DROP_DISTANCE 30
80
81 #define MAX_SETUP_MODES                 31
82
83 #define MAX_MENU_MODES                  MAX(MAX_INFO_MODES, MAX_SETUP_MODES)
84
85 /* for input setup functions */
86 #define SETUPINPUT_SCREEN_POS_START     0
87 #define SETUPINPUT_SCREEN_POS_END       (SCR_FIELDY - 4)
88 #define SETUPINPUT_SCREEN_POS_EMPTY1    (SETUPINPUT_SCREEN_POS_START + 3)
89 #define SETUPINPUT_SCREEN_POS_EMPTY2    (SETUPINPUT_SCREEN_POS_END - 1)
90
91 /* for various menu stuff  */
92 #define MENU_SCREEN_START_XPOS          1
93 #define MENU_SCREEN_START_YPOS          2
94 #define MENU_SCREEN_VALUE_XPOS          (SCR_FIELDX - 3)
95 #define MENU_SCREEN_MAX_XPOS            (SCR_FIELDX - 1)
96 #define MENU_TITLE1_YPOS                8
97 #define MENU_TITLE2_YPOS                46
98 #define MENU_SCREEN_INFO_XSTART         16
99 #define MENU_SCREEN_INFO_YSTART1        100
100 #define MENU_SCREEN_INFO_YSTART2        128
101 #define MENU_SCREEN_INFO_YSTEP          (TILEY + 4)
102 #define MENU_SCREEN_INFO_YBOTTOM        (SYSIZE - 20)
103 #define MENU_SCREEN_INFO_YSIZE          (MENU_SCREEN_INFO_YBOTTOM -     \
104                                          MENU_SCREEN_INFO_YSTART2 -     \
105                                          TILEY / 2)
106 #define MAX_INFO_ELEMENTS_ON_SCREEN     128
107 #define STD_INFO_ELEMENTS_ON_SCREEN     (MENU_SCREEN_INFO_YSIZE /       \
108                                          MENU_SCREEN_INFO_YSTEP)
109 #define NUM_INFO_ELEMENTS_FROM_CONF     \
110   (menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] > 0 ?             \
111    menu.list_size_info[GFX_SPECIAL_ARG_INFO_ELEMENTS] :                 \
112    MAX_MENU_ENTRIES_ON_SCREEN)
113 #define NUM_INFO_ELEMENTS_ON_SCREEN     MIN(MIN(STD_INFO_ELEMENTS_ON_SCREEN, \
114                                                 MAX_INFO_ELEMENTS_ON_SCREEN), \
115                                             NUM_INFO_ELEMENTS_FROM_CONF)
116 #define MAX_MENU_ENTRIES_ON_SCREEN      (SCR_FIELDY - MENU_SCREEN_START_YPOS)
117 #define MAX_MENU_TEXT_LENGTH_BIG        13
118 #define MAX_MENU_TEXT_LENGTH_MEDIUM     (MAX_MENU_TEXT_LENGTH_BIG * 2)
119
120 /* buttons and scrollbars identifiers */
121 #define SCREEN_CTRL_ID_PREV_LEVEL       0
122 #define SCREEN_CTRL_ID_NEXT_LEVEL       1
123 #define SCREEN_CTRL_ID_PREV_PLAYER      2
124 #define SCREEN_CTRL_ID_NEXT_PLAYER      3
125 #define SCREEN_CTRL_ID_SCROLL_UP        4
126 #define SCREEN_CTRL_ID_SCROLL_DOWN      5
127 #define SCREEN_CTRL_ID_SCROLL_VERTICAL  6
128
129 #define NUM_SCREEN_GADGETS              7
130
131 #define NUM_SCREEN_MENUBUTTONS          4
132 #define NUM_SCREEN_SCROLLBUTTONS        2
133 #define NUM_SCREEN_SCROLLBARS           1
134
135 #define SCREEN_MASK_MAIN                (1 << 0)
136 #define SCREEN_MASK_INPUT               (1 << 1)
137
138 /* graphic position and size values for buttons and scrollbars */
139 #define SC_MENUBUTTON_XSIZE             TILEX
140 #define SC_MENUBUTTON_YSIZE             TILEY
141
142 #define SC_SCROLLBUTTON_XSIZE           TILEX
143 #define SC_SCROLLBUTTON_YSIZE           TILEY
144
145 #define SC_SCROLLBAR_XPOS               (SXSIZE - SC_SCROLLBUTTON_XSIZE)
146
147 #define SC_SCROLL_VERTICAL_XSIZE        SC_SCROLLBUTTON_XSIZE
148 #define SC_SCROLL_VERTICAL_YSIZE        ((MAX_MENU_ENTRIES_ON_SCREEN - 2) * \
149                                          SC_SCROLLBUTTON_YSIZE)
150
151 #define SC_SCROLL_UP_XPOS               SC_SCROLLBAR_XPOS
152 #define SC_SCROLL_UP_YPOS               (2 * SC_SCROLLBUTTON_YSIZE)
153
154 #define SC_SCROLL_VERTICAL_XPOS         SC_SCROLLBAR_XPOS
155 #define SC_SCROLL_VERTICAL_YPOS         (SC_SCROLL_UP_YPOS + \
156                                          SC_SCROLLBUTTON_YSIZE)
157
158 #define SC_SCROLL_DOWN_XPOS             SC_SCROLLBAR_XPOS
159 #define SC_SCROLL_DOWN_YPOS             (SC_SCROLL_VERTICAL_YPOS + \
160                                          SC_SCROLL_VERTICAL_YSIZE)
161
162 #define SC_BORDER_SIZE                  14
163
164
165 /* forward declarations of internal functions */
166 static void HandleScreenGadgets(struct GadgetInfo *);
167 static void HandleSetupScreen_Generic(int, int, int, int, int);
168 static void HandleSetupScreen_Input(int, int, int, int, int);
169 static void CustomizeKeyboard(int);
170 static void ConfigureJoystick(int);
171 static void execSetupGame(void);
172 static void execSetupGraphics(void);
173 static void execSetupSound(void);
174 static void execSetupTouch(void);
175 static void execSetupArtwork(void);
176 static void HandleChooseTree(int, int, int, int, int, TreeInfo **);
177
178 static void DrawChooseLevelSet(void);
179 static void DrawChooseLevelNr(void);
180 static void DrawInfoScreen(void);
181 static void DrawSetupScreen(void);
182
183 static void DrawInfoScreen_NotAvailable(char *, char *);
184 static void DrawInfoScreen_HelpAnim(int, int, boolean);
185 static void DrawInfoScreen_HelpText(int, int, int, int);
186 static void HandleInfoScreen_Main(int, int, int, int, int);
187 static void HandleInfoScreen_TitleScreen(int);
188 static void HandleInfoScreen_Elements(int);
189 static void HandleInfoScreen_Music(int);
190 static void HandleInfoScreen_Credits(int);
191 static void HandleInfoScreen_Program(int);
192 static void HandleInfoScreen_Version(int);
193
194 static void MapScreenMenuGadgets(int);
195 static void MapScreenGadgets(int);
196 static void MapScreenTreeGadgets(TreeInfo *);
197
198 static struct GadgetInfo *screen_gadget[NUM_SCREEN_GADGETS];
199
200 static int info_mode = INFO_MODE_MAIN;
201 static int setup_mode = SETUP_MODE_MAIN;
202
203 static TreeInfo *window_sizes = NULL;
204 static TreeInfo *window_size_current = NULL;
205
206 static TreeInfo *scaling_types = NULL;
207 static TreeInfo *scaling_type_current = NULL;
208
209 static TreeInfo *rendering_modes = NULL;
210 static TreeInfo *rendering_mode_current = NULL;
211
212 static TreeInfo *scroll_delays = NULL;
213 static TreeInfo *scroll_delay_current = NULL;
214
215 static TreeInfo *snapshot_modes = NULL;
216 static TreeInfo *snapshot_mode_current = NULL;
217
218 static TreeInfo *game_speeds = NULL;
219 static TreeInfo *game_speed_current = NULL;
220
221 static TreeInfo *volumes_simple = NULL;
222 static TreeInfo *volume_simple_current = NULL;
223
224 static TreeInfo *volumes_loops = NULL;
225 static TreeInfo *volume_loops_current = NULL;
226
227 static TreeInfo *volumes_music = NULL;
228 static TreeInfo *volume_music_current = NULL;
229
230 static TreeInfo *touch_controls = NULL;
231 static TreeInfo *touch_control_current = NULL;
232
233 static TreeInfo *move_distances = NULL;
234 static TreeInfo *move_distance_current = NULL;
235
236 static TreeInfo *drop_distances = NULL;
237 static TreeInfo *drop_distance_current = NULL;
238
239 static TreeInfo *level_number = NULL;
240 static TreeInfo *level_number_current = NULL;
241
242 static struct
243 {
244   int value;
245   char *text;
246 } window_sizes_list[] =
247 {
248   {     50,     "50 %"                          },
249   {     80,     "80 %"                          },
250   {     90,     "90 %"                          },
251   {     100,    "100 % (Default)"               },
252   {     110,    "110 %"                         },
253   {     120,    "120 %"                         },
254   {     130,    "130 %"                         },
255   {     140,    "140 %"                         },
256   {     150,    "150 %"                         },
257   {     200,    "200 %"                         },
258   {     250,    "250 %"                         },
259   {     300,    "300 %"                         },
260
261   {     -1,     NULL                            },
262 };
263
264 static struct
265 {
266   char *value;
267   char *text;
268 } scaling_types_list[] =
269 {
270   {     SCALING_QUALITY_NEAREST, "None"         },
271   {     SCALING_QUALITY_LINEAR,  "Linear"       },
272   {     SCALING_QUALITY_BEST,    "Anisotropic"  },
273
274   {     NULL,                    NULL           },
275 };
276
277 static struct
278 {
279   char *value;
280   char *text;
281 } rendering_modes_list[] =
282 {
283   {     STR_SPECIAL_RENDERING_OFF,      "Off (May show artifacts, fast)" },
284   {     STR_SPECIAL_RENDERING_BITMAP,   "Bitmap/Texture mode (slower)"   },
285 #if DEBUG
286   // this mode may work under certain conditions, but does not work on Windows
287   {     STR_SPECIAL_RENDERING_TARGET,   "Target Texture mode (slower)"   },
288 #endif
289   {     STR_SPECIAL_RENDERING_DOUBLE,   "Double Texture mode (slower)"   },
290
291   {     NULL,                            NULL                            },
292 };
293
294 static struct
295 {
296   int value;
297   char *text;
298 } game_speeds_list[] =
299 {
300 #if 1
301   {     30,     "Very Slow"                     },
302   {     25,     "Slow"                          },
303   {     20,     "Normal"                        },
304   {     15,     "Fast"                          },
305   {     10,     "Very Fast"                     },
306 #else
307   {     1000,   "1/1s (Extremely Slow)"         },
308   {     500,    "1/2s"                          },
309   {     200,    "1/5s"                          },
310   {     100,    "1/10s"                         },
311   {     50,     "1/20s"                         },
312   {     29,     "1/35s (Original Supaplex)"     },
313   {     25,     "1/40s"                         },
314   {     20,     "1/50s (Normal Speed)"          },
315   {     14,     "1/70s (Maximum Supaplex)"      },
316   {     10,     "1/100s"                        },
317   {     5,      "1/200s"                        },
318   {     2,      "1/500s"                        },
319   {     1,      "1/1000s (Extremely Fast)"      },
320 #endif
321
322   {     -1,     NULL                            },
323 };
324
325 static struct
326 {
327   int value;
328   char *text;
329 } scroll_delays_list[] =
330 {
331   {     0,      "0 Tiles (No Scroll Delay)"     },
332   {     1,      "1 Tile"                        },
333   {     2,      "2 Tiles"                       },
334   {     3,      "3 Tiles (Default)"             },
335   {     4,      "4 Tiles"                       },
336   {     5,      "5 Tiles"                       },
337   {     6,      "6 Tiles"                       },
338   {     7,      "7 Tiles"                       },
339   {     8,      "8 Tiles (Maximum Scroll Delay)"},
340
341   {     -1,     NULL                            },
342 };
343
344 static struct
345 {
346   char *value;
347   char *text;
348 } snapshot_modes_list[] =
349 {
350   {     STR_SNAPSHOT_MODE_OFF,                  "Off"           },
351   {     STR_SNAPSHOT_MODE_EVERY_STEP,           "Every Step"    },
352   {     STR_SNAPSHOT_MODE_EVERY_MOVE,           "Every Move"    },
353   {     STR_SNAPSHOT_MODE_EVERY_COLLECT,        "Every Collect" },
354
355   {     NULL,                                   NULL            },
356 };
357
358 static struct
359 {
360   int value;
361   char *text;
362 } volumes_list[] =
363 {
364   {     0,      "0 %"                           },
365   {     1,      "1 %"                           },
366   {     2,      "2 %"                           },
367   {     5,      "5 %"                           },
368   {     10,     "10 %"                          },
369   {     20,     "20 %"                          },
370   {     30,     "30 %"                          },
371   {     40,     "40 %"                          },
372   {     50,     "50 %"                          },
373   {     60,     "60 %"                          },
374   {     70,     "70 %"                          },
375   {     80,     "80 %"                          },
376   {     90,     "90 %"                          },
377   {     100,    "100 %"                         },
378
379   {     -1,     NULL                            },
380 };
381
382 static struct
383 {
384   char *value;
385   char *text;
386 } touch_controls_list[] =
387 {
388   {     TOUCH_CONTROL_VIRTUAL_BUTTONS,  "Virtual Buttons"       },
389   {     TOUCH_CONTROL_WIPE_GESTURES,    "Wipe Gestures"         },
390   {     TOUCH_CONTROL_FOLLOW_FINGER,    "Follow Finger"         },
391
392   {     NULL,                           NULL                    },
393 };
394
395 static struct
396 {
397   int value;
398   char *text;
399 } distances_list[] =
400 {
401   {     1,      "1 %"                           },
402   {     2,      "2 %"                           },
403   {     3,      "3 %"                           },
404   {     4,      "4 %"                           },
405   {     5,      "5 %"                           },
406   {     10,     "10 %"                          },
407   {     15,     "15 %"                          },
408   {     20,     "20 %"                          },
409   {     25,     "25 %"                          },
410
411   {     -1,     NULL                            },
412 };
413
414 #define DRAW_MODE(s)            ((s) >= GAME_MODE_MAIN &&               \
415                                  (s) <= GAME_MODE_SETUP ? (s) :         \
416                                  (s) == GAME_MODE_PSEUDO_TYPENAME ?     \
417                                  GAME_MODE_MAIN : GAME_MODE_DEFAULT)
418
419 /* (there are no draw offset definitions needed for INFO_MODE_TITLE) */
420 #define DRAW_MODE_INFO(i)       ((i) >= INFO_MODE_ELEMENTS &&           \
421                                  (i) <= INFO_MODE_LEVELSET ? (i) :      \
422                                  INFO_MODE_MAIN)
423
424 #define DRAW_MODE_SETUP(i)      ((i) >= SETUP_MODE_MAIN &&              \
425                                  (i) <= SETUP_MODE_SHORTCUTS_5 ? (i) :  \
426                                  (i) >= SETUP_MODE_CHOOSE_GRAPHICS &&   \
427                                  (i) <= SETUP_MODE_CHOOSE_MUSIC ?       \
428                                  SETUP_MODE_CHOOSE_ARTWORK :            \
429                                  SETUP_MODE_CHOOSE_OTHER)
430
431 #define DRAW_XOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?  \
432                                  menu.draw_xoffset[GAME_MODE_INFO] :    \
433                                  menu.draw_xoffset_info[DRAW_MODE_INFO(i)])
434 #define DRAW_YOFFSET_INFO(i)    (DRAW_MODE_INFO(i) == INFO_MODE_MAIN ?  \
435                                  menu.draw_yoffset[GAME_MODE_INFO] :    \
436                                  menu.draw_yoffset_info[DRAW_MODE_INFO(i)])
437
438 #define DRAW_XOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
439                                  menu.draw_xoffset[GAME_MODE_SETUP] :   \
440                                  menu.draw_xoffset_setup[DRAW_MODE_SETUP(i)])
441 #define DRAW_YOFFSET_SETUP(i)   (DRAW_MODE_SETUP(i) == SETUP_MODE_MAIN ? \
442                                  menu.draw_yoffset[GAME_MODE_SETUP] :   \
443                                  menu.draw_yoffset_setup[DRAW_MODE_SETUP(i)])
444
445 #define DRAW_XOFFSET(s)         ((s) == GAME_MODE_INFO ?                \
446                                  DRAW_XOFFSET_INFO(info_mode) :         \
447                                  (s) == GAME_MODE_SETUP ?               \
448                                  DRAW_XOFFSET_SETUP(setup_mode) :       \
449                                  menu.draw_xoffset[DRAW_MODE(s)])
450 #define DRAW_YOFFSET(s)         ((s) == GAME_MODE_INFO ?                \
451                                  DRAW_YOFFSET_INFO(info_mode) :         \
452                                  (s) == GAME_MODE_SETUP ?               \
453                                  DRAW_YOFFSET_SETUP(setup_mode) :       \
454                                  menu.draw_yoffset[DRAW_MODE(s)])
455
456 #define mSX                     (SX + DRAW_XOFFSET(game_status))
457 #define mSY                     (SY + DRAW_YOFFSET(game_status))
458
459 #define NUM_MENU_ENTRIES_ON_SCREEN (menu.list_size[game_status] > 2 ?   \
460                                     menu.list_size[game_status] :       \
461                                     MAX_MENU_ENTRIES_ON_SCREEN)
462
463 #define IN_VIS_MENU(x, y)       IN_FIELD(x, y, SCR_FIELDX,              \
464                                          NUM_MENU_ENTRIES_ON_SCREEN)
465
466
467 /* title display and control definitions */
468
469 #define MAX_NUM_TITLE_SCREENS   (2 * MAX_NUM_TITLE_IMAGES +             \
470                                  2 * MAX_NUM_TITLE_MESSAGES)
471
472 #define NO_DIRECT_LEVEL_SELECT  (-1)
473
474
475 static int num_title_screens = 0;
476
477 struct TitleControlInfo
478 {
479   boolean is_image;
480   boolean initial;
481   boolean first;
482   int local_nr;
483   int sort_priority;
484 };
485
486 struct TitleControlInfo title_controls[MAX_NUM_TITLE_SCREENS];
487
488 /* main menu display and control definitions */
489
490 #define MAIN_CONTROL_NAME                       0
491 #define MAIN_CONTROL_LEVELS                     1
492 #define MAIN_CONTROL_SCORES                     2
493 #define MAIN_CONTROL_EDITOR                     3
494 #define MAIN_CONTROL_INFO                       4
495 #define MAIN_CONTROL_GAME                       5
496 #define MAIN_CONTROL_SETUP                      6
497 #define MAIN_CONTROL_QUIT                       7
498 #define MAIN_CONTROL_PREV_LEVEL                 8
499 #define MAIN_CONTROL_NEXT_LEVEL                 9
500 #define MAIN_CONTROL_FIRST_LEVEL                10
501 #define MAIN_CONTROL_LAST_LEVEL                 11
502 #define MAIN_CONTROL_LEVEL_NUMBER               12
503 #define MAIN_CONTROL_LEVEL_INFO_1               13
504 #define MAIN_CONTROL_LEVEL_INFO_2               14
505 #define MAIN_CONTROL_LEVEL_NAME                 15
506 #define MAIN_CONTROL_LEVEL_AUTHOR               16
507 #define MAIN_CONTROL_LEVEL_YEAR                 17
508 #define MAIN_CONTROL_LEVEL_IMPORTED_FROM        18
509 #define MAIN_CONTROL_LEVEL_IMPORTED_BY          19
510 #define MAIN_CONTROL_LEVEL_TESTED_BY            20
511 #define MAIN_CONTROL_TITLE_1                    21
512 #define MAIN_CONTROL_TITLE_2                    22
513 #define MAIN_CONTROL_TITLE_3                    23
514
515 static char str_main_text_name[10];
516 static char str_main_text_first_level[10];
517 static char str_main_text_last_level[10];
518 static char str_main_text_level_number[10];
519
520 static char *main_text_name                     = str_main_text_name;
521 static char *main_text_first_level              = str_main_text_first_level;
522 static char *main_text_last_level               = str_main_text_last_level;
523 static char *main_text_level_number             = str_main_text_level_number;
524 static char *main_text_levels                   = "Levelset";
525 static char *main_text_scores                   = "Hall Of Fame";
526 static char *main_text_editor                   = "Level Creator";
527 static char *main_text_info                     = "Info Screen";
528 static char *main_text_game                     = "Start Game";
529 static char *main_text_setup                    = "Setup";
530 static char *main_text_quit                     = "Quit";
531 static char *main_text_level_name               = level.name;
532 static char *main_text_level_author             = level.author;
533 static char *main_text_level_year               = NULL;
534 static char *main_text_level_imported_from      = NULL;
535 static char *main_text_level_imported_by        = NULL;
536 static char *main_text_level_tested_by          = NULL;
537
538 struct MainControlInfo
539 {
540   int nr;
541
542   struct MenuPosInfo *pos_button;
543   int button_graphic;
544
545   struct TextPosInfo *pos_text;
546   char **text;
547
548   struct TextPosInfo *pos_input;
549   char **input;
550 };
551
552 static struct MainControlInfo main_controls[] =
553 {
554   {
555     MAIN_CONTROL_NAME,
556     &menu.main.button.name,             IMG_MENU_BUTTON_NAME,
557     &menu.main.text.name,               &main_text_name,
558     &menu.main.input.name,              &setup.player_name,
559   },
560   {
561     MAIN_CONTROL_LEVELS,
562     &menu.main.button.levels,           IMG_MENU_BUTTON_LEVELS,
563     &menu.main.text.levels,             &main_text_levels,
564     NULL,                               NULL,
565   },
566   {
567     MAIN_CONTROL_SCORES,
568     &menu.main.button.scores,           IMG_MENU_BUTTON_SCORES,
569     &menu.main.text.scores,             &main_text_scores,
570     NULL,                               NULL,
571   },
572   {
573     MAIN_CONTROL_EDITOR,
574     &menu.main.button.editor,           IMG_MENU_BUTTON_EDITOR,
575     &menu.main.text.editor,             &main_text_editor,
576     NULL,                               NULL,
577   },
578   {
579     MAIN_CONTROL_INFO,
580     &menu.main.button.info,             IMG_MENU_BUTTON_INFO,
581     &menu.main.text.info,               &main_text_info,
582     NULL,                               NULL,
583   },
584   {
585     MAIN_CONTROL_GAME,
586     &menu.main.button.game,             IMG_MENU_BUTTON_GAME,
587     &menu.main.text.game,               &main_text_game,
588     NULL,                               NULL,
589   },
590   {
591     MAIN_CONTROL_SETUP,
592     &menu.main.button.setup,            IMG_MENU_BUTTON_SETUP,
593     &menu.main.text.setup,              &main_text_setup,
594     NULL,                               NULL,
595   },
596   {
597     MAIN_CONTROL_QUIT,
598     &menu.main.button.quit,             IMG_MENU_BUTTON_QUIT,
599     &menu.main.text.quit,               &main_text_quit,
600     NULL,                               NULL,
601   },
602 #if 0
603   /* (these two buttons are real gadgets) */
604   {
605     MAIN_CONTROL_PREV_LEVEL,
606     &menu.main.button.prev_level,       IMG_MENU_BUTTON_PREV_LEVEL,
607     NULL,                               NULL,
608     NULL,                               NULL,
609   },
610   {
611     MAIN_CONTROL_NEXT_LEVEL,
612     &menu.main.button.next_level,       IMG_MENU_BUTTON_NEXT_LEVEL,
613     NULL,                               NULL,
614     NULL,                               NULL,
615   },
616 #endif
617   {
618     MAIN_CONTROL_FIRST_LEVEL,
619     NULL,                               -1,
620     &menu.main.text.first_level,        &main_text_first_level,
621     NULL,                               NULL,
622   },
623   {
624     MAIN_CONTROL_LAST_LEVEL,
625     NULL,                               -1,
626     &menu.main.text.last_level,         &main_text_last_level,
627     NULL,                               NULL,
628   },
629   {
630     MAIN_CONTROL_LEVEL_NUMBER,
631     NULL,                               -1,
632     &menu.main.text.level_number,       &main_text_level_number,
633     NULL,                               NULL,
634   },
635   {
636     MAIN_CONTROL_LEVEL_INFO_1,
637     NULL,                               -1,
638     &menu.main.text.level_info_1,       NULL,
639     NULL,                               NULL,
640   },
641   {
642     MAIN_CONTROL_LEVEL_INFO_2,
643     NULL,                               -1,
644     &menu.main.text.level_info_2,       NULL,
645     NULL,                               NULL,
646   },
647   {
648     MAIN_CONTROL_LEVEL_NAME,
649     NULL,                               -1,
650     &menu.main.text.level_name,         &main_text_level_name,
651     NULL,                               NULL,
652   },
653   {
654     MAIN_CONTROL_LEVEL_AUTHOR,
655     NULL,                               -1,
656     &menu.main.text.level_author,       &main_text_level_author,
657     NULL,                               NULL,
658   },
659   {
660     MAIN_CONTROL_LEVEL_YEAR,
661     NULL,                               -1,
662     &menu.main.text.level_year,         &main_text_level_year,
663     NULL,                               NULL,
664   },
665   {
666     MAIN_CONTROL_LEVEL_IMPORTED_FROM,
667     NULL,                               -1,
668     &menu.main.text.level_imported_from, &main_text_level_imported_from,
669     NULL,                               NULL,
670   },
671   {
672     MAIN_CONTROL_LEVEL_IMPORTED_BY,
673     NULL,                               -1,
674     &menu.main.text.level_imported_by,  &main_text_level_imported_by,
675     NULL,                               NULL,
676   },
677   {
678     MAIN_CONTROL_LEVEL_TESTED_BY,
679     NULL,                               -1,
680     &menu.main.text.level_tested_by,    &main_text_level_tested_by,
681     NULL,                               NULL,
682   },
683   {
684     MAIN_CONTROL_TITLE_1,
685     NULL,                               -1,
686     &menu.main.text.title_1,            &setup.internal.program_title,
687     NULL,                               NULL,
688   },
689   {
690     MAIN_CONTROL_TITLE_2,
691     NULL,                               -1,
692     &menu.main.text.title_2,            &setup.internal.program_copyright,
693     NULL,                               NULL,
694   },
695   {
696     MAIN_CONTROL_TITLE_3,
697     NULL,                               -1,
698     &menu.main.text.title_3,            &setup.internal.program_company,
699     NULL,                               NULL,
700   },
701
702   {
703     -1,
704     NULL,                               -1,
705     NULL,                               NULL,
706     NULL,                               NULL,
707   }
708 };
709
710
711 static int getTitleScreenGraphic(int nr, boolean initial)
712 {
713   return (initial ? IMG_TITLESCREEN_INITIAL_1 : IMG_TITLESCREEN_1) + nr;
714 }
715
716 static struct TitleMessageInfo *getTitleMessageInfo(int nr, boolean initial)
717 {
718   return (initial ? &titlemessage_initial[nr] : &titlemessage[nr]);
719 }
720
721 #if 0
722 static int getTitleScreenGameMode(boolean initial)
723 {
724   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
725 }
726 #endif
727
728 static int getTitleMessageGameMode(boolean initial)
729 {
730   return (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
731 }
732
733 static int getTitleAnimMode(struct TitleControlInfo *tci)
734 {
735   int base = (tci->initial ? GAME_MODE_TITLE_INITIAL_1 : GAME_MODE_TITLE_1);
736
737   return base + tci->local_nr;
738 }
739
740 #if 0
741 static int getTitleScreenBackground(boolean initial)
742 {
743   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
744 }
745 #endif
746
747 #if 0
748 static int getTitleMessageBackground(int nr, boolean initial)
749 {
750   return (initial ? IMG_BACKGROUND_TITLE_INITIAL : IMG_BACKGROUND_TITLE);
751 }
752 #endif
753
754 static int getTitleBackground(int nr, boolean initial, boolean is_image)
755 {
756   int base = (is_image ?
757               (initial ? IMG_BACKGROUND_TITLESCREEN_INITIAL_1 :
758                          IMG_BACKGROUND_TITLESCREEN_1) :
759               (initial ? IMG_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
760                          IMG_BACKGROUND_TITLEMESSAGE_1));
761   int graphic_global = (initial ? IMG_BACKGROUND_TITLE_INITIAL :
762                                   IMG_BACKGROUND_TITLE);
763   int graphic_local = base + nr;
764
765   if (graphic_info[graphic_local].bitmap != NULL)
766     return graphic_local;
767
768   if (graphic_info[graphic_global].bitmap != NULL)
769     return graphic_global;
770
771   return IMG_UNDEFINED;
772 }
773
774 static int getTitleSound(struct TitleControlInfo *tci)
775 {
776   boolean is_image = tci->is_image;
777   int initial = tci->initial;
778   int nr = tci->local_nr;
779   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
780   int base = (is_image ?
781               (initial ? SND_BACKGROUND_TITLESCREEN_INITIAL_1 :
782                          SND_BACKGROUND_TITLESCREEN_1) :
783               (initial ? SND_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
784                          SND_BACKGROUND_TITLEMESSAGE_1));
785   int sound_global = menu.sound[mode];
786   int sound_local = base + nr;
787
788 #if 0
789   printf("::: %d, %d, %d: %d ['%s'], %d ['%s']\n",
790          nr, initial, is_image,
791          sound_global, getSoundListEntry(sound_global)->filename,
792          sound_local, getSoundListEntry(sound_local)->filename);
793 #endif
794
795   if (!strEqual(getSoundListEntry(sound_local)->filename, UNDEFINED_FILENAME))
796     return sound_local;
797
798   if (!strEqual(getSoundListEntry(sound_global)->filename, UNDEFINED_FILENAME))
799     return sound_global;
800
801   return SND_UNDEFINED;
802 }
803
804 static int getTitleMusic(struct TitleControlInfo *tci)
805 {
806   boolean is_image = tci->is_image;
807   int initial = tci->initial;
808   int nr = tci->local_nr;
809   int mode = (initial ? GAME_MODE_TITLE_INITIAL : GAME_MODE_TITLE);
810   int base = (is_image ?
811               (initial ? MUS_BACKGROUND_TITLESCREEN_INITIAL_1 :
812                          MUS_BACKGROUND_TITLESCREEN_1) :
813               (initial ? MUS_BACKGROUND_TITLEMESSAGE_INITIAL_1 :
814                          MUS_BACKGROUND_TITLEMESSAGE_1));
815   int music_global = menu.music[mode];
816   int music_local = base + nr;
817
818 #if 0
819   printf("::: %d, %d, %d: %d ['%s'], %d ['%s']\n",
820          nr, initial, is_image,
821          music_global, getMusicListEntry(music_global)->filename,
822          music_local, getMusicListEntry(music_local)->filename);
823 #endif
824
825   if (!strEqual(getMusicListEntry(music_local)->filename, UNDEFINED_FILENAME))
826     return music_local;
827
828   if (!strEqual(getMusicListEntry(music_global)->filename, UNDEFINED_FILENAME))
829     return music_global;
830
831   return MUS_UNDEFINED;
832 }
833
834 static struct TitleFadingInfo getTitleFading(struct TitleControlInfo *tci)
835 {
836   boolean is_image = tci->is_image;
837   boolean initial = tci->initial;
838   boolean first = tci->first;
839   int nr = tci->local_nr;
840   struct TitleMessageInfo tmi;
841   struct TitleFadingInfo ti;
842
843   tmi = (is_image ? (initial ? (first ?
844                                 titlescreen_initial_first[nr] :
845                                 titlescreen_initial[nr])
846                              : (first ?
847                                 titlescreen_first[nr] :
848                                 titlescreen[nr]))
849                   : (initial ? (first ?
850                                 titlemessage_initial_first[nr] :
851                                 titlemessage_initial[nr])
852                              : (first ?
853                                 titlemessage_first[nr] :
854                                 titlemessage[nr])));
855
856   ti.fade_mode  = tmi.fade_mode;
857   ti.fade_delay = tmi.fade_delay;
858   ti.post_delay = tmi.post_delay;
859   ti.auto_delay = tmi.auto_delay;
860
861   return ti;
862 }
863
864 static int compareTitleControlInfo(const void *object1, const void *object2)
865 {
866   const struct TitleControlInfo *tci1 = (struct TitleControlInfo *)object1;
867   const struct TitleControlInfo *tci2 = (struct TitleControlInfo *)object2;
868   int compare_result;
869
870   if (tci1->initial != tci2->initial)
871     compare_result = (tci1->initial ? -1 : +1);
872   else if (tci1->sort_priority != tci2->sort_priority)
873     compare_result = tci1->sort_priority - tci2->sort_priority;
874   else if (tci1->is_image != tci2->is_image)
875     compare_result = (tci1->is_image ? -1 : +1);
876   else
877     compare_result = tci1->local_nr - tci2->local_nr;
878
879   return compare_result;
880 }
881
882 static void InitializeTitleControlsExt_AddTitleInfo(boolean is_image,
883                                                     boolean initial,
884                                                     int nr, int sort_priority)
885 {
886   title_controls[num_title_screens].is_image = is_image;
887   title_controls[num_title_screens].initial = initial;
888   title_controls[num_title_screens].local_nr = nr;
889   title_controls[num_title_screens].sort_priority = sort_priority;
890
891   title_controls[num_title_screens].first = FALSE;      /* will be set later */
892
893   num_title_screens++;
894 }
895
896 static void InitializeTitleControls_CheckTitleInfo(boolean initial)
897 {
898   int i;
899
900   for (i = 0; i < MAX_NUM_TITLE_IMAGES; i++)
901   {
902     int graphic = getTitleScreenGraphic(i, initial);
903     Bitmap *bitmap = graphic_info[graphic].bitmap;
904     int sort_priority = graphic_info[graphic].sort_priority;
905
906     if (bitmap != NULL)
907       InitializeTitleControlsExt_AddTitleInfo(TRUE, initial, i, sort_priority);
908   }
909
910   for (i = 0; i < MAX_NUM_TITLE_MESSAGES; i++)
911   {
912     struct TitleMessageInfo *tmi = getTitleMessageInfo(i, initial);
913     char *filename = getLevelSetTitleMessageFilename(i, initial);
914     int sort_priority = tmi->sort_priority;
915
916     if (filename != NULL)
917       InitializeTitleControlsExt_AddTitleInfo(FALSE, initial, i, sort_priority);
918   }
919 }
920
921 static void InitializeTitleControls(boolean show_title_initial)
922 {
923   num_title_screens = 0;
924
925   /* 1st step: initialize title screens for game start (only when starting) */
926   if (show_title_initial)
927     InitializeTitleControls_CheckTitleInfo(TRUE);
928
929   /* 2nd step: initialize title screens for current level set */
930   InitializeTitleControls_CheckTitleInfo(FALSE);
931
932   /* sort title screens according to sort_priority and title number */
933   qsort(title_controls, num_title_screens, sizeof(struct TitleControlInfo),
934         compareTitleControlInfo);
935
936   /* mark first title screen */
937   title_controls[0].first = TRUE;
938 }
939
940 static boolean visibleMenuPos(struct MenuPosInfo *pos)
941 {
942   return (pos != NULL && pos->x != -1 && pos->y != -1);
943 }
944
945 static boolean visibleTextPos(struct TextPosInfo *pos)
946 {
947   return (pos != NULL && pos->x != -1 && pos->y != -1);
948 }
949
950 static void InitializeMainControls()
951 {
952   boolean local_team_mode = (!options.network && setup.team_mode);
953   int i;
954
955   /* set main control text values to dynamically determined values */
956   sprintf(main_text_name,         "%s",   local_team_mode ? "Team:" : "Name:");
957
958   strcpy(main_text_first_level,  int2str(leveldir_current->first_level,
959                                          menu.main.text.first_level.size));
960   strcpy(main_text_last_level,   int2str(leveldir_current->last_level,
961                                          menu.main.text.last_level.size));
962   strcpy(main_text_level_number, int2str(level_nr,
963                                          menu.main.text.level_number.size));
964
965   main_text_level_year          = leveldir_current->year;
966   main_text_level_imported_from = leveldir_current->imported_from;
967   main_text_level_imported_by   = leveldir_current->imported_by;
968   main_text_level_tested_by     = leveldir_current->tested_by;
969
970   /* set main control screen positions to dynamically determined values */
971   for (i = 0; main_controls[i].nr != -1; i++)
972   {
973     struct MainControlInfo *mci = &main_controls[i];
974     int nr                         = mci->nr;
975     struct MenuPosInfo *pos_button = mci->pos_button;
976     struct TextPosInfo *pos_text   = mci->pos_text;
977     struct TextPosInfo *pos_input  = mci->pos_input;
978     char *text                     = (mci->text  ? *mci->text  : NULL);
979     char *input                    = (mci->input ? *mci->input : NULL);
980     int button_graphic             = mci->button_graphic;
981     int font_text                  = (pos_text  ? pos_text->font  : -1);
982     int font_input                 = (pos_input ? pos_input->font : -1);
983
984     int font_text_width   = (font_text  != -1 ? getFontWidth(font_text)   : 0);
985     int font_text_height  = (font_text  != -1 ? getFontHeight(font_text)  : 0);
986     int font_input_width  = (font_input != -1 ? getFontWidth(font_input)  : 0);
987     int font_input_height = (font_input != -1 ? getFontHeight(font_input) : 0);
988     int text_chars  = (text  != NULL ? strlen(text)  : 0);
989     int input_chars = (input != NULL ? strlen(input) : 0);
990
991     int button_width =
992       (button_graphic != -1 ? graphic_info[button_graphic].width  : 0);
993     int button_height =
994       (button_graphic != -1 ? graphic_info[button_graphic].height : 0);
995     int text_width   = font_text_width * text_chars;
996     int text_height  = font_text_height;
997     int input_width  = font_input_width * input_chars;
998     int input_height = font_input_height;
999
1000     if (nr == MAIN_CONTROL_NAME)
1001     {
1002       menu.main.input.name.width  = input_width;
1003       menu.main.input.name.height = input_height;
1004     }
1005
1006     if (pos_button != NULL)             /* (x/y may be -1/-1 here) */
1007     {
1008       pos_button->width  = button_width;
1009       pos_button->height = button_height;
1010     }
1011
1012     if (pos_text != NULL)               /* (x/y may be -1/-1 here) */
1013     {
1014       /* calculate size for non-clickable text -- needed for text alignment */
1015       boolean calculate_text_size = (pos_button == NULL && text != NULL);
1016
1017       if (pos_text->width == -1 || calculate_text_size)
1018         pos_text->width = text_width;
1019       if (pos_text->height == -1 || calculate_text_size)
1020         pos_text->height = text_height;
1021
1022       if (visibleMenuPos(pos_button))
1023       {
1024         if (pos_text->x == -1)
1025           pos_text->x = pos_button->x + pos_button->width;
1026         if (pos_text->y == -1)
1027           pos_text->y =
1028             pos_button->y + (pos_button->height - pos_text->height) / 2;
1029       }
1030     }
1031
1032     if (pos_input != NULL)              /* (x/y may be -1/-1 here) */
1033     {
1034       if (visibleTextPos(pos_text))
1035       {
1036         if (pos_input->x == -1)
1037           pos_input->x = pos_text->x + pos_text->width;
1038         if (pos_input->y == -1)
1039           pos_input->y = pos_text->y;
1040       }
1041
1042       if (pos_input->width == -1)
1043         pos_input->width = input_width;
1044       if (pos_input->height == -1)
1045         pos_input->height = input_height;
1046     }
1047   }
1048 }
1049
1050 static void DrawPressedGraphicThruMask(int dst_x, int dst_y,
1051                                        int graphic, boolean pressed)
1052 {
1053   struct GraphicInfo *g = &graphic_info[graphic];
1054   Bitmap *src_bitmap;
1055   int src_x, src_y;
1056   int xoffset = (pressed ? g->pressed_xoffset : 0);
1057   int yoffset = (pressed ? g->pressed_yoffset : 0);
1058
1059   getFixedGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
1060
1061   BlitBitmapMasked(src_bitmap, drawto, src_x + xoffset, src_y + yoffset,
1062                    g->width, g->height, dst_x, dst_y);
1063 }
1064
1065 static void DrawCursorAndText_Main_Ext(int nr, boolean active_text,
1066                                        boolean active_input,
1067                                        boolean pressed_button)
1068 {
1069   int i;
1070
1071   for (i = 0; main_controls[i].nr != -1; i++)
1072   {
1073     struct MainControlInfo *mci = &main_controls[i];
1074
1075     if (mci->nr == nr || nr == -1)
1076     {
1077       struct MenuPosInfo *pos_button = mci->pos_button;
1078       struct TextPosInfo *pos_text   = mci->pos_text;
1079       struct TextPosInfo *pos_input  = mci->pos_input;
1080       char *text                     = (mci->text  ? *mci->text  : NULL);
1081       char *input                    = (mci->input ? *mci->input : NULL);
1082       int button_graphic             = mci->button_graphic;
1083       int font_text                  = (pos_text  ? pos_text->font  : -1);
1084       int font_input                 = (pos_input ? pos_input->font : -1);
1085
1086       if (active_text)
1087       {
1088         button_graphic = BUTTON_ACTIVE(button_graphic);
1089         font_text = FONT_ACTIVE(font_text);
1090       }
1091
1092       if (active_input)
1093       {
1094         font_input = FONT_ACTIVE(font_input);
1095       }
1096
1097       if (visibleMenuPos(pos_button))
1098       {
1099         struct MenuPosInfo *pos = pos_button;
1100         int x = mSX + pos->x;
1101         int y = mSY + pos->y;
1102
1103         DrawBackgroundForGraphic(x, y, pos->width, pos->height, button_graphic);
1104         DrawPressedGraphicThruMask(x, y, button_graphic, pressed_button);
1105       }
1106
1107       if (visibleTextPos(pos_text) && text != NULL)
1108       {
1109         struct TextPosInfo *pos = pos_text;
1110         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1111         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1112
1113 #if 1
1114         /* (check why/if this is needed) */
1115         DrawBackgroundForFont(x, y, pos->width, pos->height, font_text);
1116 #endif
1117         DrawText(x, y, text, font_text);
1118       }
1119
1120       if (visibleTextPos(pos_input) && input != NULL)
1121       {
1122         struct TextPosInfo *pos = pos_input;
1123         int x = mSX + ALIGNED_TEXT_XPOS(pos);
1124         int y = mSY + ALIGNED_TEXT_YPOS(pos);
1125
1126 #if 1
1127         /* (check why/if this is needed) */
1128         DrawBackgroundForFont(x, y, pos->width, pos->height, font_input);
1129 #endif
1130         DrawText(x, y, input, font_input);
1131       }
1132     }
1133   }
1134 }
1135
1136 static void DrawCursorAndText_Main(int nr, boolean active_text,
1137                                    boolean pressed_button)
1138 {
1139   DrawCursorAndText_Main_Ext(nr, active_text, FALSE, pressed_button);
1140 }
1141
1142 #if 0
1143 static void DrawCursorAndText_Main_Input(int nr, boolean active_text,
1144                                          boolean pressed_button)
1145 {
1146   DrawCursorAndText_Main_Ext(nr, active_text, TRUE, pressed_button);
1147 }
1148 #endif
1149
1150 static struct MainControlInfo *getMainControlInfo(int nr)
1151 {
1152   int i;
1153
1154   for (i = 0; main_controls[i].nr != -1; i++)
1155     if (main_controls[i].nr == nr)
1156       return &main_controls[i];
1157
1158   return NULL;
1159 }
1160
1161 static boolean insideMenuPosRect(struct MenuPosInfo *rect, int x, int y)
1162 {
1163   if (rect == NULL)
1164     return FALSE;
1165
1166   int rect_x = ALIGNED_TEXT_XPOS(rect);
1167   int rect_y = ALIGNED_TEXT_YPOS(rect);
1168
1169   return (x >= rect_x && x < rect_x + rect->width &&
1170           y >= rect_y && y < rect_y + rect->height);
1171 }
1172
1173 static boolean insideTextPosRect(struct TextPosInfo *rect, int x, int y)
1174 {
1175   if (rect == NULL)
1176     return FALSE;
1177
1178   int rect_x = ALIGNED_TEXT_XPOS(rect);
1179   int rect_y = ALIGNED_TEXT_YPOS(rect);
1180
1181 #if 0
1182   printf("::: insideTextPosRect: (%d, %d), (%d, %d) [%d, %d] (%d, %d) => %d\n",
1183          x, y, rect_x, rect_y, rect->x, rect->y, rect->width, rect->height,
1184          (x >= rect_x && x < rect_x + rect->width &&
1185           y >= rect_y && y < rect_y + rect->height));
1186 #endif
1187
1188   return (x >= rect_x && x < rect_x + rect->width &&
1189           y >= rect_y && y < rect_y + rect->height);
1190 }
1191
1192 static boolean insidePreviewRect(struct PreviewInfo *preview, int x, int y)
1193 {
1194   int rect_width  = preview->xsize * preview->tile_size;
1195   int rect_height = preview->ysize * preview->tile_size;
1196   int rect_x = ALIGNED_XPOS(preview->x, rect_width,  preview->align);
1197   int rect_y = ALIGNED_YPOS(preview->y, rect_height, preview->valign);
1198
1199   return (x >= rect_x && x < rect_x + rect_width &&
1200           y >= rect_y && y < rect_y + rect_height);
1201 }
1202
1203 static void AdjustScrollbar(int id, int items_max, int items_visible,
1204                             int item_position)
1205 {
1206   struct GadgetInfo *gi = screen_gadget[id];
1207
1208   if (item_position > items_max - items_visible)
1209     item_position = items_max - items_visible;
1210
1211   ModifyGadget(gi, GDI_SCROLLBAR_ITEMS_MAX, items_max,
1212                GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
1213                GDI_SCROLLBAR_ITEM_POSITION, item_position, GDI_END);
1214 }
1215
1216 static void AdjustChooseTreeScrollbar(int id, int first_entry, TreeInfo *ti)
1217 {
1218   AdjustScrollbar(id, numTreeInfoInGroup(ti), NUM_MENU_ENTRIES_ON_SCREEN,
1219                   first_entry);
1220 }
1221
1222 static void clearMenuListArea()
1223 {
1224   int scrollbar_xpos = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
1225
1226   /* correct scrollbar position if placed outside menu (playfield) area */
1227   if (scrollbar_xpos > SX + SC_SCROLLBAR_XPOS)
1228     scrollbar_xpos = SX + SC_SCROLLBAR_XPOS;
1229
1230   /* clear menu list area, but not title or scrollbar */
1231   DrawBackground(mSX, mSY + MENU_SCREEN_START_YPOS * 32,
1232                  scrollbar_xpos - mSX, NUM_MENU_ENTRIES_ON_SCREEN * 32);
1233 }
1234
1235 static void drawCursorExt(int xpos, int ypos, boolean active, int graphic)
1236 {
1237   static int cursor_array[MAX_LEV_FIELDY];
1238   int x = mSX + TILEX * xpos;
1239   int y = mSY + TILEY * (MENU_SCREEN_START_YPOS + ypos);
1240
1241   if (xpos == 0)
1242   {
1243     if (graphic != -1)
1244       cursor_array[ypos] = graphic;
1245     else
1246       graphic = cursor_array[ypos];
1247   }
1248
1249   if (active)
1250     graphic = BUTTON_ACTIVE(graphic);
1251
1252   DrawBackgroundForGraphic(x, y, TILEX, TILEY, graphic);
1253   DrawFixedGraphicThruMaskExt(drawto, x, y, graphic, 0);
1254 }
1255
1256 static void initCursor(int ypos, int graphic)
1257 {
1258   drawCursorExt(0, ypos, FALSE, graphic);
1259 }
1260
1261 static void drawCursor(int ypos, boolean active)
1262 {
1263   drawCursorExt(0, ypos, active, -1);
1264 }
1265
1266 static void drawCursorXY(int xpos, int ypos, int graphic)
1267 {
1268   drawCursorExt(xpos, ypos, FALSE, graphic);
1269 }
1270
1271 static void drawChooseTreeCursor(int ypos, boolean active)
1272 {
1273   drawCursorExt(0, ypos, active, -1);
1274 }
1275
1276 void DrawHeadline()
1277 {
1278   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, getProgramTitleString());
1279   DrawTextSCentered(MENU_TITLE2_YPOS, FONT_TITLE_2,
1280                     setup.internal.program_copyright);
1281 }
1282
1283 void DrawTitleScreenImage(int nr, boolean initial)
1284 {
1285   int graphic = getTitleScreenGraphic(nr, initial);
1286   Bitmap *bitmap = graphic_info[graphic].bitmap;
1287   int width  = graphic_info[graphic].width;
1288   int height = graphic_info[graphic].height;
1289   int src_x = graphic_info[graphic].src_x;
1290   int src_y = graphic_info[graphic].src_y;
1291   int dst_x, dst_y;
1292
1293   if (bitmap == NULL)
1294     return;
1295
1296   if (width > WIN_XSIZE)
1297   {
1298     /* image width too large for window => center image horizontally */
1299     src_x = (width - WIN_XSIZE) / 2;
1300     width = WIN_XSIZE;
1301   }
1302
1303   if (height > WIN_YSIZE)
1304   {
1305     /* image height too large for window => center image vertically */
1306     src_y = (height - WIN_YSIZE) / 2;
1307     height = WIN_YSIZE;
1308   }
1309
1310   /* always display title screens centered */
1311   dst_x = (WIN_XSIZE - width) / 2;
1312   dst_y = (WIN_YSIZE - height) / 2;
1313
1314   SetDrawBackgroundMask(REDRAW_ALL);
1315   SetWindowBackgroundImage(getTitleBackground(nr, initial, TRUE));
1316
1317   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1318
1319   if (DrawingOnBackground(dst_x, dst_y))
1320     BlitBitmapMasked(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1321   else
1322     BlitBitmap(bitmap, drawto, src_x, src_y, width, height, dst_x, dst_y);
1323
1324   redraw_mask = REDRAW_ALL;
1325 }
1326
1327 void DrawTitleScreenMessage(int nr, boolean initial)
1328 {
1329   char *filename = getLevelSetTitleMessageFilename(nr, initial);
1330   struct TitleMessageInfo *tmi = getTitleMessageInfo(nr, initial);
1331
1332   if (filename == NULL)
1333     return;
1334
1335   /* force TITLE font on title message screen */
1336   SetFontStatus(getTitleMessageGameMode(initial));
1337
1338   /* if chars *and* width set to "-1", automatically determine width */
1339   if (tmi->chars == -1 && tmi->width == -1)
1340     tmi->width = viewport.window[game_status].width;
1341
1342   /* if lines *and* height set to "-1", automatically determine height */
1343   if (tmi->lines == -1 && tmi->height == -1)
1344     tmi->height = viewport.window[game_status].height;
1345
1346   /* if chars set to "-1", automatically determine by text and font width */
1347   if (tmi->chars == -1)
1348     tmi->chars = tmi->width / getFontWidth(tmi->font);
1349   else
1350     tmi->width = tmi->chars * getFontWidth(tmi->font);
1351
1352   /* if lines set to "-1", automatically determine by text and font height */
1353   if (tmi->lines == -1)
1354     tmi->lines = tmi->height / getFontHeight(tmi->font);
1355   else
1356     tmi->height = tmi->lines * getFontHeight(tmi->font);
1357
1358   /* if x set to "-1", automatically determine by width and alignment */
1359   if (tmi->x == -1)
1360     tmi->x = -1 * ALIGNED_XPOS(0, tmi->width, tmi->align);
1361
1362   /* if y set to "-1", automatically determine by height and alignment */
1363   if (tmi->y == -1)
1364     tmi->y = -1 * ALIGNED_YPOS(0, tmi->height, tmi->valign);
1365
1366   SetDrawBackgroundMask(REDRAW_ALL);
1367   SetWindowBackgroundImage(getTitleBackground(nr, initial, FALSE));
1368
1369   ClearRectangleOnBackground(drawto, 0, 0, WIN_XSIZE, WIN_YSIZE);
1370
1371   DrawTextFile(ALIGNED_TEXT_XPOS(tmi), ALIGNED_TEXT_YPOS(tmi),
1372                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
1373                tmi->autowrap, tmi->centered, tmi->parse_comments);
1374
1375   ResetFontStatus();
1376 }
1377
1378 void DrawTitleScreen()
1379 {
1380   KeyboardAutoRepeatOff();
1381
1382   HandleTitleScreen(0, 0, 0, 0, MB_MENU_INITIALIZE);
1383 }
1384
1385 boolean CheckTitleScreen(boolean levelset_has_changed)
1386 {
1387   static boolean show_title_initial = TRUE;
1388   boolean show_titlescreen = FALSE;
1389
1390   /* needed to be able to skip title screen, if no image or message defined */
1391   InitializeTitleControls(show_title_initial);
1392
1393   if (setup.show_titlescreen && (show_title_initial || levelset_has_changed))
1394     show_titlescreen = TRUE;
1395
1396   /* show initial title images and messages only once at program start */
1397   show_title_initial = FALSE;
1398
1399   return (show_titlescreen && num_title_screens > 0);
1400 }
1401
1402 void DrawMainMenu()
1403 {
1404   static LevelDirTree *leveldir_last_valid = NULL;
1405   boolean levelset_has_changed = FALSE;
1406   int fade_mask = REDRAW_FIELD;
1407
1408   LimitScreenUpdates(FALSE);
1409
1410   FadeSetLeaveScreen();
1411
1412   /* do not fade out here -- function may continue and fade on editor screen */
1413
1414   UnmapAllGadgets();
1415   FadeMenuSoundsAndMusic();
1416
1417   ExpireSoundLoops(FALSE);
1418
1419   KeyboardAutoRepeatOn();
1420
1421   audio.sound_deactivated = FALSE;
1422
1423   GetPlayerConfig();
1424
1425   /* needed if last screen was the playing screen, invoked from level editor */
1426   if (level_editor_test_game)
1427   {
1428     CloseDoor(DOOR_CLOSE_ALL);
1429
1430     SetGameStatus(GAME_MODE_EDITOR);
1431
1432     DrawLevelEd();
1433
1434     return;
1435   }
1436
1437   /* needed if last screen was the setup screen and fullscreen state changed */
1438   // (moved to "execSetupGraphics()" to change fullscreen state directly)
1439   // ToggleFullscreenOrChangeWindowScalingIfNeeded();
1440
1441   /* leveldir_current may be invalid (level group, parent link) */
1442   if (!validLevelSeries(leveldir_current))
1443     leveldir_current = getFirstValidTreeInfoEntry(leveldir_last_valid);
1444
1445   if (leveldir_current != leveldir_last_valid)
1446     levelset_has_changed = TRUE;
1447
1448   /* store valid level series information */
1449   leveldir_last_valid = leveldir_current;
1450
1451   init_last = init;                     /* switch to new busy animation */
1452
1453   /* needed if last screen (level choice) changed graphics, sounds or music */
1454   ReloadCustomArtwork(0);
1455
1456   if (CheckTitleScreen(levelset_has_changed))
1457   {
1458     SetGameStatus(GAME_MODE_TITLE);
1459
1460     DrawTitleScreen();
1461
1462     return;
1463   }
1464
1465   if (redraw_mask & REDRAW_ALL)
1466     fade_mask = REDRAW_ALL;
1467
1468   if (CheckIfGlobalBorderHasChanged())
1469     fade_mask = REDRAW_ALL;
1470
1471   FadeOut(fade_mask);
1472
1473   /* needed if different viewport properties defined for menues */
1474   ChangeViewportPropertiesIfNeeded();
1475
1476   SetDrawtoField(DRAW_TO_BACKBUFFER);
1477
1478   /* level_nr may have been set to value over handicap with level editor */
1479   if (setup.handicap && level_nr > leveldir_current->handicap_level)
1480     level_nr = leveldir_current->handicap_level;
1481
1482   LoadLevel(level_nr);
1483   LoadScore(level_nr);
1484
1485   SaveLevelSetup_SeriesInfo();
1486
1487   // set this after "ChangeViewportPropertiesIfNeeded()" (which may reset it)
1488   SetDrawDeactivationMask(REDRAW_NONE);
1489   SetDrawBackgroundMask(REDRAW_FIELD);
1490
1491   SetMainBackgroundImage(IMG_BACKGROUND_MAIN);
1492
1493 #if 0
1494   if (fade_mask == REDRAW_ALL)
1495     RedrawGlobalBorder();
1496 #endif
1497
1498   ClearField();
1499
1500   InitializeMainControls();
1501
1502   DrawCursorAndText_Main(-1, FALSE, FALSE);
1503   DrawPreviewLevelInitial();
1504
1505   HandleMainMenu(0, 0, 0, 0, MB_MENU_INITIALIZE);
1506
1507   TapeStop();
1508   if (TAPE_IS_EMPTY(tape))
1509     LoadTape(level_nr);
1510   DrawCompleteVideoDisplay();
1511
1512   PlayMenuSoundsAndMusic();
1513
1514   /* create gadgets for main menu screen */
1515   FreeScreenGadgets();
1516   CreateScreenGadgets();
1517
1518   /* map gadgets for main menu screen */
1519   MapTapeButtons();
1520   MapScreenMenuGadgets(SCREEN_MASK_MAIN);
1521
1522   /* copy actual game door content to door double buffer for OpenDoor() */
1523   BlitBitmap(drawto, bitmap_db_door_1, DX, DY, DXSIZE, DYSIZE, 0, 0);
1524   BlitBitmap(drawto, bitmap_db_door_2, VX, VY, VXSIZE, VYSIZE, 0, 0);
1525
1526   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
1527
1528   DrawMaskedBorder(fade_mask);
1529
1530   FadeIn(fade_mask);
1531   FadeSetEnterMenu();
1532
1533   /* update screen area with special editor door */
1534   redraw_mask |= REDRAW_ALL;
1535   BackToFront();
1536
1537   SetMouseCursor(CURSOR_DEFAULT);
1538
1539   OpenDoor(DOOR_CLOSE_1 | DOOR_OPEN_2);
1540 }
1541
1542 static void gotoTopLevelDir()
1543 {
1544   /* move upwards until inside (but not above) top level directory */
1545   while (leveldir_current->node_parent &&
1546          !strEqual(leveldir_current->node_parent->subdir, STRING_TOP_DIRECTORY))
1547   {
1548     /* write a "path" into level tree for easy navigation to last level */
1549     if (leveldir_current->node_parent->node_group->cl_first == -1)
1550     {
1551       int num_leveldirs = numTreeInfoInGroup(leveldir_current);
1552       int leveldir_pos = posTreeInfo(leveldir_current);
1553       int num_page_entries;
1554       int cl_first, cl_cursor;
1555
1556       if (num_leveldirs <= NUM_MENU_ENTRIES_ON_SCREEN)
1557         num_page_entries = num_leveldirs;
1558       else
1559         num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
1560
1561       cl_first = MAX(0, leveldir_pos - num_page_entries + 1);
1562       cl_cursor = leveldir_pos - cl_first;
1563
1564       leveldir_current->node_parent->node_group->cl_first = cl_first;
1565       leveldir_current->node_parent->node_group->cl_cursor = cl_cursor;
1566     }
1567
1568     leveldir_current = leveldir_current->node_parent;
1569   }
1570 }
1571
1572 void HandleTitleScreen(int mx, int my, int dx, int dy, int button)
1573 {
1574   static unsigned int title_delay = 0;
1575   static int title_screen_nr = 0;
1576   static int last_sound = -1, last_music = -1;
1577   boolean return_to_main_menu = FALSE;
1578   struct TitleControlInfo *tci;
1579   int sound, music;
1580
1581   if (button == MB_MENU_INITIALIZE)
1582   {
1583     title_delay = 0;
1584     title_screen_nr = 0;
1585     tci = &title_controls[title_screen_nr];
1586
1587     SetAnimStatus(getTitleAnimMode(tci));
1588
1589     last_sound = SND_UNDEFINED;
1590     last_music = MUS_UNDEFINED;
1591
1592     if (num_title_screens != 0)
1593     {
1594       FadeSetEnterScreen();
1595
1596       /* use individual title fading instead of global "enter screen" fading */
1597       fading = getTitleFading(tci);
1598     }
1599
1600     if (game_status_last_screen == GAME_MODE_INFO)
1601     {
1602       if (num_title_screens == 0)
1603       {
1604         /* switch game mode from title screen mode back to info screen mode */
1605         SetGameStatus(GAME_MODE_INFO);
1606
1607         /* store that last screen was info screen, not main menu screen */
1608         game_status_last_screen = GAME_MODE_INFO;
1609
1610         DrawInfoScreen_NotAvailable("Title screen information:",
1611                                     "No title screen for this level set.");
1612         return;
1613       }
1614
1615       FadeMenuSoundsAndMusic();
1616     }
1617
1618     FadeOut(REDRAW_ALL);
1619
1620     /* title screens may have different window size */
1621     ChangeViewportPropertiesIfNeeded();
1622
1623     /* only required to update logic for redrawing global border */
1624     ClearField();
1625
1626     if (tci->is_image)
1627       DrawTitleScreenImage(tci->local_nr, tci->initial);
1628     else
1629       DrawTitleScreenMessage(tci->local_nr, tci->initial);
1630
1631     sound = getTitleSound(tci);
1632     music = getTitleMusic(tci);
1633
1634     if (sound != last_sound)
1635       PlayMenuSoundExt(sound);
1636     if (music != last_music)
1637       PlayMenuMusicExt(music);
1638
1639     last_sound = sound;
1640     last_music = music;
1641
1642     SetMouseCursor(CURSOR_NONE);
1643
1644     FadeIn(REDRAW_ALL);
1645
1646     DelayReached(&title_delay, 0);      /* reset delay counter */
1647
1648     return;
1649   }
1650
1651   if (fading.auto_delay > 0 && DelayReached(&title_delay, fading.auto_delay))
1652     button = MB_MENU_CHOICE;
1653
1654   if (button == MB_MENU_LEAVE)
1655   {
1656     return_to_main_menu = TRUE;
1657   }
1658   else if (button == MB_MENU_CHOICE)
1659   {
1660     if (game_status_last_screen == GAME_MODE_INFO && num_title_screens == 0)
1661     {
1662       SetGameStatus(GAME_MODE_INFO);
1663
1664       info_mode = INFO_MODE_MAIN;
1665
1666       DrawInfoScreen();
1667
1668       return;
1669     }
1670
1671     title_screen_nr++;
1672
1673     if (title_screen_nr < num_title_screens)
1674     {
1675       tci = &title_controls[title_screen_nr];
1676
1677       SetAnimStatus(getTitleAnimMode(tci));
1678
1679       sound = getTitleSound(tci);
1680       music = getTitleMusic(tci);
1681
1682       if (last_sound != SND_UNDEFINED && sound != last_sound)
1683         FadeSound(last_sound);
1684       if (last_music != MUS_UNDEFINED && music != last_music)
1685         FadeMusic();
1686
1687       fading = getTitleFading(tci);
1688
1689       FadeOut(REDRAW_ALL);
1690
1691       if (tci->is_image)
1692         DrawTitleScreenImage(tci->local_nr, tci->initial);
1693       else
1694         DrawTitleScreenMessage(tci->local_nr, tci->initial);
1695
1696       sound = getTitleSound(tci);
1697       music = getTitleMusic(tci);
1698
1699       if (sound != last_sound)
1700         PlayMenuSoundExt(sound);
1701       if (music != last_music)
1702         PlayMenuMusicExt(music);
1703
1704       last_sound = sound;
1705       last_music = music;
1706
1707       FadeIn(REDRAW_ALL);
1708
1709       DelayReached(&title_delay, 0);    /* reset delay counter */
1710     }
1711     else
1712     {
1713       FadeMenuSoundsAndMusic();
1714
1715       return_to_main_menu = TRUE;
1716     }
1717   }
1718
1719   if (return_to_main_menu)
1720   {
1721     SetMouseCursor(CURSOR_DEFAULT);
1722
1723     /* force full menu screen redraw after displaying title screens */
1724     redraw_mask = REDRAW_ALL;
1725
1726     if (game_status_last_screen == GAME_MODE_INFO)
1727     {
1728       SetGameStatus(GAME_MODE_INFO);
1729
1730       info_mode = INFO_MODE_MAIN;
1731
1732       DrawInfoScreen();
1733     }
1734     else        /* default: return to main menu */
1735     {
1736       SetGameStatus(GAME_MODE_MAIN);
1737
1738       DrawMainMenu();
1739     }
1740   }
1741 }
1742
1743 void HandleMainMenu_SelectLevel(int step, int direction, int selected_level_nr)
1744 {
1745   int old_level_nr = level_nr;
1746   int new_level_nr;
1747
1748   if (selected_level_nr != NO_DIRECT_LEVEL_SELECT)
1749     new_level_nr = selected_level_nr;
1750   else
1751     new_level_nr = old_level_nr + step * direction;
1752
1753   if (new_level_nr < leveldir_current->first_level)
1754     new_level_nr = leveldir_current->first_level;
1755   if (new_level_nr > leveldir_current->last_level)
1756     new_level_nr = leveldir_current->last_level;
1757
1758   if (setup.handicap && new_level_nr > leveldir_current->handicap_level)
1759   {
1760     /* skipping levels is only allowed when trying to skip single level */
1761     if (setup.skip_levels && new_level_nr == old_level_nr + 1 &&
1762         Request("Level still unsolved! Skip despite handicap?", REQ_ASK))
1763     {
1764       leveldir_current->handicap_level++;
1765       SaveLevelSetup_SeriesInfo();
1766     }
1767
1768     new_level_nr = leveldir_current->handicap_level;
1769   }
1770
1771   if (new_level_nr != old_level_nr)
1772   {
1773     struct MainControlInfo *mci= getMainControlInfo(MAIN_CONTROL_LEVEL_NUMBER);
1774
1775     PlaySound(SND_MENU_ITEM_SELECTING);
1776
1777     level_nr = new_level_nr;
1778
1779     DrawText(mSX + mci->pos_text->x, mSY + mci->pos_text->y,
1780              int2str(level_nr, menu.main.text.level_number.size),
1781              mci->pos_text->font);
1782
1783     LoadLevel(level_nr);
1784     DrawPreviewLevelInitial();
1785
1786     TapeErase();
1787     LoadTape(level_nr);
1788     DrawCompleteVideoDisplay();
1789
1790     SaveLevelSetup_SeriesInfo();
1791
1792     /* needed because DrawPreviewLevelInitial() takes some time */
1793     BackToFront();
1794     /* SyncDisplay(); */
1795   }
1796 }
1797
1798 void HandleMainMenu(int mx, int my, int dx, int dy, int button)
1799 {
1800   static int choice = MAIN_CONTROL_GAME;
1801   static boolean button_pressed_last = FALSE;
1802   boolean button_pressed = FALSE;
1803   int pos = choice;
1804   int i;
1805
1806   if (button == MB_MENU_INITIALIZE)
1807   {
1808     DrawCursorAndText_Main(choice, TRUE, FALSE);
1809
1810     return;
1811   }
1812
1813   if (mx || my)         /* mouse input */
1814   {
1815     pos = -1;
1816
1817     for (i = 0; main_controls[i].nr != -1; i++)
1818     {
1819       if (insideMenuPosRect(main_controls[i].pos_button, mx - mSX, my - mSY) ||
1820           insideTextPosRect(main_controls[i].pos_text,   mx - mSX, my - mSY) ||
1821           insideTextPosRect(main_controls[i].pos_input,  mx - mSX, my - mSY))
1822       {
1823         pos = main_controls[i].nr;
1824
1825         break;
1826       }
1827     }
1828
1829     /* check if level preview was clicked */
1830     if (insidePreviewRect(&preview, mx - SX, my - SY))
1831       pos = MAIN_CONTROL_GAME;
1832
1833     // handle pressed/unpressed state for active/inactive menu buttons
1834     // (if pos != -1, "i" contains index position corresponding to "pos")
1835     if (button &&
1836         pos >= MAIN_CONTROL_NAME && pos <= MAIN_CONTROL_QUIT &&
1837         insideMenuPosRect(main_controls[i].pos_button, mx - mSX, my - mSY))
1838       button_pressed = TRUE;
1839
1840     if (button_pressed != button_pressed_last)
1841     {
1842       DrawCursorAndText_Main(choice, TRUE, button_pressed);
1843
1844       if (button_pressed)
1845         PlaySound(SND_MENU_BUTTON_PRESSING);
1846       else
1847         PlaySound(SND_MENU_BUTTON_RELEASING);
1848     }
1849   }
1850   else if (dx || dy)    /* keyboard input */
1851   {
1852     if (dx > 0 && (choice == MAIN_CONTROL_INFO ||
1853                    choice == MAIN_CONTROL_SETUP))
1854       button = MB_MENU_CHOICE;
1855     else if (dy)
1856       pos = choice + dy;
1857   }
1858
1859   if (pos == MAIN_CONTROL_FIRST_LEVEL && !button)
1860   {
1861     HandleMainMenu_SelectLevel(MAX_LEVELS, -1, NO_DIRECT_LEVEL_SELECT);
1862   }
1863   else if (pos == MAIN_CONTROL_LAST_LEVEL && !button)
1864   {
1865     HandleMainMenu_SelectLevel(MAX_LEVELS, +1, NO_DIRECT_LEVEL_SELECT);
1866   }
1867   else if (pos == MAIN_CONTROL_LEVEL_NUMBER && !button)
1868   {
1869     CloseDoor(DOOR_CLOSE_2);
1870
1871     SetGameStatus(GAME_MODE_LEVELNR);
1872
1873     DrawChooseLevelNr();
1874   }
1875   else if (pos >= MAIN_CONTROL_NAME && pos <= MAIN_CONTROL_QUIT)
1876   {
1877     if (button)
1878     {
1879       if (pos != choice)
1880       {
1881         PlaySound(SND_MENU_ITEM_ACTIVATING);
1882
1883         DrawCursorAndText_Main(choice, FALSE, FALSE);
1884         DrawCursorAndText_Main(pos, TRUE, button_pressed);
1885
1886         choice = pos;
1887       }
1888       else if (dx != 0)
1889       {
1890         if (choice != MAIN_CONTROL_INFO &&
1891             choice != MAIN_CONTROL_SETUP)
1892           HandleMainMenu_SelectLevel(1, dx, NO_DIRECT_LEVEL_SELECT);
1893       }
1894     }
1895     else
1896     {
1897       PlaySound(SND_MENU_ITEM_SELECTING);
1898
1899       if (pos == MAIN_CONTROL_NAME)
1900       {
1901         SetGameStatus(GAME_MODE_PSEUDO_TYPENAME);
1902
1903         HandleTypeName(strlen(setup.player_name), 0);
1904       }
1905       else if (pos == MAIN_CONTROL_LEVELS)
1906       {
1907         if (leveldir_first)
1908         {
1909           CloseDoor(DOOR_CLOSE_2);
1910
1911           SetGameStatus(GAME_MODE_LEVELS);
1912
1913           SaveLevelSetup_LastSeries();
1914           SaveLevelSetup_SeriesInfo();
1915
1916           if (setup.internal.choose_from_top_leveldir)
1917             gotoTopLevelDir();
1918
1919           DrawChooseLevelSet();
1920         }
1921       }
1922       else if (pos == MAIN_CONTROL_SCORES)
1923       {
1924         CloseDoor(DOOR_CLOSE_2);
1925
1926         SetGameStatus(GAME_MODE_SCORES);
1927
1928         DrawHallOfFame(-1);
1929       }
1930       else if (pos == MAIN_CONTROL_EDITOR)
1931       {
1932         if (leveldir_current->readonly &&
1933             !strEqual(setup.player_name, "Artsoft"))
1934           Request("This level is read only!", REQ_CONFIRM);
1935
1936         CloseDoor(DOOR_CLOSE_2);
1937
1938         SetGameStatus(GAME_MODE_EDITOR);
1939
1940         FadeSetEnterScreen();
1941
1942         DrawLevelEd();
1943       }
1944       else if (pos == MAIN_CONTROL_INFO)
1945       {
1946         CloseDoor(DOOR_CLOSE_2);
1947
1948         SetGameStatus(GAME_MODE_INFO);
1949
1950         info_mode = INFO_MODE_MAIN;
1951
1952         DrawInfoScreen();
1953       }
1954       else if (pos == MAIN_CONTROL_GAME)
1955       {
1956         StartGameActions(options.network, setup.autorecord, level.random_seed);
1957       }
1958       else if (pos == MAIN_CONTROL_SETUP)
1959       {
1960         CloseDoor(DOOR_CLOSE_2);
1961
1962         SetGameStatus(GAME_MODE_SETUP);
1963
1964         setup_mode = SETUP_MODE_MAIN;
1965
1966         DrawSetupScreen();
1967       }
1968       else if (pos == MAIN_CONTROL_QUIT)
1969       {
1970         SaveLevelSetup_LastSeries();
1971         SaveLevelSetup_SeriesInfo();
1972
1973         if (Request("Do you really want to quit?", REQ_ASK | REQ_STAY_CLOSED))
1974           SetGameStatus(GAME_MODE_QUIT);
1975       }
1976     }
1977   }
1978
1979   button_pressed_last = button_pressed;
1980 }
1981
1982
1983 /* ========================================================================= */
1984 /* info screen functions                                                     */
1985 /* ========================================================================= */
1986
1987 static struct TokenInfo *info_info;
1988 static int num_info_info;       /* number of info entries shown on screen */
1989 static int max_info_info;       /* total number of info entries in list */
1990
1991 static void execInfoTitleScreen()
1992 {
1993   info_mode = INFO_MODE_TITLE;
1994
1995   DrawInfoScreen();
1996 }
1997
1998 static void execInfoElements()
1999 {
2000   info_mode = INFO_MODE_ELEMENTS;
2001
2002   DrawInfoScreen();
2003 }
2004
2005 static void execInfoMusic()
2006 {
2007   info_mode = INFO_MODE_MUSIC;
2008
2009   DrawInfoScreen();
2010 }
2011
2012 static void execInfoCredits()
2013 {
2014   info_mode = INFO_MODE_CREDITS;
2015
2016   DrawInfoScreen();
2017 }
2018
2019 static void execInfoProgram()
2020 {
2021   info_mode = INFO_MODE_PROGRAM;
2022
2023   DrawInfoScreen();
2024 }
2025
2026 static void execInfoVersion()
2027 {
2028   info_mode = INFO_MODE_VERSION;
2029
2030   DrawInfoScreen();
2031 }
2032
2033 static void execInfoLevelSet()
2034 {
2035   info_mode = INFO_MODE_LEVELSET;
2036
2037   DrawInfoScreen();
2038 }
2039
2040 static void execExitInfo()
2041 {
2042   SetGameStatus(GAME_MODE_MAIN);
2043
2044   DrawMainMenu();
2045 }
2046
2047 static struct TokenInfo info_info_main[] =
2048 {
2049   { TYPE_ENTER_SCREEN,  execInfoTitleScreen,    "Title Screen"          },
2050   { TYPE_ENTER_SCREEN,  execInfoElements,       "Elements Info"         },
2051   { TYPE_ENTER_SCREEN,  execInfoMusic,          "Music Info"            },
2052   { TYPE_ENTER_SCREEN,  execInfoCredits,        "Credits"               },
2053   { TYPE_ENTER_SCREEN,  execInfoProgram,        "Program Info"          },
2054   { TYPE_ENTER_SCREEN,  execInfoVersion,        "Version Info"          },
2055   { TYPE_ENTER_SCREEN,  execInfoLevelSet,       "Level Set Info"        },
2056   { TYPE_EMPTY,         NULL,                   ""                      },
2057   { TYPE_LEAVE_MENU,    execExitInfo,           "Exit"                  },
2058
2059   { 0,                  NULL,                   NULL                    }
2060 };
2061
2062 static int getMenuTextFont(int type)
2063 {
2064   if (type & (TYPE_SWITCH       |
2065               TYPE_YES_NO       |
2066               TYPE_YES_NO_AUTO  |
2067               TYPE_STRING       |
2068               TYPE_ECS_AGA      |
2069               TYPE_KEYTEXT      |
2070               TYPE_ENTER_LIST))
2071     return FONT_MENU_2;
2072   else
2073     return FONT_MENU_1;
2074 }
2075
2076 static struct TokenInfo *setup_info;
2077 static struct TokenInfo setup_info_input[];
2078
2079 static struct TokenInfo *menu_info;
2080
2081 static void DrawCursorAndText_Menu_Ext(struct TokenInfo *token_info,
2082                                        int screen_pos, int menu_info_pos_raw,
2083                                        boolean active)
2084 {
2085   int pos = (menu_info_pos_raw < 0 ? screen_pos : menu_info_pos_raw);
2086   struct TokenInfo *ti = &token_info[pos];
2087   int xpos = MENU_SCREEN_START_XPOS;
2088   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
2089   int font_nr = getMenuTextFont(ti->type);
2090
2091   if (token_info == setup_info_input)
2092     font_nr = FONT_MENU_1;
2093
2094   if (active)
2095     font_nr = FONT_ACTIVE(font_nr);
2096
2097   DrawText(mSX + xpos * 32, mSY + ypos * 32, ti->text, font_nr);
2098
2099   if (ti->type & ~TYPE_SKIP_ENTRY)
2100     drawCursor(screen_pos, active);
2101 }
2102
2103 static void DrawCursorAndText_Menu(int screen_pos, int menu_info_pos_raw,
2104                                    boolean active)
2105 {
2106   DrawCursorAndText_Menu_Ext(menu_info, screen_pos, menu_info_pos_raw, active);
2107 }
2108
2109 static void DrawCursorAndText_Setup(int screen_pos, int menu_info_pos_raw,
2110                                     boolean active)
2111 {
2112   DrawCursorAndText_Menu_Ext(setup_info, screen_pos, menu_info_pos_raw, active);
2113 }
2114
2115 static char *window_size_text;
2116 static char *scaling_type_text;
2117
2118 static void drawSetupValue(int, int);
2119
2120 static void drawMenuInfoList(int first_entry, int num_page_entries,
2121                              int max_page_entries)
2122 {
2123   int i;
2124
2125   if (first_entry + num_page_entries > max_page_entries)
2126     first_entry = 0;
2127
2128   clearMenuListArea();
2129
2130   for (i = 0; i < num_page_entries; i++)
2131   {
2132     int menu_info_pos = first_entry + i;
2133     struct TokenInfo *si = &menu_info[menu_info_pos];
2134     void *value_ptr = si->value;
2135
2136     /* set some entries to "unchangeable" according to other variables */
2137     if ((value_ptr == &setup.sound_simple && !audio.sound_available) ||
2138         (value_ptr == &setup.sound_loops  && !audio.loops_available) ||
2139         (value_ptr == &setup.sound_music  && !audio.music_available) ||
2140         (value_ptr == &setup.fullscreen   && !video.fullscreen_available) ||
2141         (value_ptr == &window_size_text   && !video.window_scaling_available) ||
2142         (value_ptr == &scaling_type_text  && !video.window_scaling_available))
2143       si->type |= TYPE_GHOSTED;
2144
2145     if (si->type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
2146       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
2147     else if (si->type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
2148       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
2149     else if (si->type & ~TYPE_SKIP_ENTRY)
2150       initCursor(i, IMG_MENU_BUTTON);
2151
2152     DrawCursorAndText_Menu(i, menu_info_pos, FALSE);
2153
2154     if (si->type & TYPE_VALUE &&
2155         menu_info == setup_info)
2156       drawSetupValue(i, menu_info_pos);
2157   }
2158 }
2159
2160 static void DrawInfoScreen_Main()
2161 {
2162   int fade_mask = REDRAW_FIELD;
2163   int i;
2164
2165   if (redraw_mask & REDRAW_ALL)
2166     fade_mask = REDRAW_ALL;
2167
2168   if (CheckIfGlobalBorderHasChanged())
2169     fade_mask = REDRAW_ALL;
2170
2171   UnmapAllGadgets();
2172   FadeMenuSoundsAndMusic();
2173
2174   FreeScreenGadgets();
2175   CreateScreenGadgets();
2176
2177   /* (needed after displaying title screens which disable auto repeat) */
2178   KeyboardAutoRepeatOn();
2179
2180   FadeSetLeaveScreen();
2181
2182   FadeOut(fade_mask);
2183
2184   /* needed if different viewport properties defined for info screen */
2185   ChangeViewportPropertiesIfNeeded();
2186
2187   SetMainBackgroundImage(IMG_BACKGROUND_INFO);
2188
2189   ClearField();
2190
2191   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
2192
2193   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Info Screen");
2194
2195   info_info = info_info_main;
2196
2197   // determine maximal number of info entries that can be displayed on screen
2198   num_info_info = 0;
2199   for (i = 0; info_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
2200     num_info_info++;
2201
2202   // determine maximal number of info entries available for menu of info screen
2203   max_info_info = 0;
2204   for (i = 0; info_info[i].type != 0; i++)
2205     max_info_info++;
2206
2207   HandleInfoScreen_Main(0, 0, 0, 0, MB_MENU_INITIALIZE);
2208
2209   MapScreenGadgets(max_info_info);
2210
2211   PlayMenuSoundsAndMusic();
2212
2213   DrawMaskedBorder(fade_mask);
2214
2215   FadeIn(fade_mask);
2216 }
2217
2218 static void changeSetupValue(int, int, int);
2219
2220 void HandleMenuScreen(int mx, int my, int dx, int dy, int button,
2221                       int mode, int num_page_entries, int max_page_entries)
2222 {
2223   static int num_page_entries_all_last[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2224   static int choice_stores[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2225   static int first_entry_stores[NUM_SPECIAL_GFX_ARGS][MAX_MENU_MODES];
2226   int *num_page_entries_last = num_page_entries_all_last[game_status];
2227   int *choice_store = choice_stores[game_status];
2228   int *first_entry_store = first_entry_stores[game_status];
2229   int choice = choice_store[mode];              /* starts with 0 */
2230   int first_entry = first_entry_store[mode];    /* starts with 0 */
2231   int x = 0;
2232   int y = choice - first_entry;
2233   int y_old = y;
2234   boolean position_set_by_scrollbar = (dx == 999);
2235   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
2236   int i;
2237
2238   if (button == MB_MENU_INITIALIZE)
2239   {
2240     // check if number of menu page entries has changed (may happen by change
2241     // of custom artwork definition value for 'list_size' for this menu screen)
2242     // (in this case, the last menu position most probably has to be corrected)
2243     if (num_page_entries != num_page_entries_last[mode])
2244     {
2245       choice_store[mode] = first_entry_store[mode] = 0;
2246
2247       choice = first_entry = 0;
2248       y = y_old = 0;
2249
2250       num_page_entries_last[mode] = num_page_entries;
2251     }
2252
2253     /* advance to first valid menu entry */
2254     while (choice < num_page_entries &&
2255            menu_info[choice].type & TYPE_SKIP_ENTRY)
2256       choice++;
2257
2258     if (position_set_by_scrollbar)
2259       first_entry = first_entry_store[mode] = dy;
2260     else
2261       AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2262                       NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2263
2264     drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2265
2266     if (choice < first_entry)
2267     {
2268       choice = first_entry;
2269
2270       if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2271         choice++;
2272     }
2273     else if (choice > first_entry + num_page_entries - 1)
2274     {
2275       choice = first_entry + num_page_entries - 1;
2276
2277       if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2278         choice--;
2279     }
2280
2281     choice_store[mode] = choice;
2282
2283     DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2284
2285     return;
2286   }
2287   else if (button == MB_MENU_LEAVE)
2288   {
2289     PlaySound(SND_MENU_ITEM_SELECTING);
2290
2291     for (i = 0; i < max_page_entries; i++)
2292     {
2293       if (menu_info[i].type & TYPE_LEAVE_MENU)
2294       {
2295         void (*menu_callback_function)(void) = menu_info[i].value;
2296
2297         FadeSetLeaveMenu();
2298
2299         menu_callback_function();
2300
2301         break;  /* absolutely needed because function changes 'menu_info'! */
2302       }
2303     }
2304
2305     return;
2306   }
2307
2308   if (mx || my)         /* mouse input */
2309   {
2310     x = (mx - mSX) / 32;
2311     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
2312   }
2313   else if (dx || dy)    /* keyboard or scrollbar/scrollbutton input */
2314   {
2315     /* move cursor instead of scrolling when already at start/end of list */
2316     if (dy == -1 * SCROLL_LINE && first_entry == 0)
2317       dy = -1;
2318     else if (dy == +1 * SCROLL_LINE &&
2319              first_entry + num_page_entries == max_page_entries)
2320       dy = 1;
2321
2322     /* handle scrolling screen one line or page */
2323     if (y + dy < 0 ||
2324         y + dy > num_page_entries - 1)
2325     {
2326       boolean redraw = FALSE;
2327
2328       if (ABS(dy) == SCROLL_PAGE)
2329         step = num_page_entries - 1;
2330
2331       if (dy < 0 && first_entry > 0)
2332       {
2333         /* scroll page/line up */
2334
2335         first_entry -= step;
2336         if (first_entry < 0)
2337           first_entry = 0;
2338
2339         redraw = TRUE;
2340       }
2341       else if (dy > 0 && first_entry + num_page_entries < max_page_entries)
2342       {
2343         /* scroll page/line down */
2344
2345         first_entry += step;
2346         if (first_entry + num_page_entries > max_page_entries)
2347           first_entry = MAX(0, max_page_entries - num_page_entries);
2348
2349         redraw = TRUE;
2350       }
2351
2352       if (redraw)
2353       {
2354         choice += first_entry - first_entry_store[mode];
2355
2356         if (choice < first_entry)
2357         {
2358           choice = first_entry;
2359
2360           if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2361             choice++;
2362         }
2363         else if (choice > first_entry + num_page_entries - 1)
2364         {
2365           choice = first_entry + num_page_entries - 1;
2366
2367           if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2368             choice--;
2369         }
2370         else if (menu_info[choice].type & TYPE_SKIP_ENTRY)
2371         {
2372           choice += SIGN(dy);
2373
2374           if (choice < first_entry ||
2375               choice > first_entry + num_page_entries - 1)
2376           first_entry += SIGN(dy);
2377         }
2378
2379         first_entry_store[mode] = first_entry;
2380         choice_store[mode] = choice;
2381
2382         drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2383
2384         DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2385
2386         AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2387                         NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2388       }
2389
2390       return;
2391     }
2392
2393     if (dx)
2394     {
2395       int menu_navigation_type = (dx < 0 ? TYPE_LEAVE : TYPE_ENTER);
2396
2397       if (menu_info[choice].type & menu_navigation_type ||
2398           menu_info[choice].type & TYPE_BOOLEAN_STYLE ||
2399           menu_info[choice].type & TYPE_YES_NO_AUTO)
2400         button = MB_MENU_CHOICE;
2401     }
2402     else if (dy)
2403       y += dy;
2404
2405     /* jump to next non-empty menu entry (up or down) */
2406     while (first_entry + y > 0 &&
2407            first_entry + y < max_page_entries - 1 &&
2408            menu_info[first_entry + y].type & TYPE_SKIP_ENTRY)
2409       y += dy;
2410
2411     if (!IN_VIS_MENU(x, y))
2412     {
2413       choice += y - y_old;
2414
2415       if (choice < first_entry)
2416         first_entry = choice;
2417       else if (choice > first_entry + num_page_entries - 1)
2418         first_entry = choice - num_page_entries + 1;
2419
2420       if (first_entry >= 0 &&
2421           first_entry + num_page_entries <= max_page_entries)
2422       {
2423         first_entry_store[mode] = first_entry;
2424
2425         if (choice < first_entry)
2426           choice = first_entry;
2427         else if (choice > first_entry + num_page_entries - 1)
2428           choice = first_entry + num_page_entries - 1;
2429
2430         choice_store[mode] = choice;
2431
2432         drawMenuInfoList(first_entry, num_page_entries, max_page_entries);
2433
2434         DrawCursorAndText_Menu(choice - first_entry, choice, TRUE);
2435
2436         AdjustScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL, max_page_entries,
2437                         NUM_MENU_ENTRIES_ON_SCREEN, first_entry);
2438       }
2439
2440       return;
2441     }
2442   }
2443
2444   if (!anyScrollbarGadgetActive() &&
2445       IN_VIS_MENU(x, y) &&
2446       mx < screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x &&
2447       y >= 0 && y < num_page_entries)
2448   {
2449     if (button)
2450     {
2451       if (first_entry + y != choice &&
2452           menu_info[first_entry + y].type & ~TYPE_SKIP_ENTRY)
2453       {
2454         PlaySound(SND_MENU_ITEM_ACTIVATING);
2455
2456         DrawCursorAndText_Menu(choice - first_entry, choice, FALSE);
2457         DrawCursorAndText_Menu(y, first_entry + y, TRUE);
2458
2459         choice = choice_store[mode] = first_entry + y;
2460       }
2461       else if (dx < 0)
2462       {
2463         PlaySound(SND_MENU_ITEM_SELECTING);
2464
2465         for (i = 0; menu_info[i].type != 0; i++)
2466         {
2467           if (menu_info[i].type & TYPE_LEAVE_MENU)
2468           {
2469             void (*menu_callback_function)(void) = menu_info[i].value;
2470
2471             FadeSetLeaveMenu();
2472
2473             menu_callback_function();
2474
2475             /* absolutely needed because function changes 'menu_info'! */
2476             break;
2477           }
2478         }
2479
2480         return;
2481       }
2482     }
2483     else if (!(menu_info[first_entry + y].type & TYPE_GHOSTED))
2484     {
2485       PlaySound(SND_MENU_ITEM_SELECTING);
2486
2487       /* when selecting key headline, execute function for key value change */
2488       if (menu_info[first_entry + y].type & TYPE_KEYTEXT &&
2489           menu_info[first_entry + y + 1].type & TYPE_KEY)
2490         y++;
2491
2492       /* when selecting string value, execute function for list selection */
2493       if (menu_info[first_entry + y].type & TYPE_STRING && y > 0 &&
2494           menu_info[first_entry + y - 1].type & TYPE_ENTER_LIST)
2495         y--;
2496
2497       if (menu_info[first_entry + y].type & TYPE_ENTER_OR_LEAVE)
2498       {
2499         void (*menu_callback_function)(void) =
2500           menu_info[first_entry + y].value;
2501
2502         FadeSetFromType(menu_info[first_entry + y].type);
2503
2504         menu_callback_function();
2505       }
2506       else if (menu_info[first_entry + y].type & TYPE_VALUE &&
2507                menu_info == setup_info)
2508       {
2509         changeSetupValue(y, first_entry + y, dx);
2510       }
2511     }
2512   }
2513 }
2514
2515 void HandleInfoScreen_Main(int mx, int my, int dx, int dy, int button)
2516 {
2517   menu_info = info_info;
2518
2519   HandleMenuScreen(mx, my, dx, dy, button,
2520                    info_mode, num_info_info, max_info_info);
2521 }
2522
2523 void DrawInfoScreen_NotAvailable(char *text_title, char *text_error)
2524 {
2525   int ystart1 = mSY - SY + 100;
2526   int ystart2 = mSY - SY + 150;
2527   int ybottom = mSY - SY + SYSIZE - 20;
2528
2529   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO);
2530
2531   FadeOut(REDRAW_FIELD);
2532
2533   ClearField();
2534   DrawHeadline();
2535
2536   DrawTextSCentered(ystart1, FONT_TEXT_1, text_title);
2537   DrawTextSCentered(ystart2, FONT_TEXT_2, text_error);
2538
2539   DrawTextSCentered(ybottom, FONT_TEXT_4,
2540                     "Press any key or button for info menu");
2541
2542   FadeIn(REDRAW_FIELD);
2543 }
2544
2545 void DrawInfoScreen_HelpAnim(int start, int max_anims, boolean init)
2546 {
2547   static int infoscreen_step[MAX_INFO_ELEMENTS_ON_SCREEN];
2548   static int infoscreen_frame[MAX_INFO_ELEMENTS_ON_SCREEN];
2549   int xstart = mSX + MENU_SCREEN_INFO_XSTART;
2550   int ystart1 = mSY - SY + MENU_SCREEN_INFO_YSTART1;
2551   int ystart2 = mSY + MENU_SCREEN_INFO_YSTART2;
2552   int ybottom = mSY - SY + MENU_SCREEN_INFO_YBOTTOM;
2553   int ystep = MENU_SCREEN_INFO_YSTEP;
2554   int element, action, direction;
2555   int graphic;
2556   int delay;
2557   int sync_frame;
2558   int i, j;
2559
2560   if (init)
2561   {
2562     for (i = 0; i < NUM_INFO_ELEMENTS_ON_SCREEN; i++)
2563       infoscreen_step[i] = infoscreen_frame[i] = 0;
2564
2565     ClearField();
2566     DrawHeadline();
2567
2568     DrawTextSCentered(ystart1, FONT_TEXT_1, "The Game Elements:");
2569
2570     DrawTextSCentered(ybottom, FONT_TEXT_4,
2571                       "Press any key or button for next page");
2572
2573     FrameCounter = 0;
2574   }
2575
2576   i = j = 0;
2577   while (helpanim_info[j].element != HELPANIM_LIST_END)
2578   {
2579     if (i >= start + NUM_INFO_ELEMENTS_ON_SCREEN ||
2580         i >= max_anims)
2581       break;
2582     else if (i < start)
2583     {
2584       while (helpanim_info[j].element != HELPANIM_LIST_NEXT)
2585         j++;
2586
2587       j++;
2588       i++;
2589
2590       continue;
2591     }
2592
2593     j += infoscreen_step[i - start];
2594
2595     element = helpanim_info[j].element;
2596     action = helpanim_info[j].action;
2597     direction = helpanim_info[j].direction;
2598
2599     if (element < 0)
2600       element = EL_UNKNOWN;
2601
2602     if (action != -1 && direction != -1)
2603       graphic = el_act_dir2img(element, action, direction);
2604     else if (action != -1)
2605       graphic = el_act2img(element, action);
2606     else if (direction != -1)
2607       graphic = el_dir2img(element, direction);
2608     else
2609       graphic = el2img(element);
2610
2611     delay = helpanim_info[j++].delay;
2612
2613     if (delay == -1)
2614       delay = 1000000;
2615
2616     if (infoscreen_frame[i - start] == 0)
2617     {
2618       sync_frame = 0;
2619       infoscreen_frame[i - start] = delay - 1;
2620     }
2621     else
2622     {
2623       sync_frame = delay - infoscreen_frame[i - start];
2624       infoscreen_frame[i - start]--;
2625     }
2626
2627     if (helpanim_info[j].element == HELPANIM_LIST_NEXT)
2628     {
2629       if (!infoscreen_frame[i - start])
2630         infoscreen_step[i - start] = 0;
2631     }
2632     else
2633     {
2634       if (!infoscreen_frame[i - start])
2635         infoscreen_step[i - start]++;
2636       while (helpanim_info[j].element != HELPANIM_LIST_NEXT)
2637         j++;
2638     }
2639
2640     j++;
2641
2642     ClearRectangleOnBackground(drawto, xstart, ystart2 + (i - start) * ystep,
2643                                TILEX, TILEY);
2644     DrawFixedGraphicAnimationExt(drawto, xstart, ystart2 + (i - start) * ystep,
2645                                  graphic, sync_frame, USE_MASKING);
2646
2647     if (init)
2648       DrawInfoScreen_HelpText(element, action, direction, i - start);
2649
2650     i++;
2651   }
2652
2653   redraw_mask |= REDRAW_FIELD;
2654
2655   FrameCounter++;
2656 }
2657
2658 static char *getHelpText(int element, int action, int direction)
2659 {
2660   char token[MAX_LINE_LEN];
2661
2662   strcpy(token, element_info[element].token_name);
2663
2664   if (action != -1)
2665     strcat(token, element_action_info[action].suffix);
2666
2667   if (direction != -1)
2668     strcat(token, element_direction_info[MV_DIR_TO_BIT(direction)].suffix);
2669
2670   return getHashEntry(helptext_info, token);
2671 }
2672
2673 void DrawInfoScreen_HelpText(int element, int action, int direction, int ypos)
2674 {
2675   int font_nr = FONT_INFO_ELEMENTS;
2676   int font_width = getFontWidth(font_nr);
2677   int sx = mSX + MINI_TILEX + TILEX + MINI_TILEX;
2678   int sy = mSY + 65 + 2 * 32 + 1;
2679   int ystep = TILEY + 4;
2680   int pad_x = sx - SX;
2681   int max_chars_per_line = (SXSIZE - pad_x - MINI_TILEX) / font_width;
2682   int max_lines_per_text = 2;    
2683   char *text = NULL;
2684
2685   if (action != -1 && direction != -1)          /* element.action.direction */
2686     text = getHelpText(element, action, direction);
2687
2688   if (text == NULL && action != -1)             /* element.action */
2689     text = getHelpText(element, action, -1);
2690
2691   if (text == NULL && direction != -1)          /* element.direction */
2692     text = getHelpText(element, -1, direction);
2693
2694   if (text == NULL)                             /* base element */
2695     text = getHelpText(element, -1, -1);
2696
2697   if (text == NULL)                             /* not found */
2698     text = "No description available";
2699
2700   if (strlen(text) <= max_chars_per_line)       /* only one line of text */
2701     sy += getFontHeight(font_nr) / 2;
2702
2703   DrawTextBuffer(sx, sy + ypos * ystep, text, font_nr,
2704                  max_chars_per_line, -1, max_lines_per_text, 0, -1,
2705                  TRUE, FALSE, FALSE);
2706 }
2707
2708 void DrawInfoScreen_TitleScreen()
2709 {
2710   SetGameStatus(GAME_MODE_TITLE);
2711
2712   DrawTitleScreen();
2713 }
2714
2715 void HandleInfoScreen_TitleScreen(int button)
2716 {
2717   HandleTitleScreen(0, 0, 0, 0, button);
2718 }
2719
2720 void DrawInfoScreen_Elements()
2721 {
2722   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_ELEMENTS);
2723
2724   FadeOut(REDRAW_FIELD);
2725
2726   LoadHelpAnimInfo();
2727   LoadHelpTextInfo();
2728
2729   HandleInfoScreen_Elements(MB_MENU_INITIALIZE);
2730
2731   FadeIn(REDRAW_FIELD);
2732 }
2733
2734 void HandleInfoScreen_Elements(int button)
2735 {
2736   static unsigned int info_delay = 0;
2737   static int num_anims;
2738   static int num_pages;
2739   static int page;
2740   int anims_per_page = NUM_INFO_ELEMENTS_ON_SCREEN;
2741   int i;
2742
2743   if (button == MB_MENU_INITIALIZE)
2744   {
2745     boolean new_element = TRUE;
2746
2747     num_anims = 0;
2748
2749     for (i = 0; helpanim_info[i].element != HELPANIM_LIST_END; i++)
2750     {
2751       if (helpanim_info[i].element == HELPANIM_LIST_NEXT)
2752         new_element = TRUE;
2753       else if (new_element)
2754       {
2755         num_anims++;
2756         new_element = FALSE;
2757       }
2758     }
2759
2760     num_pages = (num_anims + anims_per_page - 1) / anims_per_page;
2761     page = 0;
2762   }
2763
2764   if (button == MB_MENU_LEAVE)
2765   {
2766     PlaySound(SND_MENU_ITEM_SELECTING);
2767
2768     info_mode = INFO_MODE_MAIN;
2769     DrawInfoScreen();
2770
2771     return;
2772   }
2773   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
2774   {
2775     if (button != MB_MENU_INITIALIZE)
2776     {
2777       PlaySound(SND_MENU_ITEM_SELECTING);
2778
2779       page++;
2780     }
2781
2782     if (page >= num_pages)
2783     {
2784       FadeMenuSoundsAndMusic();
2785
2786       info_mode = INFO_MODE_MAIN;
2787       DrawInfoScreen();
2788
2789       return;
2790     }
2791
2792     if (page > 0)
2793       FadeSetNextScreen();
2794
2795     if (button != MB_MENU_INITIALIZE)
2796       FadeOut(REDRAW_FIELD);
2797
2798     DrawInfoScreen_HelpAnim(page * anims_per_page, num_anims, TRUE);
2799
2800     if (button != MB_MENU_INITIALIZE)
2801       FadeIn(REDRAW_FIELD);
2802   }
2803   else
2804   {
2805     if (DelayReached(&info_delay, GameFrameDelay))
2806       if (page < num_pages)
2807         DrawInfoScreen_HelpAnim(page * anims_per_page, num_anims, FALSE);
2808
2809     PlayMenuSoundIfLoop();
2810   }
2811 }
2812
2813 void DrawInfoScreen_Music()
2814 {
2815   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_MUSIC);
2816
2817   FadeOut(REDRAW_FIELD);
2818
2819   ClearField();
2820   DrawHeadline();
2821
2822   LoadMusicInfo();
2823
2824   HandleInfoScreen_Music(MB_MENU_INITIALIZE);
2825
2826   FadeIn(REDRAW_FIELD);
2827 }
2828
2829 void HandleInfoScreen_Music(int button)
2830 {
2831   static struct MusicFileInfo *list = NULL;
2832   int ystart1 = mSY - SY + 100;
2833   int ystart2 = mSY - SY + 150;
2834   int ybottom = mSY - SY + SYSIZE - 20;
2835   int dy = 30;
2836
2837   if (button == MB_MENU_INITIALIZE)
2838   {
2839     list = music_file_info;
2840
2841     if (list == NULL)
2842     {
2843       FadeMenuSoundsAndMusic();
2844
2845       ClearField();
2846       DrawHeadline();
2847
2848       DrawTextSCentered(ystart1, FONT_TEXT_1,
2849                         "No music info for this level set.");
2850
2851       DrawTextSCentered(ybottom, FONT_TEXT_4,
2852                         "Press any key or button for info menu");
2853
2854       return;
2855     }
2856   }
2857
2858   if (button == MB_MENU_LEAVE)
2859   {
2860     PlaySound(SND_MENU_ITEM_SELECTING);
2861
2862     FadeMenuSoundsAndMusic();
2863
2864     info_mode = INFO_MODE_MAIN;
2865     DrawInfoScreen();
2866
2867     return;
2868   }
2869   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
2870   {
2871     int y = 0;
2872
2873     if (button != MB_MENU_INITIALIZE)
2874     {
2875       PlaySound(SND_MENU_ITEM_SELECTING);
2876
2877       if (list != NULL)
2878         list = list->next;
2879     }
2880
2881     if (list == NULL)
2882     {
2883       FadeMenuSoundsAndMusic();
2884
2885       info_mode = INFO_MODE_MAIN;
2886       DrawInfoScreen();
2887
2888       return;
2889     }
2890
2891     FadeMenuSoundsAndMusic();
2892
2893     if (list != music_file_info)
2894       FadeSetNextScreen();
2895
2896     if (button != MB_MENU_INITIALIZE)
2897       FadeOut(REDRAW_FIELD);
2898
2899     ClearField();
2900     DrawHeadline();
2901
2902     if (list->is_sound)
2903     {
2904       int sound = list->music;
2905
2906       if (sound_info[sound].loop)
2907         PlaySoundLoop(sound);
2908       else
2909         PlaySound(sound);
2910
2911       DrawTextSCentered(ystart1, FONT_TEXT_1, "The Game Background Sounds:");
2912     }
2913     else
2914     {
2915       PlayMusic(list->music);
2916
2917       DrawTextSCentered(ystart1, FONT_TEXT_1, "The Game Background Music:");
2918     }
2919
2920     if (!strEqual(list->title, UNKNOWN_NAME))
2921     {
2922       if (!strEqual(list->title_header, UNKNOWN_NAME))
2923         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->title_header);
2924
2925       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "\"%s\"", list->title);
2926     }
2927
2928     if (!strEqual(list->artist, UNKNOWN_NAME))
2929     {
2930       if (!strEqual(list->artist_header, UNKNOWN_NAME))
2931         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->artist_header);
2932       else
2933         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, "by");
2934
2935       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "%s", list->artist);
2936     }
2937
2938     if (!strEqual(list->album, UNKNOWN_NAME))
2939     {
2940       if (!strEqual(list->album_header, UNKNOWN_NAME))
2941         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->album_header);
2942       else
2943         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, "from the album");
2944
2945       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "\"%s\"", list->album);
2946     }
2947
2948     if (!strEqual(list->year, UNKNOWN_NAME))
2949     {
2950       if (!strEqual(list->year_header, UNKNOWN_NAME))
2951         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, list->year_header);
2952       else
2953         DrawTextSCentered(ystart2 + y++ * dy, FONT_TEXT_2, "from the year");
2954
2955       DrawTextFCentered(ystart2 + y++ * dy, FONT_TEXT_3, "%s", list->year);
2956     }
2957
2958     DrawTextSCentered(ybottom, FONT_TEXT_4,
2959                       "Press any key or button for next page");
2960
2961     if (button != MB_MENU_INITIALIZE)
2962       FadeIn(REDRAW_FIELD);
2963   }
2964
2965   if (list != NULL && list->is_sound && sound_info[list->music].loop)
2966     PlaySoundLoop(list->music);
2967 }
2968
2969 static void DrawInfoScreen_CreditsScreen(int screen_nr)
2970 {
2971   int ystart1 = mSY - SY + 100;
2972   int ystart2 = mSY - SY + 150;
2973   int ybottom = mSY - SY + SYSIZE - 20;
2974   int ystep = 30;
2975
2976   ClearField();
2977   DrawHeadline();
2978
2979   DrawTextSCentered(ystart1, FONT_TEXT_1, "Credits:");
2980
2981   if (screen_nr == 0)
2982   {
2983     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
2984                       "Special thanks to");
2985     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
2986                       "Peter Liepa");
2987     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
2988                       "for creating");
2989     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
2990                       "\"Boulder Dash\"");
2991     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
2992                       "in the year");
2993     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
2994                       "1984");
2995     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
2996                       "published by");
2997     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
2998                       "First Star Software");
2999   }
3000   else if (screen_nr == 1)
3001   {
3002     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3003                       "Special thanks to");
3004     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3005                       "Klaus Heinz & Volker Wertich");
3006     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3007                       "for creating");
3008     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3009                       "\"Emerald Mine\"");
3010     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3011                       "in the year");
3012     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3013                       "1987");
3014     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3015                       "published by");
3016     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
3017                       "Kingsoft");
3018   }
3019   else if (screen_nr == 2)
3020   {
3021     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3022                       "Special thanks to");
3023     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3024                       "Michael Stopp & Philip Jespersen");
3025     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3026                       "for creating");
3027     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3028                       "\"Supaplex\"");
3029     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3030                       "in the year");
3031     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3032                       "1991");
3033     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3034                       "published by");
3035     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
3036                       "Digital Integration");
3037   }
3038   else if (screen_nr == 3)
3039   {
3040     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3041                       "Special thanks to");
3042     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3043                       "Hiroyuki Imabayashi");
3044     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3045                       "for creating");
3046     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3047                       "\"Sokoban\"");
3048     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3049                       "in the year");
3050     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3051                       "1982");
3052     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3053                       "published by");
3054     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_3,
3055                       "Thinking Rabbit");
3056   }
3057   else if (screen_nr == 4)
3058   {
3059     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3060                       "Special thanks to");
3061     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3062                       "Alan Bond");
3063     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3064                       "and");
3065     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3066                       "J\xfcrgen Bonhagen");
3067     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3068                       "for the continuous creation");
3069     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_2,
3070                       "of outstanding level sets");
3071   }
3072   else if (screen_nr == 5)
3073   {
3074     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3075                       "Thanks to");
3076     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3077                       "Peter Elzner");
3078     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3079                       "for ideas and inspiration by");
3080     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3081                       "Diamond Caves");
3082
3083     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_2,
3084                       "Thanks to");
3085     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_3,
3086                       "Steffest");
3087     DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_2,
3088                       "for ideas and inspiration by");
3089     DrawTextSCentered(ystart2 + 8 * ystep, FONT_TEXT_3,
3090                       "DX-Boulderdash");
3091   }
3092   else if (screen_nr == 6)
3093   {
3094     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3095                       "Thanks to");
3096     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3097                       "David Tritscher");
3098 #if 1
3099     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3100                       "for the code base used for the");
3101     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_2,
3102                       "native Emerald Mine engine");
3103 #else
3104     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3105                       "for the new Emerald Mine engine");
3106 #endif
3107   }
3108   else if (screen_nr == 7)
3109   {
3110     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3111                       "Thanks to");
3112     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_3,
3113                       "Guido Schulz");
3114     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_2,
3115                       "for the initial DOS port");
3116
3117     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3118                       "Thanks to");
3119     DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3120                       "Karl H\xf6rnell");
3121     DrawTextSCentered(ystart2 + 6 * ystep, FONT_TEXT_2,
3122                       "for some additional toons");
3123   }
3124   else if (screen_nr == 8)
3125   {
3126     DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3127                       "And not to forget:");
3128     DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_2,
3129                       "Many thanks to");
3130     DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_3,
3131                       "All those who contributed");
3132     DrawTextSCentered(ystart2 + 3 * ystep, FONT_TEXT_3,
3133                       "levels to this game");
3134     DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_3,
3135                       "since 1995");
3136   }
3137
3138   DrawTextSCentered(ybottom, FONT_TEXT_4,
3139                     "Press any key or button for next page");
3140 }
3141
3142 void DrawInfoScreen_Credits()
3143 {
3144   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_CREDITS);
3145
3146   FadeMenuSoundsAndMusic();
3147
3148   FadeOut(REDRAW_FIELD);
3149
3150   HandleInfoScreen_Credits(MB_MENU_INITIALIZE);
3151
3152   FadeIn(REDRAW_FIELD);
3153 }
3154
3155 void HandleInfoScreen_Credits(int button)
3156 {
3157   static int screen_nr = 0;
3158   int num_screens = 9;
3159
3160   if (button == MB_MENU_INITIALIZE)
3161   {
3162     screen_nr = 0;
3163
3164     // DrawInfoScreen_CreditsScreen(screen_nr);
3165   }
3166
3167   if (button == MB_MENU_LEAVE)
3168   {
3169     PlaySound(SND_MENU_ITEM_SELECTING);
3170
3171     info_mode = INFO_MODE_MAIN;
3172     DrawInfoScreen();
3173
3174     return;
3175   }
3176   else if (button == MB_MENU_CHOICE || button == MB_MENU_INITIALIZE)
3177   {
3178     if (button != MB_MENU_INITIALIZE)
3179     {
3180       PlaySound(SND_MENU_ITEM_SELECTING);
3181
3182       screen_nr++;
3183     }
3184
3185     if (screen_nr >= num_screens)
3186     {
3187       FadeMenuSoundsAndMusic();
3188
3189       info_mode = INFO_MODE_MAIN;
3190       DrawInfoScreen();
3191
3192       return;
3193     }
3194
3195     if (screen_nr > 0)
3196       FadeSetNextScreen();
3197
3198     if (button != MB_MENU_INITIALIZE)
3199       FadeOut(REDRAW_FIELD);
3200
3201     DrawInfoScreen_CreditsScreen(screen_nr);
3202
3203     if (button != MB_MENU_INITIALIZE)
3204       FadeIn(REDRAW_FIELD);
3205   }
3206   else
3207   {
3208     PlayMenuSoundIfLoop();
3209   }
3210 }
3211
3212 void DrawInfoScreen_Program()
3213 {
3214   int ystart1 = mSY - SY + 100;
3215   int ystart2 = mSY - SY + 150;
3216   int ybottom = mSY - SY + SYSIZE - 20;
3217   int ystep = 30;
3218
3219   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_PROGRAM);
3220
3221   FadeOut(REDRAW_FIELD);
3222
3223   ClearField();
3224   DrawHeadline();
3225
3226   DrawTextSCentered(ystart1, FONT_TEXT_1, "Program Information:");
3227
3228   DrawTextSCentered(ystart2 + 0 * ystep, FONT_TEXT_2,
3229                     "This game is Freeware!");
3230   DrawTextSCentered(ystart2 + 1 * ystep, FONT_TEXT_2,
3231                     "If you like it, send e-mail to:");
3232   DrawTextSCentered(ystart2 + 2 * ystep, FONT_TEXT_3,
3233                     setup.internal.program_email);
3234   DrawTextSCentered(ystart2 + 4 * ystep, FONT_TEXT_2,
3235                     "More information and levels:");
3236   DrawTextSCentered(ystart2 + 5 * ystep, FONT_TEXT_3,
3237                     setup.internal.program_website);
3238   DrawTextSCentered(ystart2 + 7 * ystep, FONT_TEXT_2,
3239                     "If you have created new levels,");
3240   DrawTextSCentered(ystart2 + 8 * ystep, FONT_TEXT_2,
3241                     "send them to me to include them!");
3242   DrawTextSCentered(ystart2 + 9 * ystep, FONT_TEXT_2,
3243                     ":-)");
3244
3245   DrawTextSCentered(ybottom, FONT_TEXT_4,
3246                     "Press any key or button for info menu");
3247
3248   FadeIn(REDRAW_FIELD);
3249 }
3250
3251 void HandleInfoScreen_Program(int button)
3252 {
3253   if (button == MB_MENU_LEAVE)
3254   {
3255     PlaySound(SND_MENU_ITEM_SELECTING);
3256
3257     info_mode = INFO_MODE_MAIN;
3258     DrawInfoScreen();
3259
3260     return;
3261   }
3262   else if (button == MB_MENU_CHOICE)
3263   {
3264     PlaySound(SND_MENU_ITEM_SELECTING);
3265
3266     FadeMenuSoundsAndMusic();
3267
3268     info_mode = INFO_MODE_MAIN;
3269     DrawInfoScreen();
3270   }
3271   else
3272   {
3273     PlayMenuSoundIfLoop();
3274   }
3275 }
3276
3277 void DrawInfoScreen_Version()
3278 {
3279   int font_header = FONT_TEXT_3;
3280   int font_text = FONT_TEXT_2;
3281   int xstep = getFontWidth(font_text);
3282   int ystep = getFontHeight(font_text);
3283   int ystart1 = mSY - SY + 100;
3284   int ystart2 = mSY - SY + 150;
3285   int ybottom = mSY - SY + SYSIZE - 20;
3286   int xstart1 = mSX - SX + 2 * xstep;
3287   int xstart2 = mSX - SX + 18 * xstep;
3288   int xstart3 = mSX - SX + 28 * xstep;
3289   SDL_version sdl_version_compiled;
3290   const SDL_version *sdl_version_linked;
3291   int driver_name_len = 10;
3292 #if defined(TARGET_SDL2)
3293   SDL_version sdl_version_linked_ext;
3294   const char *driver_name = NULL;
3295 #else
3296   char driver_name[driver_name_len];
3297 #endif
3298
3299   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_VERSION);
3300
3301   FadeOut(REDRAW_FIELD);
3302
3303   ClearField();
3304   DrawHeadline();
3305
3306   DrawTextSCentered(ystart1, FONT_TEXT_1, "Version Information:");
3307
3308   DrawTextF(xstart1, ystart2, font_header, "Name");
3309   DrawTextF(xstart2, ystart2, font_text, getProgramTitleString());
3310
3311   ystart2 += ystep;
3312   DrawTextF(xstart1, ystart2, font_header, "Version");
3313   DrawTextF(xstart2, ystart2, font_text, getProgramVersionString());
3314
3315   if (!strEqual(getProgramVersionString(), getProgramRealVersionString()))
3316   {
3317     ystart2 += ystep;
3318     DrawTextF(xstart1, ystart2, font_header, "Version (real)");
3319     DrawTextF(xstart2, ystart2, font_text, getProgramRealVersionString());
3320   }
3321
3322   ystart2 += ystep;
3323   DrawTextF(xstart1, ystart2, font_header, "Platform");
3324   DrawTextF(xstart2, ystart2, font_text, PLATFORM_STRING);
3325
3326   ystart2 += ystep;
3327   DrawTextF(xstart1, ystart2, font_header, "Target");
3328   DrawTextF(xstart2, ystart2, font_text, TARGET_STRING);
3329
3330   ystart2 += ystep;
3331   DrawTextF(xstart1, ystart2, font_header, "Source date");
3332   DrawTextF(xstart2, ystart2, font_text, getSourceDateString());
3333
3334   ystart2 += 3 * ystep;
3335   DrawTextF(xstart1, ystart2, font_header, "Library");
3336   DrawTextF(xstart2, ystart2, font_header, "compiled");
3337   DrawTextF(xstart3, ystart2, font_header, "linked");
3338
3339   SDL_VERSION(&sdl_version_compiled);
3340 #if defined(TARGET_SDL2)
3341   SDL_GetVersion(&sdl_version_linked_ext);
3342   sdl_version_linked = &sdl_version_linked_ext;
3343 #else
3344   sdl_version_linked = SDL_Linked_Version();
3345 #endif
3346
3347   ystart2 += 2 * ystep;
3348   DrawTextF(xstart1, ystart2, font_text, "SDL");
3349   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3350             sdl_version_compiled.major,
3351             sdl_version_compiled.minor,
3352             sdl_version_compiled.patch);
3353   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3354             sdl_version_linked->major,
3355             sdl_version_linked->minor,
3356             sdl_version_linked->patch);
3357
3358   SDL_IMAGE_VERSION(&sdl_version_compiled);
3359   sdl_version_linked = IMG_Linked_Version();
3360
3361   ystart2 += ystep;
3362   DrawTextF(xstart1, ystart2, font_text, "SDL_image");
3363   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3364             sdl_version_compiled.major,
3365             sdl_version_compiled.minor,
3366             sdl_version_compiled.patch);
3367   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3368             sdl_version_linked->major,
3369             sdl_version_linked->minor,
3370             sdl_version_linked->patch);
3371
3372   SDL_MIXER_VERSION(&sdl_version_compiled);
3373   sdl_version_linked = Mix_Linked_Version();
3374
3375   ystart2 += ystep;
3376   DrawTextF(xstart1, ystart2, font_text, "SDL_mixer");
3377   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3378             sdl_version_compiled.major,
3379             sdl_version_compiled.minor,
3380             sdl_version_compiled.patch);
3381   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3382             sdl_version_linked->major,
3383             sdl_version_linked->minor,
3384             sdl_version_linked->patch);
3385
3386   SDL_NET_VERSION(&sdl_version_compiled);
3387   sdl_version_linked = SDLNet_Linked_Version();
3388
3389   ystart2 += ystep;
3390   DrawTextF(xstart1, ystart2, font_text, "SDL_net");
3391   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3392             sdl_version_compiled.major,
3393             sdl_version_compiled.minor,
3394             sdl_version_compiled.patch);
3395   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3396             sdl_version_linked->major,
3397             sdl_version_linked->minor,
3398             sdl_version_linked->patch);
3399
3400   ystart2 += 3 * ystep;
3401   DrawTextF(xstart1, ystart2, font_header, "Driver");
3402   DrawTextF(xstart2, ystart2, font_header, "Requested");
3403   DrawTextF(xstart3, ystart2, font_header, "Used");
3404
3405 #if defined(TARGET_SDL2)
3406   driver_name = getStringCopyNStatic(SDL_GetVideoDriver(0), driver_name_len);
3407 #else
3408   SDL_VideoDriverName(driver_name, driver_name_len);
3409 #endif
3410
3411   ystart2 += 2 * ystep;
3412   DrawTextF(xstart1, ystart2, font_text, "SDL_VideoDriver");
3413   DrawTextF(xstart2, ystart2, font_text, "%s", setup.system.sdl_videodriver);
3414   DrawTextF(xstart3, ystart2, font_text, "%s", driver_name);
3415
3416 #if defined(TARGET_SDL2)
3417   driver_name = getStringCopyNStatic(SDL_GetAudioDriver(0), driver_name_len);
3418 #else
3419   SDL_AudioDriverName(driver_name, driver_name_len);
3420 #endif
3421
3422   ystart2 += ystep;
3423   DrawTextF(xstart1, ystart2, font_text, "SDL_AudioDriver");
3424   DrawTextF(xstart2, ystart2, font_text, "%s", setup.system.sdl_audiodriver);
3425   DrawTextF(xstart3, ystart2, font_text, "%s", driver_name);
3426
3427   DrawTextSCentered(ybottom, FONT_TEXT_4,
3428                     "Press any key or button for info menu");
3429
3430   FadeIn(REDRAW_FIELD);
3431 }
3432
3433 void HandleInfoScreen_Version(int button)
3434 {
3435   if (button == MB_MENU_LEAVE)
3436   {
3437     PlaySound(SND_MENU_ITEM_SELECTING);
3438
3439     info_mode = INFO_MODE_MAIN;
3440     DrawInfoScreen();
3441
3442     return;
3443   }
3444   else if (button == MB_MENU_CHOICE)
3445   {
3446     PlaySound(SND_MENU_ITEM_SELECTING);
3447
3448     FadeMenuSoundsAndMusic();
3449
3450     info_mode = INFO_MODE_MAIN;
3451     DrawInfoScreen();
3452   }
3453   else
3454   {
3455     PlayMenuSoundIfLoop();
3456   }
3457 }
3458
3459 void DrawInfoScreen_LevelSet()
3460 {
3461   struct TitleMessageInfo *tmi = &readme;
3462   char *filename = getLevelSetInfoFilename();
3463   char *title = "Level Set Information:";
3464   int ystart1 = mSY - SY + 100;
3465   int ybottom = mSY - SY + SYSIZE - 20;
3466
3467   if (filename == NULL)
3468   {
3469     DrawInfoScreen_NotAvailable(title, "No information for this level set.");
3470
3471     return;
3472   }
3473
3474   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_LEVELSET);
3475
3476   FadeOut(REDRAW_FIELD);
3477
3478   ClearField();
3479   DrawHeadline();
3480
3481   DrawTextSCentered(ystart1, FONT_TEXT_1, title);
3482
3483   /* if x position set to "-1", automatically determine by playfield width */
3484   if (tmi->x == -1)
3485     tmi->x = SXSIZE / 2;
3486
3487   /* if y position set to "-1", use static default value */
3488   if (tmi->y == -1)
3489     tmi->y = 150;
3490
3491   /* if width set to "-1", automatically determine by playfield width */
3492   if (tmi->width == -1)
3493     tmi->width = SXSIZE - 2 * TILEX;
3494
3495   /* if height set to "-1", automatically determine by playfield height */
3496   if (tmi->height == -1)
3497     tmi->height = SYSIZE - 20 - tmi->y - 10;
3498
3499   /* if chars set to "-1", automatically determine by text and font width */
3500   if (tmi->chars == -1)
3501     tmi->chars = tmi->width / getFontWidth(tmi->font);
3502   else
3503     tmi->width = tmi->chars * getFontWidth(tmi->font);
3504
3505   /* if lines set to "-1", automatically determine by text and font height */
3506   if (tmi->lines == -1)
3507     tmi->lines = tmi->height / getFontHeight(tmi->font);
3508   else
3509     tmi->height = tmi->lines * getFontHeight(tmi->font);
3510
3511   DrawTextFile(mSX + ALIGNED_TEXT_XPOS(tmi), mSY + ALIGNED_TEXT_YPOS(tmi),
3512                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
3513                tmi->autowrap, tmi->centered, tmi->parse_comments);
3514
3515   DrawTextSCentered(ybottom, FONT_TEXT_4,
3516                     "Press any key or button for info menu");
3517
3518   FadeIn(REDRAW_FIELD);
3519 }
3520
3521 void HandleInfoScreen_LevelSet(int button)
3522 {
3523   if (button == MB_MENU_LEAVE)
3524   {
3525     PlaySound(SND_MENU_ITEM_SELECTING);
3526
3527     info_mode = INFO_MODE_MAIN;
3528     DrawInfoScreen();
3529
3530     return;
3531   }
3532   else if (button == MB_MENU_CHOICE)
3533   {
3534     PlaySound(SND_MENU_ITEM_SELECTING);
3535
3536     FadeMenuSoundsAndMusic();
3537
3538     info_mode = INFO_MODE_MAIN;
3539     DrawInfoScreen();
3540   }
3541   else
3542   {
3543     PlayMenuSoundIfLoop();
3544   }
3545 }
3546
3547 static void DrawInfoScreen()
3548 {
3549   if (info_mode == INFO_MODE_TITLE)
3550     DrawInfoScreen_TitleScreen();
3551   else if (info_mode == INFO_MODE_ELEMENTS)
3552     DrawInfoScreen_Elements();
3553   else if (info_mode == INFO_MODE_MUSIC)
3554     DrawInfoScreen_Music();
3555   else if (info_mode == INFO_MODE_CREDITS)
3556     DrawInfoScreen_Credits();
3557   else if (info_mode == INFO_MODE_PROGRAM)
3558     DrawInfoScreen_Program();
3559   else if (info_mode == INFO_MODE_VERSION)
3560     DrawInfoScreen_Version();
3561   else if (info_mode == INFO_MODE_LEVELSET)
3562     DrawInfoScreen_LevelSet();
3563   else
3564     DrawInfoScreen_Main();
3565
3566   if (info_mode != INFO_MODE_MAIN &&
3567       info_mode != INFO_MODE_TITLE &&
3568       info_mode != INFO_MODE_MUSIC)
3569     PlayMenuSoundsAndMusic();
3570 }
3571
3572 void HandleInfoScreen(int mx, int my, int dx, int dy, int button)
3573 {
3574   if (info_mode == INFO_MODE_TITLE)
3575     HandleInfoScreen_TitleScreen(button);
3576   else if (info_mode == INFO_MODE_ELEMENTS)
3577     HandleInfoScreen_Elements(button);
3578   else if (info_mode == INFO_MODE_MUSIC)
3579     HandleInfoScreen_Music(button);
3580   else if (info_mode == INFO_MODE_CREDITS)
3581     HandleInfoScreen_Credits(button);
3582   else if (info_mode == INFO_MODE_PROGRAM)
3583     HandleInfoScreen_Program(button);
3584   else if (info_mode == INFO_MODE_VERSION)
3585     HandleInfoScreen_Version(button);
3586   else if (info_mode == INFO_MODE_LEVELSET)
3587     HandleInfoScreen_LevelSet(button);
3588   else
3589     HandleInfoScreen_Main(mx, my, dx, dy, button);
3590 }
3591
3592
3593 /* ========================================================================= */
3594 /* type name functions                                                       */
3595 /* ========================================================================= */
3596
3597 void HandleTypeName(int newxpos, Key key)
3598 {
3599   static char last_player_name[MAX_PLAYER_NAME_LEN + 1];
3600   struct MainControlInfo *mci = getMainControlInfo(MAIN_CONTROL_NAME);
3601   struct TextPosInfo *pos = mci->pos_input;
3602   int startx = mSX + ALIGNED_TEXT_XPOS(pos);
3603   int starty = mSY + ALIGNED_TEXT_YPOS(pos);
3604   static int xpos = 0;
3605   int font_nr = pos->font;
3606   int font_active_nr = FONT_ACTIVE(font_nr);
3607   int font_width = getFontWidth(font_active_nr);
3608   char key_char = getValidConfigValueChar(getCharFromKey(key));
3609   boolean is_valid_key_char = (key_char != 0 && (key_char != ' ' || xpos > 0));
3610   boolean is_active = TRUE;
3611
3612   DrawBackgroundForFont(startx,starty, pos->width, pos->height, font_active_nr);
3613
3614   if (newxpos)
3615   {
3616     strcpy(last_player_name, setup.player_name);
3617
3618     xpos = newxpos;
3619
3620     StartTextInput(startx, starty, pos->width, pos->height);
3621   }
3622   else if (is_valid_key_char && xpos < MAX_PLAYER_NAME_LEN)
3623   {
3624     setup.player_name[xpos] = key_char;
3625     setup.player_name[xpos + 1] = 0;
3626
3627     xpos++;
3628   }
3629   else if ((key == KSYM_Delete || key == KSYM_BackSpace) && xpos > 0)
3630   {
3631     xpos--;
3632
3633     setup.player_name[xpos] = 0;
3634   }
3635   else if (key == KSYM_Return && xpos > 0)
3636   {
3637     SaveSetup();
3638
3639     is_active = FALSE;
3640
3641     SetGameStatus(GAME_MODE_MAIN);
3642   }
3643   else if (key == KSYM_Escape)
3644   {
3645     strcpy(setup.player_name, last_player_name);
3646
3647     is_active = FALSE;
3648
3649     SetGameStatus(GAME_MODE_MAIN);
3650   }
3651
3652   if (is_active)
3653   {
3654     pos->width = (strlen(setup.player_name) + 1) * font_width;
3655     startx = mSX + ALIGNED_TEXT_XPOS(pos);
3656
3657     DrawText(startx, starty, setup.player_name, font_active_nr);
3658     DrawText(startx + xpos * font_width, starty, "_", font_active_nr);
3659   }
3660   else
3661   {
3662     pos->width = strlen(setup.player_name) * font_width;
3663     startx = mSX + ALIGNED_TEXT_XPOS(pos);
3664
3665     DrawText(startx, starty, setup.player_name, font_nr);
3666
3667     StopTextInput();
3668   }
3669 }
3670
3671
3672 /* ========================================================================= */
3673 /* tree menu functions                                                       */
3674 /* ========================================================================= */
3675
3676 static void DrawChooseTree(TreeInfo **ti_ptr)
3677 {
3678   int fade_mask = REDRAW_FIELD;
3679
3680   if (CheckIfGlobalBorderHasChanged())
3681     fade_mask = REDRAW_ALL;
3682
3683   if (strEqual((*ti_ptr)->subdir, STRING_TOP_DIRECTORY))
3684   {
3685     SetGameStatus(GAME_MODE_MAIN);
3686
3687     DrawMainMenu();
3688
3689     return;
3690   }
3691
3692   UnmapAllGadgets();
3693
3694   FreeScreenGadgets();
3695   CreateScreenGadgets();
3696
3697   FadeOut(fade_mask);
3698
3699   /* needed if different viewport properties defined for choosing level (set) */
3700   ChangeViewportPropertiesIfNeeded();
3701
3702   if (game_status == GAME_MODE_LEVELNR)
3703     SetMainBackgroundImage(IMG_BACKGROUND_LEVELNR);
3704   else if (game_status == GAME_MODE_LEVELS)
3705     SetMainBackgroundImage(IMG_BACKGROUND_LEVELS);
3706
3707   ClearField();
3708
3709   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
3710
3711   HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, ti_ptr);
3712   MapScreenTreeGadgets(*ti_ptr);
3713
3714   DrawMaskedBorder(fade_mask);
3715
3716   FadeIn(fade_mask);
3717 }
3718
3719 static void drawChooseTreeList(int first_entry, int num_page_entries,
3720                                TreeInfo *ti)
3721 {
3722   int i;
3723   char *title_string = NULL;
3724   int yoffset_sets = MENU_TITLE1_YPOS;
3725   int yoffset_setup = 16;
3726   int yoffset = (ti->type == TREE_TYPE_LEVEL_DIR ||
3727                  ti->type == TREE_TYPE_LEVEL_NR ? yoffset_sets : yoffset_setup);
3728
3729   title_string = ti->infotext;
3730
3731   DrawTextSCentered(mSY - SY + yoffset, FONT_TITLE_1, title_string);
3732
3733   clearMenuListArea();
3734
3735   for (i = 0; i < num_page_entries; i++)
3736   {
3737     TreeInfo *node, *node_first;
3738     int entry_pos = first_entry + i;
3739     int xpos = MENU_SCREEN_START_XPOS;
3740     int ypos = MENU_SCREEN_START_YPOS + i;
3741     int startx = mSX + xpos * 32;
3742     int starty = mSY + ypos * 32;
3743     int font_nr = FONT_TEXT_1;
3744     int font_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
3745     int startx_text = startx + font_xoffset;
3746     int startx_scrollbar = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
3747     int text_size = startx_scrollbar - startx_text;
3748     int max_buffer_len = text_size / getFontWidth(font_nr);
3749     char buffer[max_buffer_len + 1];
3750
3751     node_first = getTreeInfoFirstGroupEntry(ti);
3752     node = getTreeInfoFromPos(node_first, entry_pos);
3753
3754     strncpy(buffer, node->name, max_buffer_len);
3755     buffer[max_buffer_len] = '\0';
3756
3757     DrawText(startx, starty, buffer, font_nr + node->color);
3758
3759     if (node->parent_link)
3760       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
3761     else if (node->level_group)
3762       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
3763     else
3764       initCursor(i, IMG_MENU_BUTTON);
3765   }
3766
3767   redraw_mask |= REDRAW_FIELD;
3768 }
3769
3770 static void drawChooseTreeInfo(int entry_pos, TreeInfo *ti)
3771 {
3772   TreeInfo *node, *node_first;
3773   int x, last_redraw_mask = redraw_mask;
3774   int ypos = MENU_TITLE2_YPOS;
3775   int font_nr = FONT_TITLE_2;
3776
3777   if (ti->type == TREE_TYPE_LEVEL_NR)
3778     DrawTextFCentered(ypos, font_nr, leveldir_current->name);
3779
3780   if (ti->type != TREE_TYPE_LEVEL_DIR)
3781     return;
3782
3783   node_first = getTreeInfoFirstGroupEntry(ti);
3784   node = getTreeInfoFromPos(node_first, entry_pos);
3785
3786   DrawBackgroundForFont(SX, SY + ypos, SXSIZE, getFontHeight(font_nr), font_nr);
3787
3788   if (node->parent_link)
3789     DrawTextFCentered(ypos, font_nr, "leave \"%s\"",
3790                       node->node_parent->name);
3791   else if (node->level_group)
3792     DrawTextFCentered(ypos, font_nr, "enter \"%s\"",
3793                       node->name);
3794   else if (ti->type == TREE_TYPE_LEVEL_DIR)
3795     DrawTextFCentered(ypos, font_nr, "%3d %s (%s)",
3796                       node->levels, (node->levels > 1 ? "levels" : "level"),
3797                       node->class_desc);
3798
3799   /* let BackToFront() redraw only what is needed */
3800   redraw_mask = last_redraw_mask;
3801   for (x = 0; x < SCR_FIELDX; x++)
3802     MarkTileDirty(x, 1);
3803 }
3804
3805 static void HandleChooseTree(int mx, int my, int dx, int dy, int button,
3806                              TreeInfo **ti_ptr)
3807 {
3808   TreeInfo *ti = *ti_ptr;
3809   int x = 0;
3810   int y = ti->cl_cursor;
3811   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
3812   int num_entries = numTreeInfoInGroup(ti);
3813   int num_page_entries;
3814   boolean position_set_by_scrollbar = (dx == 999);
3815
3816   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
3817     num_page_entries = num_entries;
3818   else
3819     num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
3820
3821   if (button == MB_MENU_INITIALIZE)
3822   {
3823     int num_entries = numTreeInfoInGroup(ti);
3824     int entry_pos = posTreeInfo(ti);
3825
3826     if (ti->cl_first == -1)
3827     {
3828       /* only on initialization */
3829       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
3830       ti->cl_cursor = entry_pos - ti->cl_first;
3831     }
3832     else if (ti->cl_cursor >= num_page_entries ||
3833              (num_entries > num_page_entries &&
3834               num_entries - ti->cl_first < num_page_entries))
3835     {
3836       /* only after change of list size (by custom graphic configuration) */
3837       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
3838       ti->cl_cursor = entry_pos - ti->cl_first;
3839     }
3840
3841     if (position_set_by_scrollbar)
3842       ti->cl_first = dy;
3843     else
3844       AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
3845                                 ti->cl_first, ti);
3846
3847     drawChooseTreeList(ti->cl_first, num_page_entries, ti);
3848     drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
3849     drawChooseTreeCursor(ti->cl_cursor, TRUE);
3850
3851     return;
3852   }
3853   else if (button == MB_MENU_LEAVE)
3854   {
3855     FadeSetLeaveMenu();
3856
3857     PlaySound(SND_MENU_ITEM_SELECTING);
3858
3859     if (ti->node_parent)
3860     {
3861       *ti_ptr = ti->node_parent;
3862       DrawChooseTree(ti_ptr);
3863     }
3864     else if (game_status == GAME_MODE_SETUP)
3865     {
3866       if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
3867           setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
3868           setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
3869         execSetupGame();
3870       else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
3871                setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
3872                setup_mode == SETUP_MODE_CHOOSE_RENDERING)
3873         execSetupGraphics();
3874       else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
3875                setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
3876                setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
3877         execSetupSound();
3878       else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
3879                setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
3880                setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
3881         execSetupTouch();
3882       else
3883         execSetupArtwork();
3884     }
3885     else
3886     {
3887       if (game_status == GAME_MODE_LEVELNR)
3888       {
3889         int new_level_nr = atoi(level_number_current->identifier);
3890
3891         HandleMainMenu_SelectLevel(0, 0, new_level_nr);
3892       }
3893
3894       SetGameStatus(GAME_MODE_MAIN);
3895
3896       DrawMainMenu();
3897     }
3898
3899     return;
3900   }
3901
3902   if (mx || my)         /* mouse input */
3903   {
3904     x = (mx - mSX) / 32;
3905     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
3906   }
3907   else if (dx || dy)    /* keyboard or scrollbar/scrollbutton input */
3908   {
3909     /* move cursor instead of scrolling when already at start/end of list */
3910     if (dy == -1 * SCROLL_LINE && ti->cl_first == 0)
3911       dy = -1;
3912     else if (dy == +1 * SCROLL_LINE &&
3913              ti->cl_first + num_page_entries == num_entries)
3914       dy = 1;
3915
3916     /* handle scrolling screen one line or page */
3917     if (ti->cl_cursor + dy < 0 ||
3918         ti->cl_cursor + dy > num_page_entries - 1)
3919     {
3920       boolean redraw = FALSE;
3921
3922       if (ABS(dy) == SCROLL_PAGE)
3923         step = num_page_entries - 1;
3924
3925       if (dy < 0 && ti->cl_first > 0)
3926       {
3927         /* scroll page/line up */
3928
3929         ti->cl_first -= step;
3930         if (ti->cl_first < 0)
3931           ti->cl_first = 0;
3932
3933         redraw = TRUE;
3934       }
3935       else if (dy > 0 && ti->cl_first + num_page_entries < num_entries)
3936       {
3937         /* scroll page/line down */
3938
3939         ti->cl_first += step;
3940         if (ti->cl_first + num_page_entries > num_entries)
3941           ti->cl_first = MAX(0, num_entries - num_page_entries);
3942
3943         redraw = TRUE;
3944       }
3945
3946       if (redraw)
3947       {
3948         drawChooseTreeList(ti->cl_first, num_page_entries, ti);
3949         drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
3950         drawChooseTreeCursor(ti->cl_cursor, TRUE);
3951
3952         AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
3953                                   ti->cl_first, ti);
3954       }
3955
3956       return;
3957     }
3958
3959     /* handle moving cursor one line */
3960     y = ti->cl_cursor + dy;
3961   }
3962
3963   if (dx == 1)
3964   {
3965     TreeInfo *node_first, *node_cursor;
3966     int entry_pos = ti->cl_first + y;
3967
3968     node_first = getTreeInfoFirstGroupEntry(ti);
3969     node_cursor = getTreeInfoFromPos(node_first, entry_pos);
3970
3971     if (node_cursor->node_group)
3972     {
3973       FadeSetEnterMenu();
3974
3975       PlaySound(SND_MENU_ITEM_SELECTING);
3976
3977       node_cursor->cl_first = ti->cl_first;
3978       node_cursor->cl_cursor = ti->cl_cursor;
3979       *ti_ptr = node_cursor->node_group;
3980       DrawChooseTree(ti_ptr);
3981
3982       return;
3983     }
3984   }
3985   else if (dx == -1 && ti->node_parent)
3986   {
3987     FadeSetLeaveMenu();
3988
3989     PlaySound(SND_MENU_ITEM_SELECTING);
3990
3991     *ti_ptr = ti->node_parent;
3992     DrawChooseTree(ti_ptr);
3993
3994     return;
3995   }
3996
3997   if (!anyScrollbarGadgetActive() &&
3998       IN_VIS_MENU(x, y) &&
3999       mx < screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x &&
4000       y >= 0 && y < num_page_entries)
4001   {
4002     if (button)
4003     {
4004       if (y != ti->cl_cursor)
4005       {
4006         PlaySound(SND_MENU_ITEM_ACTIVATING);
4007
4008         drawChooseTreeCursor(ti->cl_cursor, FALSE);
4009         drawChooseTreeCursor(y, TRUE);
4010         drawChooseTreeInfo(ti->cl_first + y, ti);
4011
4012         ti->cl_cursor = y;
4013       }
4014       else if (dx < 0)
4015       {
4016         if (game_status == GAME_MODE_SETUP)
4017         {
4018           if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
4019               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
4020               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
4021             execSetupGame();
4022           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
4023                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
4024                    setup_mode == SETUP_MODE_CHOOSE_RENDERING)
4025             execSetupGraphics();
4026           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
4027                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
4028                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
4029             execSetupSound();
4030           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
4031                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
4032                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
4033             execSetupTouch();
4034           else
4035             execSetupArtwork();
4036         }
4037       }
4038     }
4039     else
4040     {
4041       TreeInfo *node_first, *node_cursor;
4042       int entry_pos = ti->cl_first + y;
4043
4044       PlaySound(SND_MENU_ITEM_SELECTING);
4045
4046       node_first = getTreeInfoFirstGroupEntry(ti);
4047       node_cursor = getTreeInfoFromPos(node_first, entry_pos);
4048
4049       if (node_cursor->node_group)
4050       {
4051         FadeSetEnterMenu();
4052
4053         node_cursor->cl_first = ti->cl_first;
4054         node_cursor->cl_cursor = ti->cl_cursor;
4055         *ti_ptr = node_cursor->node_group;
4056         DrawChooseTree(ti_ptr);
4057       }
4058       else if (node_cursor->parent_link)
4059       {
4060         FadeSetLeaveMenu();
4061
4062         *ti_ptr = node_cursor->node_parent;
4063         DrawChooseTree(ti_ptr);
4064       }
4065       else
4066       {
4067         FadeSetEnterMenu();
4068
4069         node_cursor->cl_first = ti->cl_first;
4070         node_cursor->cl_cursor = ti->cl_cursor;
4071         *ti_ptr = node_cursor;
4072
4073         if (ti->type == TREE_TYPE_LEVEL_DIR)
4074         {
4075           LoadLevelSetup_SeriesInfo();
4076
4077           SaveLevelSetup_LastSeries();
4078           SaveLevelSetup_SeriesInfo();
4079           TapeErase();
4080         }
4081
4082         if (game_status == GAME_MODE_SETUP)
4083         {
4084           if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
4085               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
4086               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
4087             execSetupGame();
4088           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
4089                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
4090                    setup_mode == SETUP_MODE_CHOOSE_RENDERING)
4091             execSetupGraphics();
4092           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
4093                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
4094                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
4095             execSetupSound();
4096           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
4097                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
4098                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
4099             execSetupTouch();
4100           else
4101             execSetupArtwork();
4102         }
4103         else
4104         {
4105           if (game_status == GAME_MODE_LEVELNR)
4106           {
4107             int new_level_nr = atoi(level_number_current->identifier);
4108
4109             HandleMainMenu_SelectLevel(0, 0, new_level_nr);
4110           }
4111
4112           SetGameStatus(GAME_MODE_MAIN);
4113
4114           DrawMainMenu();
4115         }
4116       }
4117     }
4118   }
4119 }
4120
4121 void DrawChooseLevelSet()
4122 {
4123   FadeMenuSoundsAndMusic();
4124
4125   DrawChooseTree(&leveldir_current);
4126
4127   PlayMenuSoundsAndMusic();
4128 }
4129
4130 void HandleChooseLevelSet(int mx, int my, int dx, int dy, int button)
4131 {
4132   HandleChooseTree(mx, my, dx, dy, button, &leveldir_current);
4133 }
4134
4135 void DrawChooseLevelNr()
4136 {
4137   int i;
4138
4139   FadeMenuSoundsAndMusic();
4140
4141   if (level_number != NULL)
4142   {
4143     freeTreeInfo(level_number);
4144
4145     level_number = NULL;
4146   }
4147
4148   for (i = leveldir_current->first_level; i <= leveldir_current->last_level;i++)
4149   {
4150     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_LEVEL_NR);
4151     char identifier[32], name[32];
4152     int value = i;
4153
4154     /* temporarily load level info to get level name */
4155     LoadLevelInfoOnly(i);
4156
4157     ti->node_top = &level_number;
4158     ti->sort_priority = 10000 + value;
4159     ti->color = (level.no_level_file ? FC_BLUE :
4160                  LevelStats_getSolved(i) ? FC_GREEN :
4161                  LevelStats_getPlayed(i) ? FC_YELLOW : FC_RED);
4162
4163     snprintf(identifier, sizeof(identifier), "%d", value);
4164     snprintf(name, sizeof(name), "%03d: %s", value,
4165              (level.no_level_file ? "(no file)" : level.name));
4166
4167     setString(&ti->identifier, identifier);
4168     setString(&ti->name, name);
4169     setString(&ti->name_sorting, name);
4170
4171     pushTreeInfo(&level_number, ti);
4172   }
4173
4174   /* sort level number values to start with lowest level number */
4175   sortTreeInfo(&level_number);
4176
4177   /* set current level number to current level number */
4178   level_number_current =
4179     getTreeInfoFromIdentifier(level_number, i_to_a(level_nr));
4180
4181   /* if that also fails, set current level number to first available level */
4182   if (level_number_current == NULL)
4183     level_number_current = level_number;
4184
4185   DrawChooseTree(&level_number_current);
4186
4187   PlayMenuSoundsAndMusic();
4188 }
4189
4190 void HandleChooseLevelNr(int mx, int my, int dx, int dy, int button)
4191 {
4192   HandleChooseTree(mx, my, dx, dy, button, &level_number_current);
4193 }
4194
4195 void DrawHallOfFame(int highlight_position)
4196 {
4197   int fade_mask = REDRAW_FIELD;
4198
4199   if (CheckIfGlobalBorderHasChanged())
4200     fade_mask = REDRAW_ALL;
4201
4202   UnmapAllGadgets();
4203   FadeMenuSoundsAndMusic();
4204
4205   /* (this is needed when called from GameEnd() after winning a game) */
4206   KeyboardAutoRepeatOn();
4207
4208   /* (this is needed when called from GameEnd() after winning a game) */
4209   SetDrawDeactivationMask(REDRAW_NONE);
4210   SetDrawBackgroundMask(REDRAW_FIELD);
4211
4212   if (highlight_position < 0) 
4213     LoadScore(level_nr);
4214   else
4215     SetAnimStatus(GAME_MODE_PSEUDO_SCORESNEW);
4216
4217   FadeSetEnterScreen();
4218
4219   FadeOut(fade_mask);
4220
4221   /* needed if different viewport properties defined for scores */
4222   ChangeViewportPropertiesIfNeeded();
4223
4224   PlayMenuSoundsAndMusic();
4225
4226   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
4227
4228   HandleHallOfFame(highlight_position, 0, 0, 0, MB_MENU_INITIALIZE);
4229
4230   DrawMaskedBorder(fade_mask);
4231
4232   FadeIn(fade_mask);
4233 }
4234
4235 static void drawHallOfFameList(int first_entry, int highlight_position)
4236 {
4237   int i, j;
4238
4239   SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
4240   ClearField();
4241
4242   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, "Hall Of Fame");
4243   DrawTextFCentered(MENU_TITLE2_YPOS, FONT_TITLE_2,
4244                     "HighScores of Level %d", level_nr);
4245
4246   for (i = 0; i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
4247   {
4248     int entry = first_entry + i;
4249     boolean active = (entry == highlight_position);
4250     int font_nr1 = (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4251     int font_nr2 = (active ? FONT_TEXT_2_ACTIVE : FONT_TEXT_2);
4252     int font_nr3 = (active ? FONT_TEXT_3_ACTIVE : FONT_TEXT_3);
4253     int font_nr4 = (active ? FONT_TEXT_4_ACTIVE : FONT_TEXT_4);
4254     int dxoff = getFontDrawOffsetX(font_nr1);
4255     int dx1 = 3 * getFontWidth(font_nr1);
4256     int dx2 = dx1 + getFontWidth(font_nr1);
4257     int dx3 = SXSIZE - 2 * (mSX - SX + dxoff) - 5 * getFontWidth(font_nr4);
4258     int num_dots = (dx3 - dx2) / getFontWidth(font_nr3);
4259     int sy = mSY + 64 + i * 32;
4260
4261     DrawText(mSX, sy, int2str(entry + 1, 3), font_nr1);
4262     DrawText(mSX + dx1, sy, ".", font_nr1);
4263
4264     for (j = 0; j < num_dots; j++)
4265       DrawText(mSX + dx2 + j * getFontWidth(font_nr3), sy, ".", font_nr3);
4266
4267     if (!strEqual(highscore[entry].Name, EMPTY_PLAYER_NAME))
4268       DrawText(mSX + dx2, sy, highscore[entry].Name, font_nr2);
4269
4270     DrawText(mSX + dx3, sy, int2str(highscore[entry].Score, 5), font_nr4);
4271   }
4272
4273   redraw_mask |= REDRAW_FIELD;
4274 }
4275
4276 void HandleHallOfFame(int mx, int my, int dx, int dy, int button)
4277 {
4278   static int first_entry = 0;
4279   static int highlight_position = 0;
4280   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
4281
4282   if (button == MB_MENU_INITIALIZE)
4283   {
4284     first_entry = 0;
4285     highlight_position = mx;
4286     drawHallOfFameList(first_entry, highlight_position);
4287
4288     return;
4289   }
4290
4291   if (ABS(dy) == SCROLL_PAGE)           /* handle scrolling one page */
4292     step = NUM_MENU_ENTRIES_ON_SCREEN - 1;
4293
4294   if (dy < 0)
4295   {
4296     if (first_entry > 0)
4297     {
4298       first_entry -= step;
4299       if (first_entry < 0)
4300         first_entry = 0;
4301
4302       drawHallOfFameList(first_entry, highlight_position);
4303     }
4304   }
4305   else if (dy > 0)
4306   {
4307     if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN < MAX_SCORE_ENTRIES)
4308     {
4309       first_entry += step;
4310       if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN > MAX_SCORE_ENTRIES)
4311         first_entry = MAX(0, MAX_SCORE_ENTRIES - NUM_MENU_ENTRIES_ON_SCREEN);
4312
4313       drawHallOfFameList(first_entry, highlight_position);
4314     }
4315   }
4316   else if (button == MB_MENU_LEAVE)
4317   {
4318     PlaySound(SND_MENU_ITEM_SELECTING);
4319
4320     FadeSound(SND_BACKGROUND_SCORES);
4321
4322     SetGameStatus(GAME_MODE_MAIN);
4323
4324     DrawMainMenu();
4325   }
4326   else if (button == MB_MENU_CHOICE)
4327   {
4328     PlaySound(SND_MENU_ITEM_SELECTING);
4329
4330     FadeSound(SND_BACKGROUND_SCORES);
4331
4332     SetGameStatus(GAME_MODE_MAIN);
4333
4334     DrawMainMenu();
4335   }
4336
4337   if (game_status == GAME_MODE_SCORES)
4338     PlayMenuSoundIfLoop();
4339 }
4340
4341
4342 /* ========================================================================= */
4343 /* setup screen functions                                                    */
4344 /* ========================================================================= */
4345
4346 static struct TokenInfo *setup_info;
4347 static int num_setup_info;      /* number of setup entries shown on screen */
4348 static int max_setup_info;      /* total number of setup entries in list */
4349
4350 static char *window_size_text;
4351 static char *scaling_type_text;
4352 static char *rendering_mode_text;
4353 static char *scroll_delay_text;
4354 static char *snapshot_mode_text;
4355 static char *game_speed_text;
4356 static char *graphics_set_name;
4357 static char *sounds_set_name;
4358 static char *music_set_name;
4359 static char *volume_simple_text;
4360 static char *volume_loops_text;
4361 static char *volume_music_text;
4362 static char *touch_controls_text;
4363 static char *move_distance_text;
4364 static char *drop_distance_text;
4365
4366 static void execSetupMain()
4367 {
4368   setup_mode = SETUP_MODE_MAIN;
4369
4370   DrawSetupScreen();
4371 }
4372
4373 static void execSetupGame_setGameSpeeds()
4374 {
4375   if (game_speeds == NULL)
4376   {
4377     int i;
4378
4379     for (i = 0; game_speeds_list[i].value != -1; i++)
4380     {
4381       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4382       char identifier[32], name[32];
4383       int value = game_speeds_list[i].value;
4384       char *text = game_speeds_list[i].text;
4385
4386       ti->node_top = &game_speeds;
4387       ti->sort_priority = 10000 - value;
4388
4389       sprintf(identifier, "%d", value);
4390       sprintf(name, "%s", text);
4391
4392       setString(&ti->identifier, identifier);
4393       setString(&ti->name, name);
4394       setString(&ti->name_sorting, name);
4395       setString(&ti->infotext, "Game Speed");
4396
4397       pushTreeInfo(&game_speeds, ti);
4398     }
4399
4400     /* sort game speed values to start with slowest game speed */
4401     sortTreeInfo(&game_speeds);
4402
4403     /* set current game speed to configured game speed value */
4404     game_speed_current =
4405       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
4406
4407     /* if that fails, set current game speed to reliable default value */
4408     if (game_speed_current == NULL)
4409       game_speed_current =
4410         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
4411
4412     /* if that also fails, set current game speed to first available speed */
4413     if (game_speed_current == NULL)
4414       game_speed_current = game_speeds;
4415   }
4416
4417   setup.game_frame_delay = atoi(game_speed_current->identifier);
4418
4419   /* needed for displaying game speed text instead of identifier */
4420   game_speed_text = game_speed_current->name;
4421 }
4422
4423 static void execSetupGame_setScrollDelays()
4424 {
4425   if (scroll_delays == NULL)
4426   {
4427     int i;
4428
4429     for (i = 0; scroll_delays_list[i].value != -1; i++)
4430     {
4431       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4432       char identifier[32], name[32];
4433       int value = scroll_delays_list[i].value;
4434       char *text = scroll_delays_list[i].text;
4435
4436       ti->node_top = &scroll_delays;
4437       ti->sort_priority = value;
4438
4439       sprintf(identifier, "%d", value);
4440       sprintf(name, "%s", text);
4441
4442       setString(&ti->identifier, identifier);
4443       setString(&ti->name, name);
4444       setString(&ti->name_sorting, name);
4445       setString(&ti->infotext, "Scroll Delay");
4446
4447       pushTreeInfo(&scroll_delays, ti);
4448     }
4449
4450     /* sort scroll delay values to start with lowest scroll delay value */
4451     sortTreeInfo(&scroll_delays);
4452
4453     /* set current scroll delay value to configured scroll delay value */
4454     scroll_delay_current =
4455       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
4456
4457     /* if that fails, set current scroll delay to reliable default value */
4458     if (scroll_delay_current == NULL)
4459       scroll_delay_current =
4460         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
4461
4462     /* if that also fails, set current scroll delay to first available value */
4463     if (scroll_delay_current == NULL)
4464       scroll_delay_current = scroll_delays;
4465   }
4466
4467   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
4468
4469   /* needed for displaying scroll delay text instead of identifier */
4470   scroll_delay_text = scroll_delay_current->name;
4471 }
4472
4473 static void execSetupGame_setSnapshotModes()
4474 {
4475   if (snapshot_modes == NULL)
4476   {
4477     int i;
4478
4479     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
4480     {
4481       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4482       char identifier[32], name[32];
4483       char *value = snapshot_modes_list[i].value;
4484       char *text = snapshot_modes_list[i].text;
4485
4486       ti->node_top = &snapshot_modes;
4487       ti->sort_priority = i;
4488
4489       sprintf(identifier, "%s", value);
4490       sprintf(name, "%s", text);
4491
4492       setString(&ti->identifier, identifier);
4493       setString(&ti->name, name);
4494       setString(&ti->name_sorting, name);
4495       setString(&ti->infotext, "Snapshot Mode");
4496
4497       pushTreeInfo(&snapshot_modes, ti);
4498     }
4499
4500     /* sort snapshot mode values to start with lowest snapshot mode value */
4501     sortTreeInfo(&snapshot_modes);
4502
4503     /* set current snapshot mode value to configured snapshot mode value */
4504     snapshot_mode_current =
4505       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
4506
4507     /* if that fails, set current snapshot mode to reliable default value */
4508     if (snapshot_mode_current == NULL)
4509       snapshot_mode_current =
4510         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
4511
4512     /* if that also fails, set current snapshot mode to first available value */
4513     if (snapshot_mode_current == NULL)
4514       snapshot_mode_current = snapshot_modes;
4515   }
4516
4517   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
4518
4519   /* needed for displaying snapshot mode text instead of identifier */
4520   snapshot_mode_text = snapshot_mode_current->name;
4521 }
4522
4523 static void execSetupGame()
4524 {
4525   execSetupGame_setGameSpeeds();
4526   execSetupGame_setScrollDelays();
4527   execSetupGame_setSnapshotModes();
4528
4529   setup_mode = SETUP_MODE_GAME;
4530
4531   DrawSetupScreen();
4532 }
4533
4534 static void execSetupChooseGameSpeed()
4535 {
4536   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
4537
4538   DrawSetupScreen();
4539 }
4540
4541 static void execSetupChooseScrollDelay()
4542 {
4543   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
4544
4545   DrawSetupScreen();
4546 }
4547
4548 static void execSetupChooseSnapshotMode()
4549 {
4550   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
4551
4552   DrawSetupScreen();
4553 }
4554
4555 static void execSetupEditor()
4556 {
4557   setup_mode = SETUP_MODE_EDITOR;
4558
4559   DrawSetupScreen();
4560 }
4561
4562 static void execSetupGraphics_setWindowSizes(boolean update_list)
4563 {
4564   if (window_sizes != NULL && update_list)
4565   {
4566     freeTreeInfo(window_sizes);
4567
4568     window_sizes = NULL;
4569   }
4570
4571   if (window_sizes == NULL)
4572   {
4573     boolean current_window_size_found = FALSE;
4574     int i;
4575
4576     for (i = 0; window_sizes_list[i].value != -1; i++)
4577     {
4578       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4579       char identifier[32], name[32];
4580       int value = window_sizes_list[i].value;
4581       char *text = window_sizes_list[i].text;
4582
4583       ti->node_top = &window_sizes;
4584       ti->sort_priority = value;
4585
4586       sprintf(identifier, "%d", value);
4587       sprintf(name, "%s", text);
4588
4589       setString(&ti->identifier, identifier);
4590       setString(&ti->name, name);
4591       setString(&ti->name_sorting, name);
4592       setString(&ti->infotext, "Window Scaling");
4593
4594       pushTreeInfo(&window_sizes, ti);
4595
4596       if (value == setup.window_scaling_percent)
4597         current_window_size_found = TRUE;
4598     }
4599
4600     if (!current_window_size_found)
4601     {
4602       // add entry for non-preset window scaling value
4603
4604       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4605       char identifier[32], name[32];
4606       int value = setup.window_scaling_percent;
4607
4608       ti->node_top = &window_sizes;
4609       ti->sort_priority = value;
4610
4611       sprintf(identifier, "%d", value);
4612       sprintf(name, "%d %% (Current)", value);
4613
4614       setString(&ti->identifier, identifier);
4615       setString(&ti->name, name);
4616       setString(&ti->name_sorting, name);
4617       setString(&ti->infotext, "Window Scaling");
4618
4619       pushTreeInfo(&window_sizes, ti);
4620     }
4621
4622     /* sort window size values to start with lowest window size value */
4623     sortTreeInfo(&window_sizes);
4624
4625     /* set current window size value to configured window size value */
4626     window_size_current =
4627       getTreeInfoFromIdentifier(window_sizes,
4628                                 i_to_a(setup.window_scaling_percent));
4629
4630     /* if that fails, set current window size to reliable default value */
4631     if (window_size_current == NULL)
4632       window_size_current =
4633         getTreeInfoFromIdentifier(window_sizes,
4634                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
4635
4636     /* if that also fails, set current window size to first available value */
4637     if (window_size_current == NULL)
4638       window_size_current = window_sizes;
4639   }
4640
4641   setup.window_scaling_percent = atoi(window_size_current->identifier);
4642
4643   /* needed for displaying window size text instead of identifier */
4644   window_size_text = window_size_current->name;
4645 }
4646
4647 static void execSetupGraphics_setScalingTypes()
4648 {
4649   if (scaling_types == NULL)
4650   {
4651     int i;
4652
4653     for (i = 0; scaling_types_list[i].value != NULL; i++)
4654     {
4655       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4656       char identifier[32], name[32];
4657       char *value = scaling_types_list[i].value;
4658       char *text = scaling_types_list[i].text;
4659
4660       ti->node_top = &scaling_types;
4661       ti->sort_priority = i;
4662
4663       sprintf(identifier, "%s", value);
4664       sprintf(name, "%s", text);
4665
4666       setString(&ti->identifier, identifier);
4667       setString(&ti->name, name);
4668       setString(&ti->name_sorting, name);
4669       setString(&ti->infotext, "Anti-Aliasing");
4670
4671       pushTreeInfo(&scaling_types, ti);
4672     }
4673
4674     /* sort scaling type values to start with lowest scaling type value */
4675     sortTreeInfo(&scaling_types);
4676
4677     /* set current scaling type value to configured scaling type value */
4678     scaling_type_current =
4679       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
4680
4681     /* if that fails, set current scaling type to reliable default value */
4682     if (scaling_type_current == NULL)
4683       scaling_type_current =
4684         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
4685
4686     /* if that also fails, set current scaling type to first available value */
4687     if (scaling_type_current == NULL)
4688       scaling_type_current = scaling_types;
4689   }
4690
4691   setup.window_scaling_quality = scaling_type_current->identifier;
4692
4693   /* needed for displaying scaling type text instead of identifier */
4694   scaling_type_text = scaling_type_current->name;
4695 }
4696
4697 static void execSetupGraphics_setRenderingModes()
4698 {
4699   if (rendering_modes == NULL)
4700   {
4701     int i;
4702
4703     for (i = 0; rendering_modes_list[i].value != NULL; i++)
4704     {
4705       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4706       char identifier[32], name[32];
4707       char *value = rendering_modes_list[i].value;
4708       char *text = rendering_modes_list[i].text;
4709
4710       ti->node_top = &rendering_modes;
4711       ti->sort_priority = i;
4712
4713       sprintf(identifier, "%s", value);
4714       sprintf(name, "%s", text);
4715
4716       setString(&ti->identifier, identifier);
4717       setString(&ti->name, name);
4718       setString(&ti->name_sorting, name);
4719       setString(&ti->infotext, "Special Rendering");
4720
4721       pushTreeInfo(&rendering_modes, ti);
4722     }
4723
4724     /* sort rendering mode values to start with lowest rendering mode value */
4725     sortTreeInfo(&rendering_modes);
4726
4727     /* set current rendering mode value to configured rendering mode value */
4728     rendering_mode_current =
4729       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
4730
4731     /* if that fails, set current rendering mode to reliable default value */
4732     if (rendering_mode_current == NULL)
4733       rendering_mode_current =
4734         getTreeInfoFromIdentifier(rendering_modes,
4735                                   STR_SPECIAL_RENDERING_DEFAULT);
4736
4737     /* if that also fails, set current rendering mode to first available one */
4738     if (rendering_mode_current == NULL)
4739       rendering_mode_current = rendering_modes;
4740   }
4741
4742   setup.screen_rendering_mode = rendering_mode_current->identifier;
4743
4744   /* needed for displaying rendering mode text instead of identifier */
4745   rendering_mode_text = rendering_mode_current->name;
4746 }
4747
4748 static void execSetupGraphics()
4749 {
4750   // update "setup.window_scaling_percent" from list selection
4751   // (in this case, window scaling was changed on setup screen)
4752   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
4753     execSetupGraphics_setWindowSizes(FALSE);
4754
4755   // update list selection from "setup.window_scaling_percent"
4756   // (window scaling may have changed by resizing the window)
4757   execSetupGraphics_setWindowSizes(TRUE);
4758
4759   execSetupGraphics_setScalingTypes();
4760   execSetupGraphics_setRenderingModes();
4761
4762   setup_mode = SETUP_MODE_GRAPHICS;
4763
4764   DrawSetupScreen();
4765
4766 #if defined(TARGET_SDL2)
4767   // window scaling may have changed at this point
4768   ToggleFullscreenOrChangeWindowScalingIfNeeded();
4769
4770   // window scaling quality may have changed at this point
4771   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
4772     SDLSetWindowScalingQuality(setup.window_scaling_quality);
4773
4774   // screen rendering mode may have changed at this point
4775   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
4776 #endif
4777 }
4778
4779 #if defined(TARGET_SDL2) && !defined(PLATFORM_ANDROID)
4780 static void execSetupChooseWindowSize()
4781 {
4782   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
4783
4784   DrawSetupScreen();
4785 }
4786
4787 static void execSetupChooseScalingType()
4788 {
4789   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
4790
4791   DrawSetupScreen();
4792 }
4793
4794 static void execSetupChooseRenderingMode()
4795 {
4796   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
4797
4798   DrawSetupScreen();
4799 }
4800 #endif
4801
4802 static void execSetupChooseVolumeSimple()
4803 {
4804   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
4805
4806   DrawSetupScreen();
4807 }
4808
4809 static void execSetupChooseVolumeLoops()
4810 {
4811   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
4812
4813   DrawSetupScreen();
4814 }
4815
4816 static void execSetupChooseVolumeMusic()
4817 {
4818   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
4819
4820   DrawSetupScreen();
4821 }
4822
4823 static void execSetupSound()
4824 {
4825   if (volumes_simple == NULL)
4826   {
4827     boolean current_volume_simple_found = FALSE;
4828     int i;
4829
4830     for (i = 0; volumes_list[i].value != -1; i++)
4831     {
4832       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4833       char identifier[32], name[32];
4834       int value = volumes_list[i].value;
4835       char *text = volumes_list[i].text;
4836
4837       ti->node_top = &volumes_simple;
4838       ti->sort_priority = value;
4839
4840       sprintf(identifier, "%d", value);
4841       sprintf(name, "%s", text);
4842
4843       setString(&ti->identifier, identifier);
4844       setString(&ti->name, name);
4845       setString(&ti->name_sorting, name);
4846       setString(&ti->infotext, "Sound Volume");
4847
4848       pushTreeInfo(&volumes_simple, ti);
4849
4850       if (value == setup.volume_simple)
4851         current_volume_simple_found = TRUE;
4852     }
4853
4854     if (!current_volume_simple_found)
4855     {
4856       // add entry for non-preset volume value
4857
4858       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4859       char identifier[32], name[32];
4860       int value = setup.volume_simple;
4861
4862       ti->node_top = &volumes_simple;
4863       ti->sort_priority = value;
4864
4865       sprintf(identifier, "%d", value);
4866       sprintf(name, "%d %% (Current)", value);
4867
4868       setString(&ti->identifier, identifier);
4869       setString(&ti->name, name);
4870       setString(&ti->name_sorting, name);
4871       setString(&ti->infotext, "Sound Volume");
4872
4873       pushTreeInfo(&volumes_simple, ti);
4874     }
4875
4876     /* sort volume values to start with lowest volume value */
4877     sortTreeInfo(&volumes_simple);
4878
4879     /* set current volume value to configured volume value */
4880     volume_simple_current =
4881       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
4882
4883     /* if that fails, set current volume to reliable default value */
4884     if (volume_simple_current == NULL)
4885       volume_simple_current =
4886         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
4887
4888     /* if that also fails, set current volume to first available value */
4889     if (volume_simple_current == NULL)
4890       volume_simple_current = volumes_simple;
4891   }
4892
4893   if (volumes_loops == NULL)
4894   {
4895     boolean current_volume_loops_found = FALSE;
4896     int i;
4897
4898     for (i = 0; volumes_list[i].value != -1; i++)
4899     {
4900       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4901       char identifier[32], name[32];
4902       int value = volumes_list[i].value;
4903       char *text = volumes_list[i].text;
4904
4905       ti->node_top = &volumes_loops;
4906       ti->sort_priority = value;
4907
4908       sprintf(identifier, "%d", value);
4909       sprintf(name, "%s", text);
4910
4911       setString(&ti->identifier, identifier);
4912       setString(&ti->name, name);
4913       setString(&ti->name_sorting, name);
4914       setString(&ti->infotext, "Loops Volume");
4915
4916       pushTreeInfo(&volumes_loops, ti);
4917
4918       if (value == setup.volume_loops)
4919         current_volume_loops_found = TRUE;
4920     }
4921
4922     if (!current_volume_loops_found)
4923     {
4924       // add entry for non-preset volume value
4925
4926       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4927       char identifier[32], name[32];
4928       int value = setup.volume_loops;
4929
4930       ti->node_top = &volumes_loops;
4931       ti->sort_priority = value;
4932
4933       sprintf(identifier, "%d", value);
4934       sprintf(name, "%d %% (Current)", value);
4935
4936       setString(&ti->identifier, identifier);
4937       setString(&ti->name, name);
4938       setString(&ti->name_sorting, name);
4939       setString(&ti->infotext, "Loops Volume");
4940
4941       pushTreeInfo(&volumes_loops, ti);
4942     }
4943
4944     /* sort volume values to start with lowest volume value */
4945     sortTreeInfo(&volumes_loops);
4946
4947     /* set current volume value to configured volume value */
4948     volume_loops_current =
4949       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
4950
4951     /* if that fails, set current volume to reliable default value */
4952     if (volume_loops_current == NULL)
4953       volume_loops_current =
4954         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
4955
4956     /* if that also fails, set current volume to first available value */
4957     if (volume_loops_current == NULL)
4958       volume_loops_current = volumes_loops;
4959   }
4960
4961   if (volumes_music == NULL)
4962   {
4963     boolean current_volume_music_found = FALSE;
4964     int i;
4965
4966     for (i = 0; volumes_list[i].value != -1; i++)
4967     {
4968       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4969       char identifier[32], name[32];
4970       int value = volumes_list[i].value;
4971       char *text = volumes_list[i].text;
4972
4973       ti->node_top = &volumes_music;
4974       ti->sort_priority = value;
4975
4976       sprintf(identifier, "%d", value);
4977       sprintf(name, "%s", text);
4978
4979       setString(&ti->identifier, identifier);
4980       setString(&ti->name, name);
4981       setString(&ti->name_sorting, name);
4982       setString(&ti->infotext, "Music Volume");
4983
4984       pushTreeInfo(&volumes_music, ti);
4985
4986       if (value == setup.volume_music)
4987         current_volume_music_found = TRUE;
4988     }
4989
4990     if (!current_volume_music_found)
4991     {
4992       // add entry for non-preset volume value
4993
4994       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4995       char identifier[32], name[32];
4996       int value = setup.volume_music;
4997
4998       ti->node_top = &volumes_music;
4999       ti->sort_priority = value;
5000
5001       sprintf(identifier, "%d", value);
5002       sprintf(name, "%d %% (Current)", value);
5003
5004       setString(&ti->identifier, identifier);
5005       setString(&ti->name, name);
5006       setString(&ti->name_sorting, name);
5007       setString(&ti->infotext, "Music Volume");
5008
5009       pushTreeInfo(&volumes_music, ti);
5010     }
5011
5012     /* sort volume values to start with lowest volume value */
5013     sortTreeInfo(&volumes_music);
5014
5015     /* set current volume value to configured volume value */
5016     volume_music_current =
5017       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
5018
5019     /* if that fails, set current volume to reliable default value */
5020     if (volume_music_current == NULL)
5021       volume_music_current =
5022         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
5023
5024     /* if that also fails, set current volume to first available value */
5025     if (volume_music_current == NULL)
5026       volume_music_current = volumes_music;
5027   }
5028
5029   setup.volume_simple = atoi(volume_simple_current->identifier);
5030   setup.volume_loops  = atoi(volume_loops_current->identifier);
5031   setup.volume_music  = atoi(volume_music_current->identifier);
5032
5033   /* needed for displaying volume text instead of identifier */
5034   volume_simple_text = volume_simple_current->name;
5035   volume_loops_text = volume_loops_current->name;
5036   volume_music_text = volume_music_current->name;
5037
5038   setup_mode = SETUP_MODE_SOUND;
5039
5040   DrawSetupScreen();
5041 }
5042
5043 static void execSetupChooseTouchControls()
5044 {
5045   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
5046
5047   DrawSetupScreen();
5048 }
5049
5050 static void execSetupChooseMoveDistance()
5051 {
5052   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
5053
5054   DrawSetupScreen();
5055 }
5056
5057 static void execSetupChooseDropDistance()
5058 {
5059   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
5060
5061   DrawSetupScreen();
5062 }
5063
5064 static void execSetupTouch()
5065 {
5066   if (touch_controls == NULL)
5067   {
5068     int i;
5069
5070     for (i = 0; touch_controls_list[i].value != NULL; i++)
5071     {
5072       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5073       char identifier[32], name[32];
5074       char *value = touch_controls_list[i].value;
5075       char *text = touch_controls_list[i].text;
5076
5077       ti->node_top = &touch_controls;
5078       ti->sort_priority = i;
5079
5080       sprintf(identifier, "%s", value);
5081       sprintf(name, "%s", text);
5082
5083       setString(&ti->identifier, identifier);
5084       setString(&ti->name, name);
5085       setString(&ti->name_sorting, name);
5086       setString(&ti->infotext, "Control Type");
5087
5088       pushTreeInfo(&touch_controls, ti);
5089     }
5090
5091     /* sort touch control values to start with lowest touch control value */
5092     sortTreeInfo(&touch_controls);
5093
5094     /* set current touch control value to configured touch control value */
5095     touch_control_current =
5096       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
5097
5098     /* if that fails, set current touch control to reliable default value */
5099     if (touch_control_current == NULL)
5100       touch_control_current =
5101         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
5102
5103     /* if that also fails, set current touch control to first available value */
5104     if (touch_control_current == NULL)
5105       touch_control_current = touch_controls;
5106   }
5107
5108   if (move_distances == NULL)
5109   {
5110     int i;
5111
5112     for (i = 0; distances_list[i].value != -1; i++)
5113     {
5114       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5115       char identifier[32], name[32];
5116       int value = distances_list[i].value;
5117       char *text = distances_list[i].text;
5118
5119       ti->node_top = &move_distances;
5120       ti->sort_priority = value;
5121
5122       sprintf(identifier, "%d", value);
5123       sprintf(name, "%s", text);
5124
5125       setString(&ti->identifier, identifier);
5126       setString(&ti->name, name);
5127       setString(&ti->name_sorting, name);
5128       setString(&ti->infotext, "Move Distance");
5129
5130       pushTreeInfo(&move_distances, ti);
5131     }
5132
5133     /* sort distance values to start with lowest distance value */
5134     sortTreeInfo(&move_distances);
5135
5136     /* set current distance value to configured distance value */
5137     move_distance_current =
5138       getTreeInfoFromIdentifier(move_distances,
5139                                 i_to_a(setup.touch.move_distance));
5140
5141     /* if that fails, set current distance to reliable default value */
5142     if (move_distance_current == NULL)
5143       move_distance_current =
5144         getTreeInfoFromIdentifier(move_distances, i_to_a(1));
5145
5146     /* if that also fails, set current distance to first available value */
5147     if (move_distance_current == NULL)
5148       move_distance_current = move_distances;
5149   }
5150
5151   if (drop_distances == NULL)
5152   {
5153     int i;
5154
5155     for (i = 0; distances_list[i].value != -1; i++)
5156     {
5157       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5158       char identifier[32], name[32];
5159       int value = distances_list[i].value;
5160       char *text = distances_list[i].text;
5161
5162       ti->node_top = &drop_distances;
5163       ti->sort_priority = value;
5164
5165       sprintf(identifier, "%d", value);
5166       sprintf(name, "%s", text);
5167
5168       setString(&ti->identifier, identifier);
5169       setString(&ti->name, name);
5170       setString(&ti->name_sorting, name);
5171       setString(&ti->infotext, "Drop Distance");
5172
5173       pushTreeInfo(&drop_distances, ti);
5174     }
5175
5176     /* sort distance values to start with lowest distance value */
5177     sortTreeInfo(&drop_distances);
5178
5179     /* set current distance value to configured distance value */
5180     drop_distance_current =
5181       getTreeInfoFromIdentifier(drop_distances,
5182                                 i_to_a(setup.touch.drop_distance));
5183
5184     /* if that fails, set current distance to reliable default value */
5185     if (drop_distance_current == NULL)
5186       drop_distance_current =
5187         getTreeInfoFromIdentifier(drop_distances, i_to_a(1));
5188
5189     /* if that also fails, set current distance to first available value */
5190     if (drop_distance_current == NULL)
5191       drop_distance_current = drop_distances;
5192   }
5193
5194   setup.touch.control_type = touch_control_current->identifier;
5195   setup.touch.move_distance = atoi(move_distance_current->identifier);
5196   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
5197
5198   /* needed for displaying volume text instead of identifier */
5199   touch_controls_text = touch_control_current->name;
5200   move_distance_text = move_distance_current->name;
5201   drop_distance_text = drop_distance_current->name;
5202
5203   setup_mode = SETUP_MODE_TOUCH;
5204
5205   DrawSetupScreen();
5206 }
5207
5208 static void execSetupArtwork()
5209 {
5210 #if 0
5211   printf("::: '%s', '%s', '%s'\n",
5212          artwork.gfx_current->subdir,
5213          artwork.gfx_current->fullpath,
5214          artwork.gfx_current->basepath);
5215 #endif
5216
5217   setup.graphics_set = artwork.gfx_current->identifier;
5218   setup.sounds_set = artwork.snd_current->identifier;
5219   setup.music_set = artwork.mus_current->identifier;
5220
5221   /* needed if last screen (setup choice) changed graphics, sounds or music */
5222   ReloadCustomArtwork(0);
5223
5224   /* needed for displaying artwork name instead of artwork identifier */
5225   graphics_set_name = artwork.gfx_current->name;
5226   sounds_set_name = artwork.snd_current->name;
5227   music_set_name = artwork.mus_current->name;
5228
5229   setup_mode = SETUP_MODE_ARTWORK;
5230
5231   DrawSetupScreen();
5232 }
5233
5234 static void execSetupChooseGraphics()
5235 {
5236   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
5237
5238   DrawSetupScreen();
5239 }
5240
5241 static void execSetupChooseSounds()
5242 {
5243   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
5244
5245   DrawSetupScreen();
5246 }
5247
5248 static void execSetupChooseMusic()
5249 {
5250   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
5251
5252   DrawSetupScreen();
5253 }
5254
5255 static void execSetupInput()
5256 {
5257   setup_mode = SETUP_MODE_INPUT;
5258
5259   DrawSetupScreen();
5260 }
5261
5262 static void execSetupShortcuts()
5263 {
5264   setup_mode = SETUP_MODE_SHORTCUTS;
5265
5266   DrawSetupScreen();
5267 }
5268
5269 static void execSetupShortcuts1()
5270 {
5271   setup_mode = SETUP_MODE_SHORTCUTS_1;
5272
5273   DrawSetupScreen();
5274 }
5275
5276 static void execSetupShortcuts2()
5277 {
5278   setup_mode = SETUP_MODE_SHORTCUTS_2;
5279
5280   DrawSetupScreen();
5281 }
5282
5283 static void execSetupShortcuts3()
5284 {
5285   setup_mode = SETUP_MODE_SHORTCUTS_3;
5286
5287   DrawSetupScreen();
5288 }
5289
5290 static void execSetupShortcuts4()
5291 {
5292   setup_mode = SETUP_MODE_SHORTCUTS_4;
5293
5294   DrawSetupScreen();
5295 }
5296
5297 static void execSetupShortcuts5()
5298 {
5299   setup_mode = SETUP_MODE_SHORTCUTS_5;
5300
5301   DrawSetupScreen();
5302 }
5303
5304 static void execExitSetup()
5305 {
5306   SetGameStatus(GAME_MODE_MAIN);
5307
5308   DrawMainMenu();
5309 }
5310
5311 static void execSaveAndExitSetup()
5312 {
5313   SaveSetup();
5314   execExitSetup();
5315 }
5316
5317 static struct TokenInfo setup_info_main[] =
5318 {
5319   { TYPE_ENTER_MENU,    execSetupGame,          "Game & Menu"           },
5320   { TYPE_ENTER_MENU,    execSetupEditor,        "Editor"                },
5321   { TYPE_ENTER_MENU,    execSetupGraphics,      "Graphics"              },
5322   { TYPE_ENTER_MENU,    execSetupSound,         "Sound & Music"         },
5323   { TYPE_ENTER_MENU,    execSetupArtwork,       "Custom Artwork"        },
5324   { TYPE_ENTER_MENU,    execSetupInput,         "Input Devices"         },
5325   { TYPE_ENTER_MENU,    execSetupTouch,         "Touch Controls"        },
5326   { TYPE_ENTER_MENU,    execSetupShortcuts,     "Key Shortcuts"         },
5327   { TYPE_EMPTY,         NULL,                   ""                      },
5328   { TYPE_LEAVE_MENU,    execExitSetup,          "Exit"                  },
5329   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   "Save and Exit"         },
5330
5331   { 0,                  NULL,                   NULL                    }
5332 };
5333
5334 static struct TokenInfo setup_info_game[] =
5335 {
5336   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
5337   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
5338   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
5339   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
5340   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
5341   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
5342   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
5343   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
5344   { TYPE_STRING,        &game_speed_text,       ""                      },
5345 #if 1
5346   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
5347   { TYPE_STRING,        &scroll_delay_text,     ""                      },
5348 #endif
5349   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
5350   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
5351   { TYPE_SWITCH,        &setup.show_snapshot_buttons,"Show Snapshot Buttons:" },
5352   { TYPE_EMPTY,         NULL,                   ""                      },
5353   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5354
5355   { 0,                  NULL,                   NULL                    }
5356 };
5357
5358 static struct TokenInfo setup_info_editor[] =
5359 {
5360 #if 0
5361   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
5362   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
5363   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
5364   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
5365   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
5366   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
5367   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
5368   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
5369   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
5370   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
5371 #endif
5372   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
5373   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
5374 #if 0
5375   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
5376 #endif
5377   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
5378   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
5379   { TYPE_EMPTY,         NULL,                   ""                      },
5380 #if 0
5381   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
5382   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
5383   { TYPE_EMPTY,         NULL,                   ""                      },
5384 #endif
5385   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
5386   { TYPE_EMPTY,         NULL,                   ""                      },
5387   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5388
5389   { 0,                  NULL,                   NULL                    }
5390 };
5391
5392 static struct TokenInfo setup_info_graphics[] =
5393 {
5394 #if defined(TARGET_SDL2) && !defined(PLATFORM_ANDROID)
5395   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
5396   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
5397   { TYPE_STRING,        &window_size_text,      ""                      },
5398   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
5399   { TYPE_STRING,        &scaling_type_text,     ""                      },
5400   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
5401   { TYPE_STRING,        &rendering_mode_text,   ""                      },
5402 #endif
5403 #if 0
5404   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
5405   { TYPE_STRING,        &scroll_delay_text,     ""                      },
5406 #endif
5407   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
5408   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
5409   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
5410   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
5411   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
5412   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics,"EMC graphics preference:" },
5413   { TYPE_SWITCH, &setup.sp_show_border_elements,"Supaplex Border Elements:" },
5414   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
5415   { TYPE_EMPTY,         NULL,                   ""                      },
5416   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5417
5418   { 0,                  NULL,                   NULL                    }
5419 };
5420
5421 static struct TokenInfo setup_info_sound[] =
5422 {
5423   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
5424   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
5425   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
5426   { TYPE_EMPTY,         NULL,                   ""                      },
5427   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
5428   { TYPE_STRING,        &volume_simple_text,    ""                      },
5429   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
5430   { TYPE_STRING,        &volume_loops_text,     ""                      },
5431   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
5432   { TYPE_STRING,        &volume_music_text,     ""                      },
5433   { TYPE_EMPTY,         NULL,                   ""                      },
5434   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5435
5436   { 0,                  NULL,                   NULL                    }
5437 };
5438
5439 static struct TokenInfo setup_info_artwork[] =
5440 {
5441   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
5442   { TYPE_STRING,        &graphics_set_name,     ""                      },
5443   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
5444   { TYPE_STRING,        &sounds_set_name,       ""                      },
5445   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
5446   { TYPE_STRING,        &music_set_name,        ""                      },
5447   { TYPE_EMPTY,         NULL,                   ""                      },
5448   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
5449   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
5450   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
5451   { TYPE_EMPTY,         NULL,                   ""                      },
5452   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5453
5454   { 0,                  NULL,                   NULL                    }
5455 };
5456
5457 static struct TokenInfo setup_info_input[] =
5458 {
5459   { TYPE_SWITCH,        NULL,                   "Player:"               },
5460   { TYPE_SWITCH,        NULL,                   "Device:"               },
5461   { TYPE_SWITCH,        NULL,                   ""                      },
5462   { TYPE_EMPTY,         NULL,                   ""                      },
5463   { TYPE_EMPTY,         NULL,                   ""                      },
5464   { TYPE_EMPTY,         NULL,                   ""                      },
5465   { TYPE_EMPTY,         NULL,                   ""                      },
5466   { TYPE_EMPTY,         NULL,                   ""                      },
5467   { TYPE_EMPTY,         NULL,                   ""                      },
5468   { TYPE_EMPTY,         NULL,                   ""                      },
5469   { TYPE_EMPTY,         NULL,                   ""                      },
5470   { TYPE_EMPTY,         NULL,                   ""                      },
5471   { TYPE_EMPTY,         NULL,                   ""                      },
5472   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5473
5474   { 0,                  NULL,                   NULL                    }
5475 };
5476
5477 static struct TokenInfo setup_info_touch[] =
5478 {
5479   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
5480   { TYPE_STRING,        &touch_controls_text,   ""                      },
5481   { TYPE_EMPTY,         NULL,                   ""                      },
5482   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5483
5484   { 0,                  NULL,                   NULL                    }
5485 };
5486
5487 static struct TokenInfo setup_info_touch_wipe_gestures[] =
5488 {
5489   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
5490   { TYPE_STRING,        &touch_controls_text,   ""                      },
5491   { TYPE_EMPTY,         NULL,                   ""                      },
5492   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
5493   { TYPE_STRING,        &move_distance_text,    ""                      },
5494   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
5495   { TYPE_STRING,        &drop_distance_text,    ""                      },
5496   { TYPE_EMPTY,         NULL,                   ""                      },
5497   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5498
5499   { 0,                  NULL,                   NULL                    }
5500 };
5501
5502 static struct TokenInfo setup_info_shortcuts[] =
5503 {
5504   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
5505   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
5506   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
5507   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
5508   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
5509   { TYPE_EMPTY,         NULL,                   ""                      },
5510   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5511
5512   { 0,                  NULL,                   NULL                    }
5513 };
5514
5515 static struct TokenInfo setup_info_shortcuts_1[] =
5516 {
5517   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
5518   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
5519   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
5520   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
5521   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
5522   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
5523   { TYPE_EMPTY,         NULL,                   ""                      },
5524   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
5525   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
5526   { TYPE_EMPTY,         NULL,                   ""                      },
5527   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5528
5529   { 0,                  NULL,                   NULL                    }
5530 };
5531
5532 static struct TokenInfo setup_info_shortcuts_2[] =
5533 {
5534   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
5535   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
5536   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
5537   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
5538   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
5539   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
5540   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
5541   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
5542   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
5543   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
5544   { TYPE_EMPTY,         NULL,                   ""                      },
5545   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5546
5547   { 0,                  NULL,                   NULL                    }
5548 };
5549
5550 static struct TokenInfo setup_info_shortcuts_3[] =
5551 {
5552   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
5553   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
5554   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
5555   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
5556   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
5557   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
5558   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
5559   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
5560   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
5561   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
5562   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
5563   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
5564   { TYPE_EMPTY,         NULL,                   ""                      },
5565   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5566
5567   { 0,                  NULL,                   NULL                    }
5568 };
5569
5570 static struct TokenInfo setup_info_shortcuts_4[] =
5571 {
5572   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
5573   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
5574   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
5575   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
5576   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
5577   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
5578   { TYPE_EMPTY,         NULL,                   ""                      },
5579   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5580
5581   { 0,                  NULL,                   NULL                    }
5582 };
5583
5584 static struct TokenInfo setup_info_shortcuts_5[] =
5585 {
5586   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
5587   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
5588   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
5589   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
5590   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
5591   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
5592   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
5593   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
5594   { TYPE_EMPTY,         NULL,                   ""                      },
5595   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5596
5597   { 0,                  NULL,                   NULL                    }
5598 };
5599
5600 static Key getSetupKey()
5601 {
5602   Key key = KSYM_UNDEFINED;
5603   boolean got_key_event = FALSE;
5604
5605   while (!got_key_event)
5606   {
5607     if (PendingEvent())         /* got event */
5608     {
5609       Event event;
5610
5611       WaitEvent(&event);
5612
5613       switch (event.type)
5614       {
5615         case EVENT_KEYPRESS:
5616           {
5617             key = GetEventKey((KeyEvent *)&event, TRUE);
5618
5619             /* press 'Escape' or 'Enter' to keep the existing key binding */
5620             if (key == KSYM_Escape || key == KSYM_Return)
5621               key = KSYM_UNDEFINED;     /* keep old value */
5622
5623             got_key_event = TRUE;
5624           }
5625           break;
5626
5627         case EVENT_KEYRELEASE:
5628           key_joystick_mapping = 0;
5629           break;
5630
5631         default:
5632           HandleOtherEvents(&event);
5633           break;
5634       }
5635     }
5636
5637     BackToFront();
5638   }
5639
5640   return key;
5641 }
5642
5643 static int getSetupValueFont(int type, void *value)
5644 {
5645   if (type & TYPE_GHOSTED)
5646     return FONT_OPTION_OFF;
5647   else if (type & TYPE_KEY)
5648     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
5649   else if (type & TYPE_STRING)
5650     return FONT_VALUE_2;
5651   else if (type & TYPE_ECS_AGA)
5652     return FONT_VALUE_1;
5653   else if (type & TYPE_BOOLEAN_STYLE)
5654     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
5655   else if (type & TYPE_YES_NO_AUTO)
5656     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
5657             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
5658   else
5659     return FONT_VALUE_1;
5660 }
5661
5662 static int getSetupValueFontNarrow(int type, int font_nr)
5663 {
5664   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
5665           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
5666           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
5667           font_nr);
5668 }
5669
5670 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
5671 {
5672   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
5673   struct TokenInfo *si = &setup_info[si_pos];
5674   boolean font_draw_xoffset_modified = FALSE;
5675   boolean scrollbar_needed = (num_setup_info < max_setup_info);
5676   int font_draw_xoffset_old = -1;
5677   int xoffset = (scrollbar_needed ? -1 : 0);
5678   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
5679   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
5680   int xpos = menu_screen_value_xpos;
5681   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
5682   int startx = mSX + xpos * 32;
5683   int starty = mSY + ypos * 32;
5684   int font_nr, font_nr_default, font_width_default;
5685   int type = si->type;
5686   void *value = si->value;
5687   char *value_string = getSetupValue(type, value);
5688   int i;
5689
5690   if (value_string == NULL)
5691     return;
5692
5693   if (type & TYPE_KEY)
5694   {
5695     xpos = MENU_SCREEN_START_XPOS;
5696
5697     if (type & TYPE_QUERY)
5698       value_string = "<press key>";
5699   }
5700   else if (type & TYPE_STRING)
5701   {
5702     int max_value_len = (SCR_FIELDX - 2) * 2;
5703
5704     xpos = MENU_SCREEN_START_XPOS;
5705
5706     if (strlen(value_string) > max_value_len)
5707       value_string[max_value_len] = '\0';
5708   }
5709   else if (type & TYPE_YES_NO_AUTO)
5710   {
5711     xpos = menu_screen_value_xpos - 1;
5712   }
5713
5714   startx = mSX + xpos * 32;
5715   starty = mSY + ypos * 32;
5716   font_nr_default = getSetupValueFont(type, value);
5717   font_width_default = getFontWidth(font_nr_default);
5718
5719   font_nr = font_nr_default;
5720
5721   // special check if right-side setup values moved left due to scrollbar
5722   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
5723   {
5724     int max_menu_text_length = 26;      // maximum text length for classic menu
5725     int font_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
5726     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
5727     int text_font_nr = getMenuTextFont(FONT_MENU_2);
5728     int text_font_xoffset = getFontBitmapInfo(text_font_nr)->draw_xoffset;
5729     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
5730
5731     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
5732     {
5733       xpos += 1;
5734       startx = mSX + xpos * 32;
5735
5736       font_nr = getSetupValueFontNarrow(type, font_nr);
5737     }
5738   }
5739
5740   /* downward compatibility correction for Juergen Bonhagen's menu settings */
5741   if (setup_mode != SETUP_MODE_INPUT)
5742   {
5743     int max_menu_text_length_big = (menu_screen_value_xpos -
5744                                     MENU_SCREEN_START_XPOS);
5745     int max_menu_text_length_medium = max_menu_text_length_big * 2;
5746     int check_font_nr = FONT_OPTION_ON; /* known font that needs correction */
5747     int font1_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
5748     int font2_xoffset = getFontBitmapInfo(check_font_nr)->draw_xoffset;
5749     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
5750     int text_font_nr = getMenuTextFont(FONT_MENU_2);
5751     int text_font_xoffset = getFontBitmapInfo(text_font_nr)->draw_xoffset;
5752     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
5753     boolean correct_font_draw_xoffset = FALSE;
5754
5755     if (xpos == MENU_SCREEN_START_XPOS &&
5756         startx + font1_xoffset < text_startx + text_font_xoffset)
5757       correct_font_draw_xoffset = TRUE;
5758
5759     if (xpos == menu_screen_value_xpos &&
5760         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
5761       correct_font_draw_xoffset = TRUE;
5762
5763     /* check if setup value would overlap with setup text when printed */
5764     /* (this can happen for extreme/wrong values for font draw offset) */
5765     if (correct_font_draw_xoffset)
5766     {
5767       font_draw_xoffset_old = getFontBitmapInfo(font_nr)->draw_xoffset;
5768       font_draw_xoffset_modified = TRUE;
5769
5770       if (type & TYPE_KEY)
5771         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
5772       else if (!(type & TYPE_STRING))
5773         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
5774           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
5775     }
5776   }
5777
5778   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
5779     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
5780
5781   DrawText(startx, starty, value_string, font_nr);
5782
5783   if (font_draw_xoffset_modified)
5784     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
5785 }
5786
5787 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
5788 {
5789   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
5790   struct TokenInfo *si = &setup_info[si_pos];
5791
5792   if (si->type & TYPE_BOOLEAN_STYLE)
5793   {
5794     *(boolean *)si->value ^= TRUE;
5795   }
5796   else if (si->type & TYPE_YES_NO_AUTO)
5797   {
5798     *(int *)si->value =
5799       (dx == -1 ?
5800        (*(int *)si->value == AUTO ? TRUE :
5801         *(int *)si->value == TRUE ? FALSE : AUTO) :
5802        (*(int *)si->value == TRUE ? AUTO :
5803         *(int *)si->value == AUTO ? FALSE : TRUE));
5804   }
5805   else if (si->type & TYPE_KEY)
5806   {
5807     Key key;
5808
5809     si->type |= TYPE_QUERY;
5810     drawSetupValue(screen_pos, setup_info_pos_raw);
5811     si->type &= ~TYPE_QUERY;
5812
5813     key = getSetupKey();
5814     if (key != KSYM_UNDEFINED)
5815       *(Key *)si->value = key;
5816   }
5817
5818   drawSetupValue(screen_pos, setup_info_pos_raw);
5819
5820   // fullscreen state may have changed at this point
5821   if (si->value == &setup.fullscreen)
5822     ToggleFullscreenOrChangeWindowScalingIfNeeded();
5823 }
5824
5825 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
5826 {
5827   static struct TokenInfo *setup_info_hide = NULL;
5828   int list_size = 0;
5829   int list_pos = 0;
5830   int i;
5831
5832   /* determine maximum list size of target list */
5833   while (setup_info_orig[list_size++].type != 0);
5834
5835   /* free, allocate and clear memory for target list */
5836   checked_free(setup_info_hide);
5837   setup_info_hide = checked_calloc(list_size * sizeof(struct TokenInfo));
5838
5839   /* copy setup info list without setup entries marked as hidden */
5840   for (i = 0; setup_info_orig[i].type != 0; i++)
5841     if (!hideSetupEntry(setup_info_orig[i].value))
5842       setup_info_hide[list_pos++] = setup_info_orig[i];
5843
5844   return setup_info_hide;
5845 }
5846
5847 static void DrawSetupScreen_Generic()
5848 {
5849   int fade_mask = REDRAW_FIELD;
5850   boolean redraw_all = FALSE;
5851   char *title_string = NULL;
5852   int i;
5853
5854   if (CheckIfGlobalBorderHasChanged())
5855     fade_mask = REDRAW_ALL;
5856
5857   UnmapAllGadgets();
5858   FadeMenuSoundsAndMusic();
5859
5860   FreeScreenGadgets();
5861   CreateScreenGadgets();
5862
5863   if (redraw_mask & REDRAW_ALL)
5864     redraw_all = TRUE;
5865
5866   FadeOut(fade_mask);
5867
5868   /* needed if different viewport properties defined for setup screen */
5869   ChangeViewportPropertiesIfNeeded();
5870
5871   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
5872
5873   ClearField();
5874
5875   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
5876
5877   if (setup_mode == SETUP_MODE_MAIN)
5878   {
5879     setup_info = setup_info_main;
5880     title_string = "Setup";
5881   }
5882   else if (setup_mode == SETUP_MODE_GAME)
5883   {
5884     setup_info = setup_info_game;
5885     title_string = "Setup Game";
5886   }
5887   else if (setup_mode == SETUP_MODE_EDITOR)
5888   {
5889     setup_info = setup_info_editor;
5890     title_string = "Setup Editor";
5891   }
5892   else if (setup_mode == SETUP_MODE_GRAPHICS)
5893   {
5894     setup_info = setup_info_graphics;
5895     title_string = "Setup Graphics";
5896   }
5897   else if (setup_mode == SETUP_MODE_SOUND)
5898   {
5899     setup_info = setup_info_sound;
5900     title_string = "Setup Sound";
5901   }
5902   else if (setup_mode == SETUP_MODE_ARTWORK)
5903   {
5904     setup_info = setup_info_artwork;
5905     title_string = "Custom Artwork";
5906   }
5907   else if (setup_mode == SETUP_MODE_TOUCH)
5908   {
5909     setup_info = setup_info_touch;
5910     title_string = "Setup Touch Ctrls";
5911
5912     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
5913       setup_info = setup_info_touch_wipe_gestures;
5914   }
5915   else if (setup_mode == SETUP_MODE_SHORTCUTS)
5916   {
5917     setup_info = setup_info_shortcuts;
5918     title_string = "Setup Shortcuts";
5919   }
5920   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
5921   {
5922     setup_info = setup_info_shortcuts_1;
5923     title_string = "Setup Shortcuts";
5924   }
5925   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
5926   {
5927     setup_info = setup_info_shortcuts_2;
5928     title_string = "Setup Shortcuts";
5929   }
5930   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
5931   {
5932     setup_info = setup_info_shortcuts_3;
5933     title_string = "Setup Shortcuts";
5934   }
5935   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
5936   {
5937     setup_info = setup_info_shortcuts_4;
5938     title_string = "Setup Shortcuts";
5939   }
5940   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
5941   {
5942     setup_info = setup_info_shortcuts_5;
5943     title_string = "Setup Shortcuts";
5944   }
5945
5946   /* use modified setup info without setup entries marked as hidden */
5947   setup_info = getSetupInfoFinal(setup_info);
5948
5949   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
5950
5951   // determine maximal number of setup entries that can be displayed on screen
5952   num_setup_info = 0;
5953   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
5954     num_setup_info++;
5955
5956   // determine maximal number of setup entries available for this setup screen
5957   max_setup_info = 0;
5958   for (i = 0; setup_info[i].type != 0; i++)
5959     max_setup_info++;
5960
5961   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
5962
5963   MapScreenGadgets(max_setup_info);
5964
5965   if (redraw_all)
5966     redraw_mask = fade_mask = REDRAW_ALL;
5967
5968   DrawMaskedBorder(fade_mask);
5969
5970   FadeIn(fade_mask);
5971 }
5972
5973 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
5974 {
5975   menu_info = setup_info;
5976
5977   HandleMenuScreen(mx, my, dx, dy, button,
5978                    setup_mode, num_setup_info, max_setup_info);
5979 }
5980
5981 void DrawSetupScreen_Input()
5982 {
5983   int i;
5984
5985   FadeOut(REDRAW_FIELD);
5986
5987   ClearField();
5988
5989   setup_info = setup_info_input;
5990
5991   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Setup Input");
5992
5993   for (i = 0; setup_info[i].type != 0 && i < MAX_MENU_ENTRIES_ON_SCREEN; i++)
5994   {
5995     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
5996       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
5997     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
5998       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
5999     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
6000       initCursor(i, IMG_MENU_BUTTON);
6001
6002     DrawCursorAndText_Setup(i, -1, FALSE);
6003   }
6004
6005   /* create gadgets for setup input menu screen */
6006   FreeScreenGadgets();
6007   CreateScreenGadgets();
6008
6009   /* map gadgets for setup input menu screen */
6010   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
6011
6012   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
6013
6014   FadeIn(REDRAW_FIELD);
6015 }
6016
6017 static void setJoystickDeviceToNr(char *device_name, int device_nr)
6018 {
6019   if (device_name == NULL)
6020     return;
6021
6022   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
6023     device_nr = 0;
6024
6025   if (strlen(device_name) > 1)
6026   {
6027     char c1 = device_name[strlen(device_name) - 1];
6028     char c2 = device_name[strlen(device_name) - 2];
6029
6030     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
6031       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
6032   }
6033   else
6034     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
6035             strlen(device_name));
6036 }
6037
6038 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
6039 {
6040   int i;
6041   static struct SetupKeyboardInfo custom_key;
6042   static struct
6043   {
6044     Key *key;
6045     char *text;
6046   } custom[] =
6047   {
6048     { &custom_key.left,  "Axis/Pad Left"  },
6049     { &custom_key.right, "Axis/Pad Right" },
6050     { &custom_key.up,    "Axis/Pad Up"    },
6051     { &custom_key.down,  "Axis/Pad Down"  },
6052     { &custom_key.snap,  "Button 1/A/X"   },
6053     { &custom_key.drop,  "Button 2/B/Y"   }
6054   };
6055   static char *joystick_name[MAX_PLAYERS] =
6056   {
6057     "Joystick1",
6058     "Joystick2",
6059     "Joystick3",
6060     "Joystick4"
6061   };
6062   int text_font_nr = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
6063
6064   custom_key = setup.input[player_nr].key;
6065
6066   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
6067            FONT_INPUT_1_ACTIVE);
6068
6069   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
6070                              TILEX, TILEY);
6071   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
6072                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
6073
6074   if (setup.input[player_nr].use_joystick)
6075   {
6076     char *device_name = setup.input[player_nr].joy.device_name;
6077     int joystick_nr = getJoystickNrFromDeviceName(device_name);
6078     boolean joystick_active = CheckJoystickOpened(joystick_nr);
6079     char *text = joystick_name[joystick_nr];
6080     int font_nr = (joystick_active ? FONT_VALUE_1 : FONT_VALUE_OLD);
6081
6082     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
6083     DrawText(mSX + 32, mSY + 4 * 32, "Configure", text_font_nr);
6084   }
6085   else
6086   {
6087     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", FONT_VALUE_1);
6088     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", text_font_nr);
6089   }
6090
6091   DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", FONT_MENU_1);
6092
6093   drawCursorXY(1, 4, IMG_MENU_BUTTON_LEFT);
6094   drawCursorXY(1, 5, IMG_MENU_BUTTON_RIGHT);
6095   drawCursorXY(1, 6, IMG_MENU_BUTTON_UP);
6096   drawCursorXY(1, 7, IMG_MENU_BUTTON_DOWN);
6097
6098   DrawText(mSX + 2 * 32, mSY +  6 * 32, ":", FONT_VALUE_OLD);
6099   DrawText(mSX + 2 * 32, mSY +  7 * 32, ":", FONT_VALUE_OLD);
6100   DrawText(mSX + 2 * 32, mSY +  8 * 32, ":", FONT_VALUE_OLD);
6101   DrawText(mSX + 2 * 32, mSY +  9 * 32, ":", FONT_VALUE_OLD);
6102   DrawText(mSX + 1 * 32, mSY + 10 * 32, "Snap Field:", FONT_VALUE_OLD);
6103   DrawText(mSX + 1 * 32, mSY + 12 * 32, "Drop Element:", FONT_VALUE_OLD);
6104
6105   for (i = 0; i < 6; i++)
6106   {
6107     int ypos = 6 + i + (i > 3 ? i-3 : 0);
6108
6109     DrawText(mSX + 3 * 32, mSY + ypos * 32,
6110              "              ", FONT_VALUE_1);
6111     DrawText(mSX + 3 * 32, mSY + ypos * 32,
6112              (setup.input[player_nr].use_joystick ?
6113               custom[i].text :
6114               getKeyNameFromKey(*custom[i].key)), FONT_VALUE_1);
6115   }
6116 }
6117
6118 static int input_player_nr = 0;
6119
6120 void HandleSetupScreen_Input_Player(int step, int direction)
6121 {
6122   int old_player_nr = input_player_nr;
6123   int new_player_nr;
6124
6125   new_player_nr = old_player_nr + step * direction;
6126   if (new_player_nr < 0)
6127     new_player_nr = 0;
6128   if (new_player_nr > MAX_PLAYERS - 1)
6129     new_player_nr = MAX_PLAYERS - 1;
6130
6131   if (new_player_nr != old_player_nr)
6132   {
6133     input_player_nr = new_player_nr;
6134
6135     drawPlayerSetupInputInfo(input_player_nr, FALSE);
6136   }
6137 }
6138
6139 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
6140 {
6141   static int choice = 0;
6142   int x = 0;
6143   int y = choice;
6144   int pos_start  = SETUPINPUT_SCREEN_POS_START;
6145   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
6146   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
6147   int pos_end    = SETUPINPUT_SCREEN_POS_END;
6148
6149   if (button == MB_MENU_INITIALIZE)
6150   {
6151     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
6152
6153     DrawCursorAndText_Setup(choice, -1, TRUE);
6154
6155     return;
6156   }
6157   else if (button == MB_MENU_LEAVE)
6158   {
6159     setup_mode = SETUP_MODE_MAIN;
6160     DrawSetupScreen();
6161     InitJoysticks();
6162
6163     return;
6164   }
6165
6166   if (mx || my)         /* mouse input */
6167   {
6168     x = (mx - mSX) / 32;
6169     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
6170   }
6171   else if (dx || dy)    /* keyboard input */
6172   {
6173     if (dx && choice == 0)
6174       x = (dx < 0 ? 10 : 12);
6175     else if ((dx && choice == 1) ||
6176              (dx == -1 && choice == pos_end))
6177       button = MB_MENU_CHOICE;
6178     else if (dy)
6179       y = choice + dy;
6180
6181     if (y >= pos_empty1 && y <= pos_empty2)
6182       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
6183   }
6184
6185   if (y == 0 && dx != 0 && button)
6186   {
6187     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
6188   }
6189   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
6190            y >= pos_start && y <= pos_end &&
6191            !(y >= pos_empty1 && y <= pos_empty2))
6192   {
6193     if (button)
6194     {
6195       if (y != choice)
6196       {
6197         DrawCursorAndText_Setup(choice, -1, FALSE);
6198         DrawCursorAndText_Setup(y, -1, TRUE);
6199
6200         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
6201
6202         choice = y;
6203       }
6204     }
6205     else
6206     {
6207       if (y == 1)
6208       {
6209         char *device_name = setup.input[input_player_nr].joy.device_name;
6210
6211         if (!setup.input[input_player_nr].use_joystick)
6212         {
6213           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
6214
6215           setJoystickDeviceToNr(device_name, new_device_nr);
6216           setup.input[input_player_nr].use_joystick = TRUE;
6217         }
6218         else
6219         {
6220           int device_nr = getJoystickNrFromDeviceName(device_name);
6221           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
6222
6223           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
6224             setup.input[input_player_nr].use_joystick = FALSE;
6225           else
6226             setJoystickDeviceToNr(device_name, new_device_nr);
6227         }
6228
6229         drawPlayerSetupInputInfo(input_player_nr, FALSE);
6230       }
6231       else if (y == 2)
6232       {
6233         if (setup.input[input_player_nr].use_joystick)
6234           ConfigureJoystick(input_player_nr);
6235         else
6236           CustomizeKeyboard(input_player_nr);
6237       }
6238       else if (y == pos_end)
6239       {
6240         InitJoysticks();
6241
6242         FadeSetLeaveMenu();
6243
6244         setup_mode = SETUP_MODE_MAIN;
6245         DrawSetupScreen();
6246       }
6247     }
6248   }
6249 }
6250
6251 void CustomizeKeyboard(int player_nr)
6252 {
6253   int i;
6254   int step_nr;
6255   boolean finished = FALSE;
6256   static struct SetupKeyboardInfo custom_key;
6257   static struct
6258   {
6259     Key *key;
6260     char *text;
6261   } customize_step[] =
6262   {
6263     { &custom_key.left,  "Move Left"    },
6264     { &custom_key.right, "Move Right"   },
6265     { &custom_key.up,    "Move Up"      },
6266     { &custom_key.down,  "Move Down"    },
6267     { &custom_key.snap,  "Snap Field"   },
6268     { &custom_key.drop,  "Drop Element" }
6269   };
6270
6271   /* read existing key bindings from player setup */
6272   custom_key = setup.input[player_nr].key;
6273
6274   FadeSetEnterMenu();
6275   FadeOut(REDRAW_FIELD);
6276
6277   ClearField();
6278
6279   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
6280
6281   step_nr = 0;
6282   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
6283            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
6284   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
6285            "Key:", FONT_INPUT_1_ACTIVE);
6286   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6287            getKeyNameFromKey(*customize_step[step_nr].key), FONT_VALUE_OLD);
6288
6289   FadeIn(REDRAW_FIELD);
6290
6291   while (!finished)
6292   {
6293     if (PendingEvent())         /* got event */
6294     {
6295       Event event;
6296
6297       WaitEvent(&event);
6298
6299       switch (event.type)
6300       {
6301         case EVENT_KEYPRESS:
6302           {
6303             Key key = GetEventKey((KeyEvent *)&event, FALSE);
6304
6305             if (key == KSYM_Escape || (key == KSYM_Return && step_nr == 6))
6306             {
6307               if (key == KSYM_Escape)
6308                 FadeSkipNextFadeIn();
6309
6310               finished = TRUE;
6311               break;
6312             }
6313
6314             /* all keys configured -- wait for "Escape" or "Return" key */
6315             if (step_nr == 6)
6316               break;
6317
6318             /* press 'Enter' to keep the existing key binding */
6319             if (key == KSYM_Return)
6320               key = *customize_step[step_nr].key;
6321
6322             /* check if key already used */
6323             for (i = 0; i < step_nr; i++)
6324               if (*customize_step[i].key == key)
6325                 break;
6326             if (i < step_nr)
6327               break;
6328
6329             /* got new key binding */
6330             *customize_step[step_nr].key = key;
6331             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6332                      "             ", FONT_VALUE_1);
6333             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6334                      getKeyNameFromKey(key), FONT_VALUE_1);
6335             step_nr++;
6336
6337             /* un-highlight last query */
6338             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
6339                      customize_step[step_nr - 1].text, FONT_MENU_1);
6340             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
6341                      "Key:", FONT_MENU_1);
6342
6343             /* press 'Enter' to leave */
6344             if (step_nr == 6)
6345             {
6346               DrawText(mSX + 16, mSY + 15 * 32 + 16,
6347                        "Press Enter", FONT_TITLE_1);
6348               break;
6349             }
6350
6351             /* query next key binding */
6352             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
6353                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
6354             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
6355                      "Key:", FONT_INPUT_1_ACTIVE);
6356             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6357                      getKeyNameFromKey(*customize_step[step_nr].key),
6358                      FONT_VALUE_OLD);
6359           }
6360           break;
6361
6362         case EVENT_KEYRELEASE:
6363           key_joystick_mapping = 0;
6364           break;
6365
6366         default:
6367           HandleOtherEvents(&event);
6368           break;
6369       }
6370     }
6371
6372     BackToFront();
6373   }
6374
6375   /* write new key bindings back to player setup */
6376   setup.input[player_nr].key = custom_key;
6377
6378   DrawSetupScreen_Input();
6379 }
6380
6381 /* game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com> */
6382
6383 #define MARKER_BUTTON           1
6384 #define MARKER_AXIS_X           2
6385 #define MARKER_AXIS_Y           3
6386
6387 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
6388 {
6389 #if defined(TARGET_SDL2)
6390   static boolean bitmaps_initialized = FALSE;
6391   boolean screen_initialized = FALSE;
6392   static Bitmap *controller, *button, *axis_x, *axis_y;
6393   char *name;
6394   boolean success = TRUE;
6395   boolean done = FALSE, next = FALSE;
6396   Event event;
6397   int alpha = 200, alpha_step = -1;
6398   int alpha_ticks = 0;
6399   char mapping[4096], temp[4096];
6400   int font_name = FONT_TEXT_1;
6401   int font_info = FONT_REQUEST;
6402   int ystep1 = getFontHeight(font_name) + 2;
6403   int ystep2 = getFontHeight(font_info) + 2;
6404   int i, j;
6405
6406   struct
6407   {
6408     int x, y;
6409     int marker;
6410     char *field;
6411     int axis, button, hat, hat_value;
6412     char mapping[4096];
6413   }
6414   *step, *prev_step, steps[] =
6415   {
6416     { 356, 155, MARKER_BUTTON, "a",             },
6417     { 396, 122, MARKER_BUTTON, "b",             },
6418     { 320, 125, MARKER_BUTTON, "x",             },
6419     { 358,  95, MARKER_BUTTON, "y",             },
6420     { 162, 125, MARKER_BUTTON, "back",          },
6421     { 216, 125, MARKER_BUTTON, "guide",         },
6422     { 271, 125, MARKER_BUTTON, "start",         },
6423     { 110, 200, MARKER_BUTTON, "dpleft",        },
6424     { 146, 228, MARKER_BUTTON, "dpdown",        },
6425     { 178, 200, MARKER_BUTTON, "dpright",       },
6426     { 146, 172, MARKER_BUTTON, "dpup",          },
6427     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
6428     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
6429     { 382,  40, MARKER_BUTTON, "rightshoulder", },
6430     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
6431     {  73, 141, MARKER_BUTTON, "leftstick",     },
6432     { 282, 210, MARKER_BUTTON, "rightstick",    },
6433     {  73, 141, MARKER_AXIS_X, "leftx",         },
6434     {  73, 141, MARKER_AXIS_Y, "lefty",         },
6435     { 282, 210, MARKER_AXIS_X, "rightx",        },
6436     { 282, 210, MARKER_AXIS_Y, "righty",        },
6437   };
6438
6439   unsigned int event_frame_delay = 0;
6440   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
6441
6442   ResetDelayCounter(&event_frame_delay);
6443
6444   if (!bitmaps_initialized)
6445   {
6446     controller = LoadCustomImage("joystick/controller.png");
6447     button     = LoadCustomImage("joystick/button.png");
6448     axis_x     = LoadCustomImage("joystick/axis_x.png");
6449     axis_y     = LoadCustomImage("joystick/axis_y.png");
6450
6451     bitmaps_initialized = TRUE;
6452   }
6453
6454   name = getFormattedJoystickName(SDL_JoystickName(joystick));
6455
6456 #if DEBUG_JOYSTICKS
6457   /* print info about the joystick we are watching */
6458   Error(ERR_DEBUG, "watching joystick %d: (%s)\n",
6459         SDL_JoystickInstanceID(joystick), name);
6460   Error(ERR_DEBUG, "joystick has %d axes, %d hats, %d balls, and %d buttons\n",
6461         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
6462         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
6463 #endif
6464
6465   /* initialize mapping with GUID and name */
6466   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
6467
6468   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
6469            temp, name, SDL_GetPlatform());
6470
6471   /* loop through all steps (buttons and axes), getting joystick events */
6472   for (i = 0; i < SDL_arraysize(steps) && !done;)
6473   {
6474     Bitmap *marker = button;    /* initialize with reliable default value */
6475
6476     step = &steps[i];
6477     strcpy(step->mapping, mapping);
6478     step->axis = -1;
6479     step->button = -1;
6480     step->hat = -1;
6481     step->hat_value = -1;
6482
6483     marker = (step->marker == MARKER_BUTTON ? button :
6484               step->marker == MARKER_AXIS_X ? axis_x :
6485               step->marker == MARKER_AXIS_Y ? axis_y : marker);
6486
6487     next = FALSE;
6488
6489     while (!done && !next)
6490     {
6491       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
6492       alpha_ticks = SDL_GetTicks();
6493
6494       if (alpha >= 255)
6495       {
6496         alpha = 255;
6497         alpha_step = -1;
6498       }
6499       else if (alpha < 128)
6500       {
6501         alpha = 127;
6502         alpha_step = 1;
6503       }
6504
6505       int controller_x = SX + (SXSIZE - controller->width) / 2;
6506       int controller_y = SY + ystep2;
6507
6508       int marker_x = controller_x + step->x;
6509       int marker_y = controller_y + step->y;
6510
6511       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
6512       int ystart2 = ystart1 + ystep1 + ystep2;
6513
6514       ClearField();
6515
6516       DrawTextSCentered(ystart1, font_name, name);
6517
6518       DrawTextSCentered(ystart2 + 0 * ystep2, font_info,
6519                         "Press buttons and move axes on");
6520       DrawTextSCentered(ystart2 + 1 * ystep2, font_info,
6521                         "your controller when indicated.");
6522       DrawTextSCentered(ystart2 + 2 * ystep2, font_info,
6523                         "(Your controller may look different.)");
6524
6525 #if defined(PLATFORM_ANDROID)
6526       DrawTextSCentered(ystart2 + 4 * ystep2, font_info,
6527                         "To correct a mistake,");
6528       DrawTextSCentered(ystart2 + 5 * ystep2, font_info,
6529                         "press the 'back' button.");
6530       DrawTextSCentered(ystart2 + 6 * ystep2, font_info,
6531                         "To skip a button or axis,");
6532       DrawTextSCentered(ystart2 + 7 * ystep2, font_info,
6533                         "press the 'menu' button.");
6534 #else
6535       DrawTextSCentered(ystart2 + 4 * ystep2, font_info,
6536                         "To correct a mistake,");
6537       DrawTextSCentered(ystart2 + 5 * ystep2, font_info,
6538                         "press the 'backspace' key.");
6539       DrawTextSCentered(ystart2 + 6 * ystep2, font_info,
6540                         "To skip a button or axis,");
6541       DrawTextSCentered(ystart2 + 7 * ystep2, font_info,
6542                         "press the 'return' key.");
6543
6544       DrawTextSCentered(ystart2 + 8 * ystep2, font_info,
6545                         "To exit, press the 'escape' key.");
6546 #endif
6547
6548       BlitBitmapMasked(controller, drawto, 0, 0,
6549                        controller->width, controller->height,
6550                        controller_x, controller_y);
6551
6552       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
6553
6554       BlitBitmapMasked(marker, drawto, 0, 0,
6555                        marker->width, marker->height,
6556                        marker_x, marker_y);
6557
6558       if (!screen_initialized)
6559         FadeIn(REDRAW_FIELD);
6560       else
6561         BackToFront();
6562
6563       screen_initialized = TRUE;
6564
6565       while (NextValidEvent(&event))
6566       {
6567         switch (event.type)
6568         {
6569           case SDL_JOYAXISMOTION:
6570             if (event.jaxis.value > 20000 ||
6571                 event.jaxis.value < -20000)
6572             {
6573               for (j = 0; j < i; j++)
6574                 if (steps[j].axis == event.jaxis.axis)
6575                   break;
6576
6577               if (j == i)
6578               {
6579                 if (step->marker != MARKER_AXIS_X &&
6580                     step->marker != MARKER_AXIS_Y)
6581                   break;
6582
6583                 step->axis = event.jaxis.axis;
6584                 strcat(mapping, step->field);
6585                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
6586                 strcat(mapping, temp);
6587                 i++;
6588                 next = TRUE;
6589               }
6590             }
6591
6592             break;
6593
6594           case SDL_JOYHATMOTION:
6595             /* ignore centering; we're probably just coming back
6596                to the center from the previous item we set */
6597             if (event.jhat.value == SDL_HAT_CENTERED)
6598               break;
6599
6600             for (j = 0; j < i; j++)
6601               if (steps[j].hat == event.jhat.hat &&
6602                   steps[j].hat_value == event.jhat.value)
6603                 break;
6604
6605             if (j == i)
6606             {
6607               step->hat = event.jhat.hat;
6608               step->hat_value = event.jhat.value;
6609               strcat(mapping, step->field);
6610               snprintf(temp, sizeof(temp), ":h%u.%u,",
6611                        event.jhat.hat, event.jhat.value );
6612               strcat(mapping, temp);
6613               i++;
6614               next = TRUE;
6615             }
6616
6617             break;
6618
6619           case SDL_JOYBALLMOTION:
6620             break;
6621
6622           case SDL_JOYBUTTONUP:
6623             for (j = 0; j < i; j++)
6624               if (steps[j].button == event.jbutton.button)
6625                 break;
6626
6627             if (j == i)
6628             {
6629               step->button = event.jbutton.button;
6630               strcat(mapping, step->field);
6631               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
6632               strcat(mapping, temp);
6633               i++;
6634               next = TRUE;
6635             }
6636
6637             break;
6638
6639           case SDL_FINGERDOWN:
6640           case SDL_MOUSEBUTTONDOWN:
6641             /* skip this step */
6642             i++;
6643             next = TRUE;
6644
6645             break;
6646
6647           case SDL_KEYDOWN:
6648             if (event.key.keysym.sym == KSYM_BackSpace ||
6649                 event.key.keysym.sym == KSYM_Back)
6650             {
6651               if (i == 0)
6652               {
6653                 /* leave screen */
6654                 success = FALSE;
6655                 done = TRUE;
6656               }
6657
6658               /* undo this step */
6659               prev_step = &steps[i - 1];
6660               strcpy(mapping, prev_step->mapping);
6661               i--;
6662               next = TRUE;
6663
6664               break;
6665             }
6666
6667             if (event.key.keysym.sym == KSYM_space ||
6668                 event.key.keysym.sym == KSYM_Return ||
6669                 event.key.keysym.sym == KSYM_Menu)
6670             {
6671               /* skip this step */
6672               i++;
6673               next = TRUE;
6674
6675               break;
6676             }
6677
6678             if (event.key.keysym.sym == KSYM_Escape)
6679             {
6680               /* leave screen */
6681               success = FALSE;
6682               done = TRUE;
6683             }
6684
6685             break;
6686
6687           case SDL_QUIT:
6688             program.exit_function(0);
6689             break;
6690
6691           default:
6692             break;
6693         }
6694
6695         // do not handle events for longer than standard frame delay period
6696         if (DelayReached(&event_frame_delay, event_frame_delay_value))
6697           break;
6698       }
6699     }
6700   }
6701
6702   if (success)
6703   {
6704 #if DEBUG_JOYSTICKS
6705     Error(ERR_DEBUG, "New game controller mapping:\n\n%s\n\n", mapping);
6706 #endif
6707
6708     // activate mapping for this game
6709     SDL_GameControllerAddMapping(mapping);
6710
6711     // save mapping to personal mappings
6712     SaveSetup_AddGameControllerMapping(mapping);
6713   }
6714
6715   /* wait until the last pending event was removed from event queue */
6716   while (NextValidEvent(&event));
6717
6718   return success;
6719 #else
6720   return TRUE;
6721 #endif
6722 }
6723
6724 static int ConfigureJoystickMain(int player_nr)
6725 {
6726   char *device_name = setup.input[player_nr].joy.device_name;
6727   int joystick_nr = getJoystickNrFromDeviceName(device_name);
6728   boolean joystick_active = CheckJoystickOpened(joystick_nr);
6729   int success = FALSE;
6730   int i;
6731
6732   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
6733     return JOYSTICK_NOT_AVAILABLE;
6734
6735   if (!joystick_active || !setup.input[player_nr].use_joystick)
6736     return JOYSTICK_NOT_AVAILABLE;
6737
6738   FadeSetEnterMenu();
6739   FadeOut(REDRAW_FIELD);
6740
6741   // close all joystick devices (potentially opened as game controllers)
6742   for (i = 0; i < SDL_NumJoysticks(); i++)
6743     SDLCloseJoystick(i);
6744
6745   // open joystick device as plain joystick to configure as game controller
6746   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
6747
6748   // as the joystick was successfully opened before, this should not happen
6749   if (joystick == NULL)
6750     return FALSE;
6751
6752   // create new game controller mapping (buttons and axes) for joystick device
6753   success = ConfigureJoystickMapButtonsAndAxes(joystick);
6754
6755   // close joystick (and maybe re-open as configured game controller later)
6756   SDL_JoystickClose(joystick);
6757
6758   // re-open all joystick devices (potentially as game controllers)
6759   for (i = 0; i < SDL_NumJoysticks(); i++)
6760     SDLOpenJoystick(i);
6761
6762   // clear all joystick input actions for all joystick devices
6763   SDLClearJoystickState();
6764
6765   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
6766 }
6767
6768 void ConfigureJoystick(int player_nr)
6769 {
6770   boolean state = ConfigureJoystickMain(player_nr);
6771
6772   if (state != JOYSTICK_NOT_CONFIGURED)
6773   {
6774     boolean success = (state == JOYSTICK_CONFIGURED);
6775     char *message = (success ? " IS CONFIGURED! " : " NOT AVAILABLE! ");
6776     char *device_name = setup.input[player_nr].joy.device_name;
6777     int nr = getJoystickNrFromDeviceName(device_name) + 1;
6778     int xpos = mSX - SX;
6779     int ypos = mSY - SY;
6780     unsigned int wait_frame_delay = 0;
6781     unsigned int wait_frame_delay_value = 2000;
6782
6783     ResetDelayCounter(&wait_frame_delay);
6784
6785     ClearField();
6786
6787     DrawTextF(xpos + 16, ypos + 6 * 32, FONT_TITLE_1, "   JOYSTICK %d   ", nr);
6788     DrawTextF(xpos + 16, ypos + 7 * 32, FONT_TITLE_1, message);
6789
6790     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
6791       BackToFront();
6792
6793     ClearEventQueue();
6794   }
6795
6796   DrawSetupScreen_Input();
6797 }
6798
6799 void DrawSetupScreen()
6800 {
6801   if (setup_mode == SETUP_MODE_INPUT)
6802     DrawSetupScreen_Input();
6803   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
6804     DrawChooseTree(&game_speed_current);
6805   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
6806     DrawChooseTree(&scroll_delay_current);
6807   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
6808     DrawChooseTree(&snapshot_mode_current);
6809   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6810     DrawChooseTree(&window_size_current);
6811   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
6812     DrawChooseTree(&scaling_type_current);
6813   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
6814     DrawChooseTree(&rendering_mode_current);
6815   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
6816     DrawChooseTree(&artwork.gfx_current);
6817   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
6818     DrawChooseTree(&artwork.snd_current);
6819   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
6820     DrawChooseTree(&artwork.mus_current);
6821   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
6822     DrawChooseTree(&volume_simple_current);
6823   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
6824     DrawChooseTree(&volume_loops_current);
6825   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
6826     DrawChooseTree(&volume_music_current);
6827   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
6828     DrawChooseTree(&touch_control_current);
6829   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
6830     DrawChooseTree(&move_distance_current);
6831   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
6832     DrawChooseTree(&drop_distance_current);
6833   else
6834     DrawSetupScreen_Generic();
6835
6836   PlayMenuSoundsAndMusic();
6837 }
6838
6839 void RedrawSetupScreenAfterFullscreenToggle()
6840 {
6841   if (setup_mode == SETUP_MODE_GRAPHICS ||
6842       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6843   {
6844     // update list selection from "setup.window_scaling_percent"
6845     execSetupGraphics_setWindowSizes(TRUE);
6846
6847     DrawSetupScreen();
6848   }
6849 }
6850
6851 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
6852 {
6853   if (setup_mode == SETUP_MODE_INPUT)
6854     HandleSetupScreen_Input(mx, my, dx, dy, button);
6855   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
6856     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
6857   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
6858     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
6859   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
6860     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
6861   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6862     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
6863   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
6864     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
6865   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
6866     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
6867   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
6868     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
6869   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
6870     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
6871   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
6872     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
6873   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
6874     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
6875   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
6876     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
6877   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
6878     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
6879   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
6880     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
6881   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
6882     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
6883   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
6884     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
6885   else
6886     HandleSetupScreen_Generic(mx, my, dx, dy, button);
6887 }
6888
6889 void HandleGameActions()
6890 {
6891   if (game_status != GAME_MODE_PLAYING)
6892     return;
6893
6894   GameActions();        /* main game loop */
6895
6896   if (tape.auto_play && !tape.playing)
6897     AutoPlayTape();     /* continue automatically playing next tape */
6898 }
6899
6900
6901 /* ---------- new screen button stuff -------------------------------------- */
6902
6903 static void getScreenMenuButtonPos(int *x, int *y, int gadget_id)
6904 {
6905   switch (gadget_id)
6906   {
6907     case SCREEN_CTRL_ID_PREV_LEVEL:
6908       *x = mSX + GDI_ACTIVE_POS(menu.main.button.prev_level.x);
6909       *y = mSY + GDI_ACTIVE_POS(menu.main.button.prev_level.y);
6910       break;
6911
6912     case SCREEN_CTRL_ID_NEXT_LEVEL:
6913       *x = mSX + GDI_ACTIVE_POS(menu.main.button.next_level.x);
6914       *y = mSY + GDI_ACTIVE_POS(menu.main.button.next_level.y);
6915       break;
6916
6917     case SCREEN_CTRL_ID_PREV_PLAYER:
6918       *x = mSX + TILEX * 10;
6919       *y = mSY + TILEY * MENU_SCREEN_START_YPOS;
6920       break;
6921
6922     case SCREEN_CTRL_ID_NEXT_PLAYER:
6923       *x = mSX + TILEX * 12;
6924       *y = mSY + TILEY * MENU_SCREEN_START_YPOS;
6925       break;
6926
6927     default:
6928       Error(ERR_EXIT, "unknown gadget ID %d", gadget_id);
6929   }
6930 }
6931
6932 static struct
6933 {
6934   int gfx_unpressed, gfx_pressed;
6935   void (*get_gadget_position)(int *, int *, int);
6936   int gadget_id;
6937   int screen_mask;
6938   char *infotext;
6939 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
6940 {
6941   {
6942     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
6943     getScreenMenuButtonPos,
6944     SCREEN_CTRL_ID_PREV_LEVEL,
6945     SCREEN_MASK_MAIN,
6946     "last level"
6947   },
6948   {
6949     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
6950     getScreenMenuButtonPos,
6951     SCREEN_CTRL_ID_NEXT_LEVEL,
6952     SCREEN_MASK_MAIN,
6953     "next level"
6954   },
6955   {
6956     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
6957     getScreenMenuButtonPos,
6958     SCREEN_CTRL_ID_PREV_PLAYER,
6959     SCREEN_MASK_INPUT,
6960     "last player"
6961   },
6962   {
6963     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
6964     getScreenMenuButtonPos,
6965     SCREEN_CTRL_ID_NEXT_PLAYER,
6966     SCREEN_MASK_INPUT,
6967     "next player"
6968   },
6969 };
6970
6971 static struct
6972 {
6973   int gfx_unpressed, gfx_pressed;
6974   int x, y;
6975   int gadget_id;
6976   char *infotext;
6977 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
6978 {
6979   {
6980     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
6981     -1, -1,     /* these values are not constant, but can change at runtime */
6982     SCREEN_CTRL_ID_SCROLL_UP,
6983     "scroll up"
6984   },
6985   {
6986     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
6987     -1, -1,     /* these values are not constant, but can change at runtime */
6988     SCREEN_CTRL_ID_SCROLL_DOWN,
6989     "scroll down"
6990   }
6991 };
6992
6993 static struct
6994 {
6995   int gfx_unpressed, gfx_pressed;
6996   int x, y;
6997   int width, height;
6998   int type;
6999   int gadget_id;
7000   char *infotext;
7001 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
7002 {
7003   {
7004     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
7005     -1, -1,     /* these values are not constant, but can change at runtime */
7006     -1, -1,     /* these values are not constant, but can change at runtime */
7007     GD_TYPE_SCROLLBAR_VERTICAL,
7008     SCREEN_CTRL_ID_SCROLL_VERTICAL,
7009     "scroll level series vertically"
7010   }
7011 };
7012
7013 static void CreateScreenMenubuttons()
7014 {
7015   struct GadgetInfo *gi;
7016   unsigned int event_mask;
7017   int i;
7018
7019   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
7020   {
7021     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7022     int gfx_unpressed, gfx_pressed;
7023     int x, y, width, height;
7024     int gd_x1, gd_x2, gd_y1, gd_y2;
7025     int id = menubutton_info[i].gadget_id;
7026
7027     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
7028
7029     menubutton_info[i].get_gadget_position(&x, &y, id);
7030
7031     width = SC_MENUBUTTON_XSIZE;
7032     height = SC_MENUBUTTON_YSIZE;
7033
7034     gfx_unpressed = menubutton_info[i].gfx_unpressed;
7035     gfx_pressed   = menubutton_info[i].gfx_pressed;
7036     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7037     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7038     gd_x1 = graphic_info[gfx_unpressed].src_x;
7039     gd_y1 = graphic_info[gfx_unpressed].src_y;
7040     gd_x2 = graphic_info[gfx_pressed].src_x;
7041     gd_y2 = graphic_info[gfx_pressed].src_y;
7042
7043     gi = CreateGadget(GDI_CUSTOM_ID, id,
7044                       GDI_CUSTOM_TYPE_ID, i,
7045                       GDI_INFO_TEXT, menubutton_info[i].infotext,
7046                       GDI_X, x,
7047                       GDI_Y, y,
7048                       GDI_WIDTH, width,
7049                       GDI_HEIGHT, height,
7050                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
7051                       GDI_STATE, GD_BUTTON_UNPRESSED,
7052                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7053                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7054                       GDI_DIRECT_DRAW, FALSE,
7055                       GDI_EVENT_MASK, event_mask,
7056                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7057                       GDI_END);
7058
7059     if (gi == NULL)
7060       Error(ERR_EXIT, "cannot create gadget");
7061
7062     screen_gadget[id] = gi;
7063   }
7064 }
7065
7066 static void CreateScreenScrollbuttons()
7067 {
7068   struct GadgetInfo *gi;
7069   unsigned int event_mask;
7070   int i;
7071
7072   /* these values are not constant, but can change at runtime */
7073   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
7074   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
7075   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
7076   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
7077
7078   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
7079   {
7080     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7081     int gfx_unpressed, gfx_pressed;
7082     int x, y, width, height;
7083     int gd_x1, gd_x2, gd_y1, gd_y2;
7084     int id = scrollbutton_info[i].gadget_id;
7085
7086     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
7087
7088     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
7089     y = mSY + scrollbutton_info[i].y;
7090     width = SC_SCROLLBUTTON_XSIZE;
7091     height = SC_SCROLLBUTTON_YSIZE;
7092
7093     /* correct scrollbar position if placed outside menu (playfield) area */
7094     if (x > SX + SC_SCROLL_UP_XPOS)
7095       x = SX + SC_SCROLL_UP_XPOS;
7096
7097     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
7098       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
7099                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
7100
7101     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
7102     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
7103     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7104     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7105     gd_x1 = graphic_info[gfx_unpressed].src_x;
7106     gd_y1 = graphic_info[gfx_unpressed].src_y;
7107     gd_x2 = graphic_info[gfx_pressed].src_x;
7108     gd_y2 = graphic_info[gfx_pressed].src_y;
7109
7110     gi = CreateGadget(GDI_CUSTOM_ID, id,
7111                       GDI_CUSTOM_TYPE_ID, i,
7112                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
7113                       GDI_X, x,
7114                       GDI_Y, y,
7115                       GDI_WIDTH, width,
7116                       GDI_HEIGHT, height,
7117                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
7118                       GDI_STATE, GD_BUTTON_UNPRESSED,
7119                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7120                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7121                       GDI_DIRECT_DRAW, FALSE,
7122                       GDI_EVENT_MASK, event_mask,
7123                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7124                       GDI_END);
7125
7126     if (gi == NULL)
7127       Error(ERR_EXIT, "cannot create gadget");
7128
7129     screen_gadget[id] = gi;
7130   }
7131 }
7132
7133 static void CreateScreenScrollbars()
7134 {
7135   int i;
7136
7137   /* these values are not constant, but can change at runtime */
7138   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
7139   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
7140   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
7141   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
7142
7143   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
7144   {
7145     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7146     int gfx_unpressed, gfx_pressed;
7147     int x, y, width, height;
7148     int gd_x1, gd_x2, gd_y1, gd_y2;
7149     struct GadgetInfo *gi;
7150     int items_max, items_visible, item_position;
7151     unsigned int event_mask;
7152     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
7153     int id = scrollbar_info[i].gadget_id;
7154
7155     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
7156
7157     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
7158     y = mSY + scrollbar_info[i].y;
7159     width  = scrollbar_info[i].width;
7160     height = scrollbar_info[i].height;
7161
7162     /* correct scrollbar position if placed outside menu (playfield) area */
7163     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
7164       x = SX + SC_SCROLL_VERTICAL_XPOS;
7165
7166     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
7167       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
7168
7169     items_max = num_page_entries;
7170     items_visible = num_page_entries;
7171     item_position = 0;
7172
7173     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
7174     gfx_pressed   = scrollbar_info[i].gfx_pressed;
7175     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7176     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7177     gd_x1 = graphic_info[gfx_unpressed].src_x;
7178     gd_y1 = graphic_info[gfx_unpressed].src_y;
7179     gd_x2 = graphic_info[gfx_pressed].src_x;
7180     gd_y2 = graphic_info[gfx_pressed].src_y;
7181
7182     gi = CreateGadget(GDI_CUSTOM_ID, id,
7183                       GDI_CUSTOM_TYPE_ID, i,
7184                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
7185                       GDI_X, x,
7186                       GDI_Y, y,
7187                       GDI_WIDTH, width,
7188                       GDI_HEIGHT, height,
7189                       GDI_TYPE, scrollbar_info[i].type,
7190                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
7191                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
7192                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
7193                       GDI_WHEEL_AREA_X, SX,
7194                       GDI_WHEEL_AREA_Y, SY,
7195                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
7196                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
7197                       GDI_STATE, GD_BUTTON_UNPRESSED,
7198                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7199                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7200                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
7201                       GDI_DIRECT_DRAW, FALSE,
7202                       GDI_EVENT_MASK, event_mask,
7203                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7204                       GDI_END);
7205
7206     if (gi == NULL)
7207       Error(ERR_EXIT, "cannot create gadget");
7208
7209     screen_gadget[id] = gi;
7210   }
7211 }
7212
7213 void CreateScreenGadgets()
7214 {
7215   CreateScreenMenubuttons();
7216
7217   CreateScreenScrollbuttons();
7218   CreateScreenScrollbars();
7219 }
7220
7221 void FreeScreenGadgets()
7222 {
7223   int i;
7224
7225   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
7226     FreeGadget(screen_gadget[i]);
7227 }
7228
7229 void MapScreenMenuGadgets(int screen_mask)
7230 {
7231   int i;
7232
7233   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
7234     if (screen_mask & menubutton_info[i].screen_mask)
7235       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
7236 }
7237
7238 void MapScreenGadgets(int num_entries)
7239 {
7240   int i;
7241
7242   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
7243     return;
7244
7245   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
7246     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
7247
7248   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
7249     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
7250 }
7251
7252 void MapScreenTreeGadgets(TreeInfo *ti)
7253 {
7254   MapScreenGadgets(numTreeInfoInGroup(ti));
7255 }
7256
7257 static void HandleScreenGadgets(struct GadgetInfo *gi)
7258 {
7259   int id = gi->custom_id;
7260   int button = gi->event.button;
7261   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
7262
7263   switch (id)
7264   {
7265     case SCREEN_CTRL_ID_PREV_LEVEL:
7266       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
7267       break;
7268
7269     case SCREEN_CTRL_ID_NEXT_LEVEL:
7270       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
7271       break;
7272
7273     case SCREEN_CTRL_ID_PREV_PLAYER:
7274       HandleSetupScreen_Input_Player(step, -1);
7275       break;
7276
7277     case SCREEN_CTRL_ID_NEXT_PLAYER:
7278       HandleSetupScreen_Input_Player(step, +1);
7279       break;
7280
7281     case SCREEN_CTRL_ID_SCROLL_UP:
7282       if (game_status == GAME_MODE_LEVELS)
7283         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7284       else if (game_status == GAME_MODE_LEVELNR)
7285         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7286       else if (game_status == GAME_MODE_SETUP)
7287         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7288       else if (game_status == GAME_MODE_INFO)
7289         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7290       break;
7291
7292     case SCREEN_CTRL_ID_SCROLL_DOWN:
7293       if (game_status == GAME_MODE_LEVELS)
7294         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7295       else if (game_status == GAME_MODE_LEVELNR)
7296         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7297       else if (game_status == GAME_MODE_SETUP)
7298         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7299       else if (game_status == GAME_MODE_INFO)
7300         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7301       break;
7302
7303     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
7304       if (game_status == GAME_MODE_LEVELS)
7305         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
7306       else if (game_status == GAME_MODE_LEVELNR)
7307         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
7308       else if (game_status == GAME_MODE_SETUP)
7309         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
7310       else if (game_status == GAME_MODE_INFO)
7311         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
7312       break;
7313
7314     default:
7315       break;
7316   }
7317 }