added saving current level number when manually selecting different level
[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   ystart2 += ystep;
3316   DrawTextF(xstart1, ystart2, font_header, "Platform");
3317   DrawTextF(xstart2, ystart2, font_text, PLATFORM_STRING);
3318
3319   ystart2 += ystep;
3320   DrawTextF(xstart1, ystart2, font_header, "Target");
3321   DrawTextF(xstart2, ystart2, font_text, TARGET_STRING);
3322
3323   ystart2 += ystep;
3324   DrawTextF(xstart1, ystart2, font_header, "Source date");
3325   DrawTextF(xstart2, ystart2, font_text, getSourceDateString());
3326
3327   ystart2 += 3 * ystep;
3328   DrawTextF(xstart1, ystart2, font_header, "Library");
3329   DrawTextF(xstart2, ystart2, font_header, "compiled");
3330   DrawTextF(xstart3, ystart2, font_header, "linked");
3331
3332   SDL_VERSION(&sdl_version_compiled);
3333 #if defined(TARGET_SDL2)
3334   SDL_GetVersion(&sdl_version_linked_ext);
3335   sdl_version_linked = &sdl_version_linked_ext;
3336 #else
3337   sdl_version_linked = SDL_Linked_Version();
3338 #endif
3339
3340   ystart2 += 2 * ystep;
3341   DrawTextF(xstart1, ystart2, font_text, "SDL");
3342   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3343             sdl_version_compiled.major,
3344             sdl_version_compiled.minor,
3345             sdl_version_compiled.patch);
3346   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3347             sdl_version_linked->major,
3348             sdl_version_linked->minor,
3349             sdl_version_linked->patch);
3350
3351   SDL_IMAGE_VERSION(&sdl_version_compiled);
3352   sdl_version_linked = IMG_Linked_Version();
3353
3354   ystart2 += ystep;
3355   DrawTextF(xstart1, ystart2, font_text, "SDL_image");
3356   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3357             sdl_version_compiled.major,
3358             sdl_version_compiled.minor,
3359             sdl_version_compiled.patch);
3360   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3361             sdl_version_linked->major,
3362             sdl_version_linked->minor,
3363             sdl_version_linked->patch);
3364
3365   SDL_MIXER_VERSION(&sdl_version_compiled);
3366   sdl_version_linked = Mix_Linked_Version();
3367
3368   ystart2 += ystep;
3369   DrawTextF(xstart1, ystart2, font_text, "SDL_mixer");
3370   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3371             sdl_version_compiled.major,
3372             sdl_version_compiled.minor,
3373             sdl_version_compiled.patch);
3374   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3375             sdl_version_linked->major,
3376             sdl_version_linked->minor,
3377             sdl_version_linked->patch);
3378
3379   SDL_NET_VERSION(&sdl_version_compiled);
3380   sdl_version_linked = SDLNet_Linked_Version();
3381
3382   ystart2 += ystep;
3383   DrawTextF(xstart1, ystart2, font_text, "SDL_net");
3384   DrawTextF(xstart2, ystart2, font_text, "%d.%d.%d",
3385             sdl_version_compiled.major,
3386             sdl_version_compiled.minor,
3387             sdl_version_compiled.patch);
3388   DrawTextF(xstart3, ystart2, font_text, "%d.%d.%d",
3389             sdl_version_linked->major,
3390             sdl_version_linked->minor,
3391             sdl_version_linked->patch);
3392
3393   ystart2 += 3 * ystep;
3394   DrawTextF(xstart1, ystart2, font_header, "Driver");
3395   DrawTextF(xstart2, ystart2, font_header, "Requested");
3396   DrawTextF(xstart3, ystart2, font_header, "Used");
3397
3398 #if defined(TARGET_SDL2)
3399   driver_name = getStringCopyNStatic(SDL_GetVideoDriver(0), driver_name_len);
3400 #else
3401   SDL_VideoDriverName(driver_name, driver_name_len);
3402 #endif
3403
3404   ystart2 += 2 * ystep;
3405   DrawTextF(xstart1, ystart2, font_text, "SDL_VideoDriver");
3406   DrawTextF(xstart2, ystart2, font_text, "%s", setup.system.sdl_videodriver);
3407   DrawTextF(xstart3, ystart2, font_text, "%s", driver_name);
3408
3409 #if defined(TARGET_SDL2)
3410   driver_name = getStringCopyNStatic(SDL_GetAudioDriver(0), driver_name_len);
3411 #else
3412   SDL_AudioDriverName(driver_name, driver_name_len);
3413 #endif
3414
3415   ystart2 += ystep;
3416   DrawTextF(xstart1, ystart2, font_text, "SDL_AudioDriver");
3417   DrawTextF(xstart2, ystart2, font_text, "%s", setup.system.sdl_audiodriver);
3418   DrawTextF(xstart3, ystart2, font_text, "%s", driver_name);
3419
3420   DrawTextSCentered(ybottom, FONT_TEXT_4,
3421                     "Press any key or button for info menu");
3422
3423   FadeIn(REDRAW_FIELD);
3424 }
3425
3426 void HandleInfoScreen_Version(int button)
3427 {
3428   if (button == MB_MENU_LEAVE)
3429   {
3430     PlaySound(SND_MENU_ITEM_SELECTING);
3431
3432     info_mode = INFO_MODE_MAIN;
3433     DrawInfoScreen();
3434
3435     return;
3436   }
3437   else if (button == MB_MENU_CHOICE)
3438   {
3439     PlaySound(SND_MENU_ITEM_SELECTING);
3440
3441     FadeMenuSoundsAndMusic();
3442
3443     info_mode = INFO_MODE_MAIN;
3444     DrawInfoScreen();
3445   }
3446   else
3447   {
3448     PlayMenuSoundIfLoop();
3449   }
3450 }
3451
3452 void DrawInfoScreen_LevelSet()
3453 {
3454   struct TitleMessageInfo *tmi = &readme;
3455   char *filename = getLevelSetInfoFilename();
3456   char *title = "Level Set Information:";
3457   int ystart1 = mSY - SY + 100;
3458   int ybottom = mSY - SY + SYSIZE - 20;
3459
3460   if (filename == NULL)
3461   {
3462     DrawInfoScreen_NotAvailable(title, "No information for this level set.");
3463
3464     return;
3465   }
3466
3467   SetMainBackgroundImageIfDefined(IMG_BACKGROUND_INFO_LEVELSET);
3468
3469   FadeOut(REDRAW_FIELD);
3470
3471   ClearField();
3472   DrawHeadline();
3473
3474   DrawTextSCentered(ystart1, FONT_TEXT_1, title);
3475
3476   /* if x position set to "-1", automatically determine by playfield width */
3477   if (tmi->x == -1)
3478     tmi->x = SXSIZE / 2;
3479
3480   /* if y position set to "-1", use static default value */
3481   if (tmi->y == -1)
3482     tmi->y = 150;
3483
3484   /* if width set to "-1", automatically determine by playfield width */
3485   if (tmi->width == -1)
3486     tmi->width = SXSIZE - 2 * TILEX;
3487
3488   /* if height set to "-1", automatically determine by playfield height */
3489   if (tmi->height == -1)
3490     tmi->height = SYSIZE - 20 - tmi->y - 10;
3491
3492   /* if chars set to "-1", automatically determine by text and font width */
3493   if (tmi->chars == -1)
3494     tmi->chars = tmi->width / getFontWidth(tmi->font);
3495   else
3496     tmi->width = tmi->chars * getFontWidth(tmi->font);
3497
3498   /* if lines set to "-1", automatically determine by text and font height */
3499   if (tmi->lines == -1)
3500     tmi->lines = tmi->height / getFontHeight(tmi->font);
3501   else
3502     tmi->height = tmi->lines * getFontHeight(tmi->font);
3503
3504   DrawTextFile(mSX + ALIGNED_TEXT_XPOS(tmi), mSY + ALIGNED_TEXT_YPOS(tmi),
3505                filename, tmi->font, tmi->chars, -1, tmi->lines, 0, -1,
3506                tmi->autowrap, tmi->centered, tmi->parse_comments);
3507
3508   DrawTextSCentered(ybottom, FONT_TEXT_4,
3509                     "Press any key or button for info menu");
3510
3511   FadeIn(REDRAW_FIELD);
3512 }
3513
3514 void HandleInfoScreen_LevelSet(int button)
3515 {
3516   if (button == MB_MENU_LEAVE)
3517   {
3518     PlaySound(SND_MENU_ITEM_SELECTING);
3519
3520     info_mode = INFO_MODE_MAIN;
3521     DrawInfoScreen();
3522
3523     return;
3524   }
3525   else if (button == MB_MENU_CHOICE)
3526   {
3527     PlaySound(SND_MENU_ITEM_SELECTING);
3528
3529     FadeMenuSoundsAndMusic();
3530
3531     info_mode = INFO_MODE_MAIN;
3532     DrawInfoScreen();
3533   }
3534   else
3535   {
3536     PlayMenuSoundIfLoop();
3537   }
3538 }
3539
3540 static void DrawInfoScreen()
3541 {
3542   if (info_mode == INFO_MODE_TITLE)
3543     DrawInfoScreen_TitleScreen();
3544   else if (info_mode == INFO_MODE_ELEMENTS)
3545     DrawInfoScreen_Elements();
3546   else if (info_mode == INFO_MODE_MUSIC)
3547     DrawInfoScreen_Music();
3548   else if (info_mode == INFO_MODE_CREDITS)
3549     DrawInfoScreen_Credits();
3550   else if (info_mode == INFO_MODE_PROGRAM)
3551     DrawInfoScreen_Program();
3552   else if (info_mode == INFO_MODE_VERSION)
3553     DrawInfoScreen_Version();
3554   else if (info_mode == INFO_MODE_LEVELSET)
3555     DrawInfoScreen_LevelSet();
3556   else
3557     DrawInfoScreen_Main();
3558
3559   if (info_mode != INFO_MODE_MAIN &&
3560       info_mode != INFO_MODE_TITLE &&
3561       info_mode != INFO_MODE_MUSIC)
3562     PlayMenuSoundsAndMusic();
3563 }
3564
3565 void HandleInfoScreen(int mx, int my, int dx, int dy, int button)
3566 {
3567   if (info_mode == INFO_MODE_TITLE)
3568     HandleInfoScreen_TitleScreen(button);
3569   else if (info_mode == INFO_MODE_ELEMENTS)
3570     HandleInfoScreen_Elements(button);
3571   else if (info_mode == INFO_MODE_MUSIC)
3572     HandleInfoScreen_Music(button);
3573   else if (info_mode == INFO_MODE_CREDITS)
3574     HandleInfoScreen_Credits(button);
3575   else if (info_mode == INFO_MODE_PROGRAM)
3576     HandleInfoScreen_Program(button);
3577   else if (info_mode == INFO_MODE_VERSION)
3578     HandleInfoScreen_Version(button);
3579   else if (info_mode == INFO_MODE_LEVELSET)
3580     HandleInfoScreen_LevelSet(button);
3581   else
3582     HandleInfoScreen_Main(mx, my, dx, dy, button);
3583 }
3584
3585
3586 /* ========================================================================= */
3587 /* type name functions                                                       */
3588 /* ========================================================================= */
3589
3590 void HandleTypeName(int newxpos, Key key)
3591 {
3592   static char last_player_name[MAX_PLAYER_NAME_LEN + 1];
3593   struct MainControlInfo *mci = getMainControlInfo(MAIN_CONTROL_NAME);
3594   struct TextPosInfo *pos = mci->pos_input;
3595   int startx = mSX + ALIGNED_TEXT_XPOS(pos);
3596   int starty = mSY + ALIGNED_TEXT_YPOS(pos);
3597   static int xpos = 0;
3598   int font_nr = pos->font;
3599   int font_active_nr = FONT_ACTIVE(font_nr);
3600   int font_width = getFontWidth(font_active_nr);
3601   char key_char = getValidConfigValueChar(getCharFromKey(key));
3602   boolean is_valid_key_char = (key_char != 0 && (key_char != ' ' || xpos > 0));
3603   boolean is_active = TRUE;
3604
3605   DrawBackgroundForFont(startx,starty, pos->width, pos->height, font_active_nr);
3606
3607   if (newxpos)
3608   {
3609     strcpy(last_player_name, setup.player_name);
3610
3611     xpos = newxpos;
3612
3613     StartTextInput(startx, starty, pos->width, pos->height);
3614   }
3615   else if (is_valid_key_char && xpos < MAX_PLAYER_NAME_LEN)
3616   {
3617     setup.player_name[xpos] = key_char;
3618     setup.player_name[xpos + 1] = 0;
3619
3620     xpos++;
3621   }
3622   else if ((key == KSYM_Delete || key == KSYM_BackSpace) && xpos > 0)
3623   {
3624     xpos--;
3625
3626     setup.player_name[xpos] = 0;
3627   }
3628   else if (key == KSYM_Return && xpos > 0)
3629   {
3630     SaveSetup();
3631
3632     is_active = FALSE;
3633
3634     SetGameStatus(GAME_MODE_MAIN);
3635   }
3636   else if (key == KSYM_Escape)
3637   {
3638     strcpy(setup.player_name, last_player_name);
3639
3640     is_active = FALSE;
3641
3642     SetGameStatus(GAME_MODE_MAIN);
3643   }
3644
3645   if (is_active)
3646   {
3647     pos->width = (strlen(setup.player_name) + 1) * font_width;
3648     startx = mSX + ALIGNED_TEXT_XPOS(pos);
3649
3650     DrawText(startx, starty, setup.player_name, font_active_nr);
3651     DrawText(startx + xpos * font_width, starty, "_", font_active_nr);
3652   }
3653   else
3654   {
3655     pos->width = strlen(setup.player_name) * font_width;
3656     startx = mSX + ALIGNED_TEXT_XPOS(pos);
3657
3658     DrawText(startx, starty, setup.player_name, font_nr);
3659
3660     StopTextInput();
3661   }
3662 }
3663
3664
3665 /* ========================================================================= */
3666 /* tree menu functions                                                       */
3667 /* ========================================================================= */
3668
3669 static void DrawChooseTree(TreeInfo **ti_ptr)
3670 {
3671   int fade_mask = REDRAW_FIELD;
3672
3673   if (CheckIfGlobalBorderHasChanged())
3674     fade_mask = REDRAW_ALL;
3675
3676   if (strEqual((*ti_ptr)->subdir, STRING_TOP_DIRECTORY))
3677   {
3678     SetGameStatus(GAME_MODE_MAIN);
3679
3680     DrawMainMenu();
3681
3682     return;
3683   }
3684
3685   UnmapAllGadgets();
3686
3687   FreeScreenGadgets();
3688   CreateScreenGadgets();
3689
3690   FadeOut(fade_mask);
3691
3692   /* needed if different viewport properties defined for choosing level (set) */
3693   ChangeViewportPropertiesIfNeeded();
3694
3695   if (game_status == GAME_MODE_LEVELNR)
3696     SetMainBackgroundImage(IMG_BACKGROUND_LEVELNR);
3697   else if (game_status == GAME_MODE_LEVELS)
3698     SetMainBackgroundImage(IMG_BACKGROUND_LEVELS);
3699
3700   ClearField();
3701
3702   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
3703
3704   HandleChooseTree(0, 0, 0, 0, MB_MENU_INITIALIZE, ti_ptr);
3705   MapScreenTreeGadgets(*ti_ptr);
3706
3707   DrawMaskedBorder(fade_mask);
3708
3709   FadeIn(fade_mask);
3710 }
3711
3712 static void drawChooseTreeList(int first_entry, int num_page_entries,
3713                                TreeInfo *ti)
3714 {
3715   int i;
3716   char *title_string = NULL;
3717   int yoffset_sets = MENU_TITLE1_YPOS;
3718   int yoffset_setup = 16;
3719   int yoffset = (ti->type == TREE_TYPE_LEVEL_DIR ||
3720                  ti->type == TREE_TYPE_LEVEL_NR ? yoffset_sets : yoffset_setup);
3721
3722   title_string = ti->infotext;
3723
3724   DrawTextSCentered(mSY - SY + yoffset, FONT_TITLE_1, title_string);
3725
3726   clearMenuListArea();
3727
3728   for (i = 0; i < num_page_entries; i++)
3729   {
3730     TreeInfo *node, *node_first;
3731     int entry_pos = first_entry + i;
3732     int xpos = MENU_SCREEN_START_XPOS;
3733     int ypos = MENU_SCREEN_START_YPOS + i;
3734     int startx = mSX + xpos * 32;
3735     int starty = mSY + ypos * 32;
3736     int font_nr = FONT_TEXT_1;
3737     int font_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
3738     int startx_text = startx + font_xoffset;
3739     int startx_scrollbar = mSX + SC_SCROLLBAR_XPOS + menu.scrollbar_xoffset;
3740     int text_size = startx_scrollbar - startx_text;
3741     int max_buffer_len = text_size / getFontWidth(font_nr);
3742     char buffer[max_buffer_len + 1];
3743
3744     node_first = getTreeInfoFirstGroupEntry(ti);
3745     node = getTreeInfoFromPos(node_first, entry_pos);
3746
3747     strncpy(buffer, node->name, max_buffer_len);
3748     buffer[max_buffer_len] = '\0';
3749
3750     DrawText(startx, starty, buffer, font_nr + node->color);
3751
3752     if (node->parent_link)
3753       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
3754     else if (node->level_group)
3755       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
3756     else
3757       initCursor(i, IMG_MENU_BUTTON);
3758   }
3759
3760   redraw_mask |= REDRAW_FIELD;
3761 }
3762
3763 static void drawChooseTreeInfo(int entry_pos, TreeInfo *ti)
3764 {
3765   TreeInfo *node, *node_first;
3766   int x, last_redraw_mask = redraw_mask;
3767   int ypos = MENU_TITLE2_YPOS;
3768   int font_nr = FONT_TITLE_2;
3769
3770   if (ti->type == TREE_TYPE_LEVEL_NR)
3771     DrawTextFCentered(ypos, font_nr, leveldir_current->name);
3772
3773   if (ti->type != TREE_TYPE_LEVEL_DIR)
3774     return;
3775
3776   node_first = getTreeInfoFirstGroupEntry(ti);
3777   node = getTreeInfoFromPos(node_first, entry_pos);
3778
3779   DrawBackgroundForFont(SX, SY + ypos, SXSIZE, getFontHeight(font_nr), font_nr);
3780
3781   if (node->parent_link)
3782     DrawTextFCentered(ypos, font_nr, "leave \"%s\"",
3783                       node->node_parent->name);
3784   else if (node->level_group)
3785     DrawTextFCentered(ypos, font_nr, "enter \"%s\"",
3786                       node->name);
3787   else if (ti->type == TREE_TYPE_LEVEL_DIR)
3788     DrawTextFCentered(ypos, font_nr, "%3d %s (%s)",
3789                       node->levels, (node->levels > 1 ? "levels" : "level"),
3790                       node->class_desc);
3791
3792   /* let BackToFront() redraw only what is needed */
3793   redraw_mask = last_redraw_mask;
3794   for (x = 0; x < SCR_FIELDX; x++)
3795     MarkTileDirty(x, 1);
3796 }
3797
3798 static void HandleChooseTree(int mx, int my, int dx, int dy, int button,
3799                              TreeInfo **ti_ptr)
3800 {
3801   TreeInfo *ti = *ti_ptr;
3802   int x = 0;
3803   int y = ti->cl_cursor;
3804   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
3805   int num_entries = numTreeInfoInGroup(ti);
3806   int num_page_entries;
3807   boolean position_set_by_scrollbar = (dx == 999);
3808
3809   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
3810     num_page_entries = num_entries;
3811   else
3812     num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
3813
3814   if (button == MB_MENU_INITIALIZE)
3815   {
3816     int num_entries = numTreeInfoInGroup(ti);
3817     int entry_pos = posTreeInfo(ti);
3818
3819     if (ti->cl_first == -1)
3820     {
3821       /* only on initialization */
3822       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
3823       ti->cl_cursor = entry_pos - ti->cl_first;
3824     }
3825     else if (ti->cl_cursor >= num_page_entries ||
3826              (num_entries > num_page_entries &&
3827               num_entries - ti->cl_first < num_page_entries))
3828     {
3829       /* only after change of list size (by custom graphic configuration) */
3830       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
3831       ti->cl_cursor = entry_pos - ti->cl_first;
3832     }
3833
3834     if (position_set_by_scrollbar)
3835       ti->cl_first = dy;
3836     else
3837       AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
3838                                 ti->cl_first, ti);
3839
3840     drawChooseTreeList(ti->cl_first, num_page_entries, ti);
3841     drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
3842     drawChooseTreeCursor(ti->cl_cursor, TRUE);
3843
3844     return;
3845   }
3846   else if (button == MB_MENU_LEAVE)
3847   {
3848     FadeSetLeaveMenu();
3849
3850     PlaySound(SND_MENU_ITEM_SELECTING);
3851
3852     if (ti->node_parent)
3853     {
3854       *ti_ptr = ti->node_parent;
3855       DrawChooseTree(ti_ptr);
3856     }
3857     else if (game_status == GAME_MODE_SETUP)
3858     {
3859       if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
3860           setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
3861           setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
3862         execSetupGame();
3863       else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
3864                setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
3865                setup_mode == SETUP_MODE_CHOOSE_RENDERING)
3866         execSetupGraphics();
3867       else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
3868                setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
3869                setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
3870         execSetupSound();
3871       else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
3872                setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
3873                setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
3874         execSetupTouch();
3875       else
3876         execSetupArtwork();
3877     }
3878     else
3879     {
3880       if (game_status == GAME_MODE_LEVELNR)
3881       {
3882         int new_level_nr = atoi(level_number_current->identifier);
3883
3884         HandleMainMenu_SelectLevel(0, 0, new_level_nr);
3885       }
3886
3887       SetGameStatus(GAME_MODE_MAIN);
3888
3889       DrawMainMenu();
3890     }
3891
3892     return;
3893   }
3894
3895   if (mx || my)         /* mouse input */
3896   {
3897     x = (mx - mSX) / 32;
3898     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
3899   }
3900   else if (dx || dy)    /* keyboard or scrollbar/scrollbutton input */
3901   {
3902     /* move cursor instead of scrolling when already at start/end of list */
3903     if (dy == -1 * SCROLL_LINE && ti->cl_first == 0)
3904       dy = -1;
3905     else if (dy == +1 * SCROLL_LINE &&
3906              ti->cl_first + num_page_entries == num_entries)
3907       dy = 1;
3908
3909     /* handle scrolling screen one line or page */
3910     if (ti->cl_cursor + dy < 0 ||
3911         ti->cl_cursor + dy > num_page_entries - 1)
3912     {
3913       boolean redraw = FALSE;
3914
3915       if (ABS(dy) == SCROLL_PAGE)
3916         step = num_page_entries - 1;
3917
3918       if (dy < 0 && ti->cl_first > 0)
3919       {
3920         /* scroll page/line up */
3921
3922         ti->cl_first -= step;
3923         if (ti->cl_first < 0)
3924           ti->cl_first = 0;
3925
3926         redraw = TRUE;
3927       }
3928       else if (dy > 0 && ti->cl_first + num_page_entries < num_entries)
3929       {
3930         /* scroll page/line down */
3931
3932         ti->cl_first += step;
3933         if (ti->cl_first + num_page_entries > num_entries)
3934           ti->cl_first = MAX(0, num_entries - num_page_entries);
3935
3936         redraw = TRUE;
3937       }
3938
3939       if (redraw)
3940       {
3941         drawChooseTreeList(ti->cl_first, num_page_entries, ti);
3942         drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
3943         drawChooseTreeCursor(ti->cl_cursor, TRUE);
3944
3945         AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
3946                                   ti->cl_first, ti);
3947       }
3948
3949       return;
3950     }
3951
3952     /* handle moving cursor one line */
3953     y = ti->cl_cursor + dy;
3954   }
3955
3956   if (dx == 1)
3957   {
3958     TreeInfo *node_first, *node_cursor;
3959     int entry_pos = ti->cl_first + y;
3960
3961     node_first = getTreeInfoFirstGroupEntry(ti);
3962     node_cursor = getTreeInfoFromPos(node_first, entry_pos);
3963
3964     if (node_cursor->node_group)
3965     {
3966       FadeSetEnterMenu();
3967
3968       PlaySound(SND_MENU_ITEM_SELECTING);
3969
3970       node_cursor->cl_first = ti->cl_first;
3971       node_cursor->cl_cursor = ti->cl_cursor;
3972       *ti_ptr = node_cursor->node_group;
3973       DrawChooseTree(ti_ptr);
3974
3975       return;
3976     }
3977   }
3978   else if (dx == -1 && ti->node_parent)
3979   {
3980     FadeSetLeaveMenu();
3981
3982     PlaySound(SND_MENU_ITEM_SELECTING);
3983
3984     *ti_ptr = ti->node_parent;
3985     DrawChooseTree(ti_ptr);
3986
3987     return;
3988   }
3989
3990   if (!anyScrollbarGadgetActive() &&
3991       IN_VIS_MENU(x, y) &&
3992       mx < screen_gadget[SCREEN_CTRL_ID_SCROLL_VERTICAL]->x &&
3993       y >= 0 && y < num_page_entries)
3994   {
3995     if (button)
3996     {
3997       if (y != ti->cl_cursor)
3998       {
3999         PlaySound(SND_MENU_ITEM_ACTIVATING);
4000
4001         drawChooseTreeCursor(ti->cl_cursor, FALSE);
4002         drawChooseTreeCursor(y, TRUE);
4003         drawChooseTreeInfo(ti->cl_first + y, ti);
4004
4005         ti->cl_cursor = y;
4006       }
4007       else if (dx < 0)
4008       {
4009         if (game_status == GAME_MODE_SETUP)
4010         {
4011           if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
4012               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
4013               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
4014             execSetupGame();
4015           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
4016                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
4017                    setup_mode == SETUP_MODE_CHOOSE_RENDERING)
4018             execSetupGraphics();
4019           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
4020                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
4021                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
4022             execSetupSound();
4023           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
4024                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
4025                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
4026             execSetupTouch();
4027           else
4028             execSetupArtwork();
4029         }
4030       }
4031     }
4032     else
4033     {
4034       TreeInfo *node_first, *node_cursor;
4035       int entry_pos = ti->cl_first + y;
4036
4037       PlaySound(SND_MENU_ITEM_SELECTING);
4038
4039       node_first = getTreeInfoFirstGroupEntry(ti);
4040       node_cursor = getTreeInfoFromPos(node_first, entry_pos);
4041
4042       if (node_cursor->node_group)
4043       {
4044         FadeSetEnterMenu();
4045
4046         node_cursor->cl_first = ti->cl_first;
4047         node_cursor->cl_cursor = ti->cl_cursor;
4048         *ti_ptr = node_cursor->node_group;
4049         DrawChooseTree(ti_ptr);
4050       }
4051       else if (node_cursor->parent_link)
4052       {
4053         FadeSetLeaveMenu();
4054
4055         *ti_ptr = node_cursor->node_parent;
4056         DrawChooseTree(ti_ptr);
4057       }
4058       else
4059       {
4060         FadeSetEnterMenu();
4061
4062         node_cursor->cl_first = ti->cl_first;
4063         node_cursor->cl_cursor = ti->cl_cursor;
4064         *ti_ptr = node_cursor;
4065
4066         if (ti->type == TREE_TYPE_LEVEL_DIR)
4067         {
4068           LoadLevelSetup_SeriesInfo();
4069
4070           SaveLevelSetup_LastSeries();
4071           SaveLevelSetup_SeriesInfo();
4072           TapeErase();
4073         }
4074
4075         if (game_status == GAME_MODE_SETUP)
4076         {
4077           if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED ||
4078               setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY ||
4079               setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
4080             execSetupGame();
4081           else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE ||
4082                    setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE ||
4083                    setup_mode == SETUP_MODE_CHOOSE_RENDERING)
4084             execSetupGraphics();
4085           else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE ||
4086                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS ||
4087                    setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
4088             execSetupSound();
4089           else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL ||
4090                    setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE ||
4091                    setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
4092             execSetupTouch();
4093           else
4094             execSetupArtwork();
4095         }
4096         else
4097         {
4098           if (game_status == GAME_MODE_LEVELNR)
4099           {
4100             int new_level_nr = atoi(level_number_current->identifier);
4101
4102             HandleMainMenu_SelectLevel(0, 0, new_level_nr);
4103           }
4104
4105           SetGameStatus(GAME_MODE_MAIN);
4106
4107           DrawMainMenu();
4108         }
4109       }
4110     }
4111   }
4112 }
4113
4114 void DrawChooseLevelSet()
4115 {
4116   FadeMenuSoundsAndMusic();
4117
4118   DrawChooseTree(&leveldir_current);
4119
4120   PlayMenuSoundsAndMusic();
4121 }
4122
4123 void HandleChooseLevelSet(int mx, int my, int dx, int dy, int button)
4124 {
4125   HandleChooseTree(mx, my, dx, dy, button, &leveldir_current);
4126 }
4127
4128 void DrawChooseLevelNr()
4129 {
4130   int i;
4131
4132   FadeMenuSoundsAndMusic();
4133
4134   if (level_number != NULL)
4135   {
4136     freeTreeInfo(level_number);
4137
4138     level_number = NULL;
4139   }
4140
4141   for (i = leveldir_current->first_level; i <= leveldir_current->last_level;i++)
4142   {
4143     TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_LEVEL_NR);
4144     char identifier[32], name[32];
4145     int value = i;
4146
4147     /* temporarily load level info to get level name */
4148     LoadLevelInfoOnly(i);
4149
4150     ti->node_top = &level_number;
4151     ti->sort_priority = 10000 + value;
4152     ti->color = (level.no_level_file ? FC_BLUE :
4153                  LevelStats_getSolved(i) ? FC_GREEN :
4154                  LevelStats_getPlayed(i) ? FC_YELLOW : FC_RED);
4155
4156     snprintf(identifier, sizeof(identifier), "%d", value);
4157     snprintf(name, sizeof(name), "%03d: %s", value,
4158              (level.no_level_file ? "(no file)" : level.name));
4159
4160     setString(&ti->identifier, identifier);
4161     setString(&ti->name, name);
4162     setString(&ti->name_sorting, name);
4163
4164     pushTreeInfo(&level_number, ti);
4165   }
4166
4167   /* sort level number values to start with lowest level number */
4168   sortTreeInfo(&level_number);
4169
4170   /* set current level number to current level number */
4171   level_number_current =
4172     getTreeInfoFromIdentifier(level_number, i_to_a(level_nr));
4173
4174   /* if that also fails, set current level number to first available level */
4175   if (level_number_current == NULL)
4176     level_number_current = level_number;
4177
4178   DrawChooseTree(&level_number_current);
4179
4180   PlayMenuSoundsAndMusic();
4181 }
4182
4183 void HandleChooseLevelNr(int mx, int my, int dx, int dy, int button)
4184 {
4185   HandleChooseTree(mx, my, dx, dy, button, &level_number_current);
4186 }
4187
4188 void DrawHallOfFame(int highlight_position)
4189 {
4190   int fade_mask = REDRAW_FIELD;
4191
4192   if (CheckIfGlobalBorderHasChanged())
4193     fade_mask = REDRAW_ALL;
4194
4195   UnmapAllGadgets();
4196   FadeMenuSoundsAndMusic();
4197
4198   /* (this is needed when called from GameEnd() after winning a game) */
4199   KeyboardAutoRepeatOn();
4200
4201   /* (this is needed when called from GameEnd() after winning a game) */
4202   SetDrawDeactivationMask(REDRAW_NONE);
4203   SetDrawBackgroundMask(REDRAW_FIELD);
4204
4205   if (highlight_position < 0) 
4206     LoadScore(level_nr);
4207   else
4208     SetAnimStatus(GAME_MODE_PSEUDO_SCORESNEW);
4209
4210   FadeSetEnterScreen();
4211
4212   FadeOut(fade_mask);
4213
4214   /* needed if different viewport properties defined for scores */
4215   ChangeViewportPropertiesIfNeeded();
4216
4217   PlayMenuSoundsAndMusic();
4218
4219   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
4220
4221   HandleHallOfFame(highlight_position, 0, 0, 0, MB_MENU_INITIALIZE);
4222
4223   DrawMaskedBorder(fade_mask);
4224
4225   FadeIn(fade_mask);
4226 }
4227
4228 static void drawHallOfFameList(int first_entry, int highlight_position)
4229 {
4230   int i, j;
4231
4232   SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
4233   ClearField();
4234
4235   DrawTextSCentered(MENU_TITLE1_YPOS, FONT_TITLE_1, "Hall Of Fame");
4236   DrawTextFCentered(MENU_TITLE2_YPOS, FONT_TITLE_2,
4237                     "HighScores of Level %d", level_nr);
4238
4239   for (i = 0; i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
4240   {
4241     int entry = first_entry + i;
4242     boolean active = (entry == highlight_position);
4243     int font_nr1 = (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
4244     int font_nr2 = (active ? FONT_TEXT_2_ACTIVE : FONT_TEXT_2);
4245     int font_nr3 = (active ? FONT_TEXT_3_ACTIVE : FONT_TEXT_3);
4246     int font_nr4 = (active ? FONT_TEXT_4_ACTIVE : FONT_TEXT_4);
4247     int dxoff = getFontDrawOffsetX(font_nr1);
4248     int dx1 = 3 * getFontWidth(font_nr1);
4249     int dx2 = dx1 + getFontWidth(font_nr1);
4250     int dx3 = SXSIZE - 2 * (mSX - SX + dxoff) - 5 * getFontWidth(font_nr4);
4251     int num_dots = (dx3 - dx2) / getFontWidth(font_nr3);
4252     int sy = mSY + 64 + i * 32;
4253
4254     DrawText(mSX, sy, int2str(entry + 1, 3), font_nr1);
4255     DrawText(mSX + dx1, sy, ".", font_nr1);
4256
4257     for (j = 0; j < num_dots; j++)
4258       DrawText(mSX + dx2 + j * getFontWidth(font_nr3), sy, ".", font_nr3);
4259
4260     if (!strEqual(highscore[entry].Name, EMPTY_PLAYER_NAME))
4261       DrawText(mSX + dx2, sy, highscore[entry].Name, font_nr2);
4262
4263     DrawText(mSX + dx3, sy, int2str(highscore[entry].Score, 5), font_nr4);
4264   }
4265
4266   redraw_mask |= REDRAW_FIELD;
4267 }
4268
4269 void HandleHallOfFame(int mx, int my, int dx, int dy, int button)
4270 {
4271   static int first_entry = 0;
4272   static int highlight_position = 0;
4273   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
4274
4275   if (button == MB_MENU_INITIALIZE)
4276   {
4277     first_entry = 0;
4278     highlight_position = mx;
4279     drawHallOfFameList(first_entry, highlight_position);
4280
4281     return;
4282   }
4283
4284   if (ABS(dy) == SCROLL_PAGE)           /* handle scrolling one page */
4285     step = NUM_MENU_ENTRIES_ON_SCREEN - 1;
4286
4287   if (dy < 0)
4288   {
4289     if (first_entry > 0)
4290     {
4291       first_entry -= step;
4292       if (first_entry < 0)
4293         first_entry = 0;
4294
4295       drawHallOfFameList(first_entry, highlight_position);
4296     }
4297   }
4298   else if (dy > 0)
4299   {
4300     if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN < MAX_SCORE_ENTRIES)
4301     {
4302       first_entry += step;
4303       if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN > MAX_SCORE_ENTRIES)
4304         first_entry = MAX(0, MAX_SCORE_ENTRIES - NUM_MENU_ENTRIES_ON_SCREEN);
4305
4306       drawHallOfFameList(first_entry, highlight_position);
4307     }
4308   }
4309   else if (button == MB_MENU_LEAVE)
4310   {
4311     PlaySound(SND_MENU_ITEM_SELECTING);
4312
4313     FadeSound(SND_BACKGROUND_SCORES);
4314
4315     SetGameStatus(GAME_MODE_MAIN);
4316
4317     DrawMainMenu();
4318   }
4319   else if (button == MB_MENU_CHOICE)
4320   {
4321     PlaySound(SND_MENU_ITEM_SELECTING);
4322
4323     FadeSound(SND_BACKGROUND_SCORES);
4324
4325     SetGameStatus(GAME_MODE_MAIN);
4326
4327     DrawMainMenu();
4328   }
4329
4330   if (game_status == GAME_MODE_SCORES)
4331     PlayMenuSoundIfLoop();
4332 }
4333
4334
4335 /* ========================================================================= */
4336 /* setup screen functions                                                    */
4337 /* ========================================================================= */
4338
4339 static struct TokenInfo *setup_info;
4340 static int num_setup_info;      /* number of setup entries shown on screen */
4341 static int max_setup_info;      /* total number of setup entries in list */
4342
4343 static char *window_size_text;
4344 static char *scaling_type_text;
4345 static char *rendering_mode_text;
4346 static char *scroll_delay_text;
4347 static char *snapshot_mode_text;
4348 static char *game_speed_text;
4349 static char *graphics_set_name;
4350 static char *sounds_set_name;
4351 static char *music_set_name;
4352 static char *volume_simple_text;
4353 static char *volume_loops_text;
4354 static char *volume_music_text;
4355 static char *touch_controls_text;
4356 static char *move_distance_text;
4357 static char *drop_distance_text;
4358
4359 static void execSetupMain()
4360 {
4361   setup_mode = SETUP_MODE_MAIN;
4362
4363   DrawSetupScreen();
4364 }
4365
4366 static void execSetupGame_setGameSpeeds()
4367 {
4368   if (game_speeds == NULL)
4369   {
4370     int i;
4371
4372     for (i = 0; game_speeds_list[i].value != -1; i++)
4373     {
4374       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4375       char identifier[32], name[32];
4376       int value = game_speeds_list[i].value;
4377       char *text = game_speeds_list[i].text;
4378
4379       ti->node_top = &game_speeds;
4380       ti->sort_priority = 10000 - value;
4381
4382       sprintf(identifier, "%d", value);
4383       sprintf(name, "%s", text);
4384
4385       setString(&ti->identifier, identifier);
4386       setString(&ti->name, name);
4387       setString(&ti->name_sorting, name);
4388       setString(&ti->infotext, "Game Speed");
4389
4390       pushTreeInfo(&game_speeds, ti);
4391     }
4392
4393     /* sort game speed values to start with slowest game speed */
4394     sortTreeInfo(&game_speeds);
4395
4396     /* set current game speed to configured game speed value */
4397     game_speed_current =
4398       getTreeInfoFromIdentifier(game_speeds, i_to_a(setup.game_frame_delay));
4399
4400     /* if that fails, set current game speed to reliable default value */
4401     if (game_speed_current == NULL)
4402       game_speed_current =
4403         getTreeInfoFromIdentifier(game_speeds, i_to_a(GAME_FRAME_DELAY));
4404
4405     /* if that also fails, set current game speed to first available speed */
4406     if (game_speed_current == NULL)
4407       game_speed_current = game_speeds;
4408   }
4409
4410   setup.game_frame_delay = atoi(game_speed_current->identifier);
4411
4412   /* needed for displaying game speed text instead of identifier */
4413   game_speed_text = game_speed_current->name;
4414 }
4415
4416 static void execSetupGame_setScrollDelays()
4417 {
4418   if (scroll_delays == NULL)
4419   {
4420     int i;
4421
4422     for (i = 0; scroll_delays_list[i].value != -1; i++)
4423     {
4424       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4425       char identifier[32], name[32];
4426       int value = scroll_delays_list[i].value;
4427       char *text = scroll_delays_list[i].text;
4428
4429       ti->node_top = &scroll_delays;
4430       ti->sort_priority = value;
4431
4432       sprintf(identifier, "%d", value);
4433       sprintf(name, "%s", text);
4434
4435       setString(&ti->identifier, identifier);
4436       setString(&ti->name, name);
4437       setString(&ti->name_sorting, name);
4438       setString(&ti->infotext, "Scroll Delay");
4439
4440       pushTreeInfo(&scroll_delays, ti);
4441     }
4442
4443     /* sort scroll delay values to start with lowest scroll delay value */
4444     sortTreeInfo(&scroll_delays);
4445
4446     /* set current scroll delay value to configured scroll delay value */
4447     scroll_delay_current =
4448       getTreeInfoFromIdentifier(scroll_delays,i_to_a(setup.scroll_delay_value));
4449
4450     /* if that fails, set current scroll delay to reliable default value */
4451     if (scroll_delay_current == NULL)
4452       scroll_delay_current =
4453         getTreeInfoFromIdentifier(scroll_delays, i_to_a(STD_SCROLL_DELAY));
4454
4455     /* if that also fails, set current scroll delay to first available value */
4456     if (scroll_delay_current == NULL)
4457       scroll_delay_current = scroll_delays;
4458   }
4459
4460   setup.scroll_delay_value = atoi(scroll_delay_current->identifier);
4461
4462   /* needed for displaying scroll delay text instead of identifier */
4463   scroll_delay_text = scroll_delay_current->name;
4464 }
4465
4466 static void execSetupGame_setSnapshotModes()
4467 {
4468   if (snapshot_modes == NULL)
4469   {
4470     int i;
4471
4472     for (i = 0; snapshot_modes_list[i].value != NULL; i++)
4473     {
4474       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4475       char identifier[32], name[32];
4476       char *value = snapshot_modes_list[i].value;
4477       char *text = snapshot_modes_list[i].text;
4478
4479       ti->node_top = &snapshot_modes;
4480       ti->sort_priority = i;
4481
4482       sprintf(identifier, "%s", value);
4483       sprintf(name, "%s", text);
4484
4485       setString(&ti->identifier, identifier);
4486       setString(&ti->name, name);
4487       setString(&ti->name_sorting, name);
4488       setString(&ti->infotext, "Snapshot Mode");
4489
4490       pushTreeInfo(&snapshot_modes, ti);
4491     }
4492
4493     /* sort snapshot mode values to start with lowest snapshot mode value */
4494     sortTreeInfo(&snapshot_modes);
4495
4496     /* set current snapshot mode value to configured snapshot mode value */
4497     snapshot_mode_current =
4498       getTreeInfoFromIdentifier(snapshot_modes, setup.engine_snapshot_mode);
4499
4500     /* if that fails, set current snapshot mode to reliable default value */
4501     if (snapshot_mode_current == NULL)
4502       snapshot_mode_current =
4503         getTreeInfoFromIdentifier(snapshot_modes, STR_SNAPSHOT_MODE_DEFAULT);
4504
4505     /* if that also fails, set current snapshot mode to first available value */
4506     if (snapshot_mode_current == NULL)
4507       snapshot_mode_current = snapshot_modes;
4508   }
4509
4510   setup.engine_snapshot_mode = snapshot_mode_current->identifier;
4511
4512   /* needed for displaying snapshot mode text instead of identifier */
4513   snapshot_mode_text = snapshot_mode_current->name;
4514 }
4515
4516 static void execSetupGame()
4517 {
4518   execSetupGame_setGameSpeeds();
4519   execSetupGame_setScrollDelays();
4520   execSetupGame_setSnapshotModes();
4521
4522   setup_mode = SETUP_MODE_GAME;
4523
4524   DrawSetupScreen();
4525 }
4526
4527 static void execSetupChooseGameSpeed()
4528 {
4529   setup_mode = SETUP_MODE_CHOOSE_GAME_SPEED;
4530
4531   DrawSetupScreen();
4532 }
4533
4534 static void execSetupChooseScrollDelay()
4535 {
4536   setup_mode = SETUP_MODE_CHOOSE_SCROLL_DELAY;
4537
4538   DrawSetupScreen();
4539 }
4540
4541 static void execSetupChooseSnapshotMode()
4542 {
4543   setup_mode = SETUP_MODE_CHOOSE_SNAPSHOT_MODE;
4544
4545   DrawSetupScreen();
4546 }
4547
4548 static void execSetupEditor()
4549 {
4550   setup_mode = SETUP_MODE_EDITOR;
4551
4552   DrawSetupScreen();
4553 }
4554
4555 static void execSetupGraphics_setWindowSizes(boolean update_list)
4556 {
4557   if (window_sizes != NULL && update_list)
4558   {
4559     freeTreeInfo(window_sizes);
4560
4561     window_sizes = NULL;
4562   }
4563
4564   if (window_sizes == NULL)
4565   {
4566     boolean current_window_size_found = FALSE;
4567     int i;
4568
4569     for (i = 0; window_sizes_list[i].value != -1; i++)
4570     {
4571       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4572       char identifier[32], name[32];
4573       int value = window_sizes_list[i].value;
4574       char *text = window_sizes_list[i].text;
4575
4576       ti->node_top = &window_sizes;
4577       ti->sort_priority = value;
4578
4579       sprintf(identifier, "%d", value);
4580       sprintf(name, "%s", text);
4581
4582       setString(&ti->identifier, identifier);
4583       setString(&ti->name, name);
4584       setString(&ti->name_sorting, name);
4585       setString(&ti->infotext, "Window Scaling");
4586
4587       pushTreeInfo(&window_sizes, ti);
4588
4589       if (value == setup.window_scaling_percent)
4590         current_window_size_found = TRUE;
4591     }
4592
4593     if (!current_window_size_found)
4594     {
4595       // add entry for non-preset window scaling value
4596
4597       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4598       char identifier[32], name[32];
4599       int value = setup.window_scaling_percent;
4600
4601       ti->node_top = &window_sizes;
4602       ti->sort_priority = value;
4603
4604       sprintf(identifier, "%d", value);
4605       sprintf(name, "%d %% (Current)", value);
4606
4607       setString(&ti->identifier, identifier);
4608       setString(&ti->name, name);
4609       setString(&ti->name_sorting, name);
4610       setString(&ti->infotext, "Window Scaling");
4611
4612       pushTreeInfo(&window_sizes, ti);
4613     }
4614
4615     /* sort window size values to start with lowest window size value */
4616     sortTreeInfo(&window_sizes);
4617
4618     /* set current window size value to configured window size value */
4619     window_size_current =
4620       getTreeInfoFromIdentifier(window_sizes,
4621                                 i_to_a(setup.window_scaling_percent));
4622
4623     /* if that fails, set current window size to reliable default value */
4624     if (window_size_current == NULL)
4625       window_size_current =
4626         getTreeInfoFromIdentifier(window_sizes,
4627                                   i_to_a(STD_WINDOW_SCALING_PERCENT));
4628
4629     /* if that also fails, set current window size to first available value */
4630     if (window_size_current == NULL)
4631       window_size_current = window_sizes;
4632   }
4633
4634   setup.window_scaling_percent = atoi(window_size_current->identifier);
4635
4636   /* needed for displaying window size text instead of identifier */
4637   window_size_text = window_size_current->name;
4638 }
4639
4640 static void execSetupGraphics_setScalingTypes()
4641 {
4642   if (scaling_types == NULL)
4643   {
4644     int i;
4645
4646     for (i = 0; scaling_types_list[i].value != NULL; i++)
4647     {
4648       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4649       char identifier[32], name[32];
4650       char *value = scaling_types_list[i].value;
4651       char *text = scaling_types_list[i].text;
4652
4653       ti->node_top = &scaling_types;
4654       ti->sort_priority = i;
4655
4656       sprintf(identifier, "%s", value);
4657       sprintf(name, "%s", text);
4658
4659       setString(&ti->identifier, identifier);
4660       setString(&ti->name, name);
4661       setString(&ti->name_sorting, name);
4662       setString(&ti->infotext, "Anti-Aliasing");
4663
4664       pushTreeInfo(&scaling_types, ti);
4665     }
4666
4667     /* sort scaling type values to start with lowest scaling type value */
4668     sortTreeInfo(&scaling_types);
4669
4670     /* set current scaling type value to configured scaling type value */
4671     scaling_type_current =
4672       getTreeInfoFromIdentifier(scaling_types, setup.window_scaling_quality);
4673
4674     /* if that fails, set current scaling type to reliable default value */
4675     if (scaling_type_current == NULL)
4676       scaling_type_current =
4677         getTreeInfoFromIdentifier(scaling_types, SCALING_QUALITY_DEFAULT);
4678
4679     /* if that also fails, set current scaling type to first available value */
4680     if (scaling_type_current == NULL)
4681       scaling_type_current = scaling_types;
4682   }
4683
4684   setup.window_scaling_quality = scaling_type_current->identifier;
4685
4686   /* needed for displaying scaling type text instead of identifier */
4687   scaling_type_text = scaling_type_current->name;
4688 }
4689
4690 static void execSetupGraphics_setRenderingModes()
4691 {
4692   if (rendering_modes == NULL)
4693   {
4694     int i;
4695
4696     for (i = 0; rendering_modes_list[i].value != NULL; i++)
4697     {
4698       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4699       char identifier[32], name[32];
4700       char *value = rendering_modes_list[i].value;
4701       char *text = rendering_modes_list[i].text;
4702
4703       ti->node_top = &rendering_modes;
4704       ti->sort_priority = i;
4705
4706       sprintf(identifier, "%s", value);
4707       sprintf(name, "%s", text);
4708
4709       setString(&ti->identifier, identifier);
4710       setString(&ti->name, name);
4711       setString(&ti->name_sorting, name);
4712       setString(&ti->infotext, "Special Rendering");
4713
4714       pushTreeInfo(&rendering_modes, ti);
4715     }
4716
4717     /* sort rendering mode values to start with lowest rendering mode value */
4718     sortTreeInfo(&rendering_modes);
4719
4720     /* set current rendering mode value to configured rendering mode value */
4721     rendering_mode_current =
4722       getTreeInfoFromIdentifier(rendering_modes, setup.screen_rendering_mode);
4723
4724     /* if that fails, set current rendering mode to reliable default value */
4725     if (rendering_mode_current == NULL)
4726       rendering_mode_current =
4727         getTreeInfoFromIdentifier(rendering_modes,
4728                                   STR_SPECIAL_RENDERING_DEFAULT);
4729
4730     /* if that also fails, set current rendering mode to first available one */
4731     if (rendering_mode_current == NULL)
4732       rendering_mode_current = rendering_modes;
4733   }
4734
4735   setup.screen_rendering_mode = rendering_mode_current->identifier;
4736
4737   /* needed for displaying rendering mode text instead of identifier */
4738   rendering_mode_text = rendering_mode_current->name;
4739 }
4740
4741 static void execSetupGraphics()
4742 {
4743   // update "setup.window_scaling_percent" from list selection
4744   // (in this case, window scaling was changed on setup screen)
4745   if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
4746     execSetupGraphics_setWindowSizes(FALSE);
4747
4748   // update list selection from "setup.window_scaling_percent"
4749   // (window scaling may have changed by resizing the window)
4750   execSetupGraphics_setWindowSizes(TRUE);
4751
4752   execSetupGraphics_setScalingTypes();
4753   execSetupGraphics_setRenderingModes();
4754
4755   setup_mode = SETUP_MODE_GRAPHICS;
4756
4757   DrawSetupScreen();
4758
4759 #if defined(TARGET_SDL2)
4760   // window scaling may have changed at this point
4761   ToggleFullscreenOrChangeWindowScalingIfNeeded();
4762
4763   // window scaling quality may have changed at this point
4764   if (!strEqual(setup.window_scaling_quality, video.window_scaling_quality))
4765     SDLSetWindowScalingQuality(setup.window_scaling_quality);
4766
4767   // screen rendering mode may have changed at this point
4768   SDLSetScreenRenderingMode(setup.screen_rendering_mode);
4769 #endif
4770 }
4771
4772 #if defined(TARGET_SDL2) && !defined(PLATFORM_ANDROID)
4773 static void execSetupChooseWindowSize()
4774 {
4775   setup_mode = SETUP_MODE_CHOOSE_WINDOW_SIZE;
4776
4777   DrawSetupScreen();
4778 }
4779
4780 static void execSetupChooseScalingType()
4781 {
4782   setup_mode = SETUP_MODE_CHOOSE_SCALING_TYPE;
4783
4784   DrawSetupScreen();
4785 }
4786
4787 static void execSetupChooseRenderingMode()
4788 {
4789   setup_mode = SETUP_MODE_CHOOSE_RENDERING;
4790
4791   DrawSetupScreen();
4792 }
4793 #endif
4794
4795 static void execSetupChooseVolumeSimple()
4796 {
4797   setup_mode = SETUP_MODE_CHOOSE_VOLUME_SIMPLE;
4798
4799   DrawSetupScreen();
4800 }
4801
4802 static void execSetupChooseVolumeLoops()
4803 {
4804   setup_mode = SETUP_MODE_CHOOSE_VOLUME_LOOPS;
4805
4806   DrawSetupScreen();
4807 }
4808
4809 static void execSetupChooseVolumeMusic()
4810 {
4811   setup_mode = SETUP_MODE_CHOOSE_VOLUME_MUSIC;
4812
4813   DrawSetupScreen();
4814 }
4815
4816 static void execSetupSound()
4817 {
4818   if (volumes_simple == NULL)
4819   {
4820     boolean current_volume_simple_found = FALSE;
4821     int i;
4822
4823     for (i = 0; volumes_list[i].value != -1; i++)
4824     {
4825       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4826       char identifier[32], name[32];
4827       int value = volumes_list[i].value;
4828       char *text = volumes_list[i].text;
4829
4830       ti->node_top = &volumes_simple;
4831       ti->sort_priority = value;
4832
4833       sprintf(identifier, "%d", value);
4834       sprintf(name, "%s", text);
4835
4836       setString(&ti->identifier, identifier);
4837       setString(&ti->name, name);
4838       setString(&ti->name_sorting, name);
4839       setString(&ti->infotext, "Sound Volume");
4840
4841       pushTreeInfo(&volumes_simple, ti);
4842
4843       if (value == setup.volume_simple)
4844         current_volume_simple_found = TRUE;
4845     }
4846
4847     if (!current_volume_simple_found)
4848     {
4849       // add entry for non-preset volume value
4850
4851       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4852       char identifier[32], name[32];
4853       int value = setup.volume_simple;
4854
4855       ti->node_top = &volumes_simple;
4856       ti->sort_priority = value;
4857
4858       sprintf(identifier, "%d", value);
4859       sprintf(name, "%d %% (Current)", value);
4860
4861       setString(&ti->identifier, identifier);
4862       setString(&ti->name, name);
4863       setString(&ti->name_sorting, name);
4864       setString(&ti->infotext, "Sound Volume");
4865
4866       pushTreeInfo(&volumes_simple, ti);
4867     }
4868
4869     /* sort volume values to start with lowest volume value */
4870     sortTreeInfo(&volumes_simple);
4871
4872     /* set current volume value to configured volume value */
4873     volume_simple_current =
4874       getTreeInfoFromIdentifier(volumes_simple,i_to_a(setup.volume_simple));
4875
4876     /* if that fails, set current volume to reliable default value */
4877     if (volume_simple_current == NULL)
4878       volume_simple_current =
4879         getTreeInfoFromIdentifier(volumes_simple, i_to_a(100));
4880
4881     /* if that also fails, set current volume to first available value */
4882     if (volume_simple_current == NULL)
4883       volume_simple_current = volumes_simple;
4884   }
4885
4886   if (volumes_loops == NULL)
4887   {
4888     boolean current_volume_loops_found = FALSE;
4889     int i;
4890
4891     for (i = 0; volumes_list[i].value != -1; i++)
4892     {
4893       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4894       char identifier[32], name[32];
4895       int value = volumes_list[i].value;
4896       char *text = volumes_list[i].text;
4897
4898       ti->node_top = &volumes_loops;
4899       ti->sort_priority = value;
4900
4901       sprintf(identifier, "%d", value);
4902       sprintf(name, "%s", text);
4903
4904       setString(&ti->identifier, identifier);
4905       setString(&ti->name, name);
4906       setString(&ti->name_sorting, name);
4907       setString(&ti->infotext, "Loops Volume");
4908
4909       pushTreeInfo(&volumes_loops, ti);
4910
4911       if (value == setup.volume_loops)
4912         current_volume_loops_found = TRUE;
4913     }
4914
4915     if (!current_volume_loops_found)
4916     {
4917       // add entry for non-preset volume value
4918
4919       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4920       char identifier[32], name[32];
4921       int value = setup.volume_loops;
4922
4923       ti->node_top = &volumes_loops;
4924       ti->sort_priority = value;
4925
4926       sprintf(identifier, "%d", value);
4927       sprintf(name, "%d %% (Current)", value);
4928
4929       setString(&ti->identifier, identifier);
4930       setString(&ti->name, name);
4931       setString(&ti->name_sorting, name);
4932       setString(&ti->infotext, "Loops Volume");
4933
4934       pushTreeInfo(&volumes_loops, ti);
4935     }
4936
4937     /* sort volume values to start with lowest volume value */
4938     sortTreeInfo(&volumes_loops);
4939
4940     /* set current volume value to configured volume value */
4941     volume_loops_current =
4942       getTreeInfoFromIdentifier(volumes_loops,i_to_a(setup.volume_loops));
4943
4944     /* if that fails, set current volume to reliable default value */
4945     if (volume_loops_current == NULL)
4946       volume_loops_current =
4947         getTreeInfoFromIdentifier(volumes_loops, i_to_a(100));
4948
4949     /* if that also fails, set current volume to first available value */
4950     if (volume_loops_current == NULL)
4951       volume_loops_current = volumes_loops;
4952   }
4953
4954   if (volumes_music == NULL)
4955   {
4956     boolean current_volume_music_found = FALSE;
4957     int i;
4958
4959     for (i = 0; volumes_list[i].value != -1; i++)
4960     {
4961       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4962       char identifier[32], name[32];
4963       int value = volumes_list[i].value;
4964       char *text = volumes_list[i].text;
4965
4966       ti->node_top = &volumes_music;
4967       ti->sort_priority = value;
4968
4969       sprintf(identifier, "%d", value);
4970       sprintf(name, "%s", text);
4971
4972       setString(&ti->identifier, identifier);
4973       setString(&ti->name, name);
4974       setString(&ti->name_sorting, name);
4975       setString(&ti->infotext, "Music Volume");
4976
4977       pushTreeInfo(&volumes_music, ti);
4978
4979       if (value == setup.volume_music)
4980         current_volume_music_found = TRUE;
4981     }
4982
4983     if (!current_volume_music_found)
4984     {
4985       // add entry for non-preset volume value
4986
4987       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
4988       char identifier[32], name[32];
4989       int value = setup.volume_music;
4990
4991       ti->node_top = &volumes_music;
4992       ti->sort_priority = value;
4993
4994       sprintf(identifier, "%d", value);
4995       sprintf(name, "%d %% (Current)", value);
4996
4997       setString(&ti->identifier, identifier);
4998       setString(&ti->name, name);
4999       setString(&ti->name_sorting, name);
5000       setString(&ti->infotext, "Music Volume");
5001
5002       pushTreeInfo(&volumes_music, ti);
5003     }
5004
5005     /* sort volume values to start with lowest volume value */
5006     sortTreeInfo(&volumes_music);
5007
5008     /* set current volume value to configured volume value */
5009     volume_music_current =
5010       getTreeInfoFromIdentifier(volumes_music,i_to_a(setup.volume_music));
5011
5012     /* if that fails, set current volume to reliable default value */
5013     if (volume_music_current == NULL)
5014       volume_music_current =
5015         getTreeInfoFromIdentifier(volumes_music, i_to_a(100));
5016
5017     /* if that also fails, set current volume to first available value */
5018     if (volume_music_current == NULL)
5019       volume_music_current = volumes_music;
5020   }
5021
5022   setup.volume_simple = atoi(volume_simple_current->identifier);
5023   setup.volume_loops  = atoi(volume_loops_current->identifier);
5024   setup.volume_music  = atoi(volume_music_current->identifier);
5025
5026   /* needed for displaying volume text instead of identifier */
5027   volume_simple_text = volume_simple_current->name;
5028   volume_loops_text = volume_loops_current->name;
5029   volume_music_text = volume_music_current->name;
5030
5031   setup_mode = SETUP_MODE_SOUND;
5032
5033   DrawSetupScreen();
5034 }
5035
5036 static void execSetupChooseTouchControls()
5037 {
5038   setup_mode = SETUP_MODE_CHOOSE_TOUCH_CONTROL;
5039
5040   DrawSetupScreen();
5041 }
5042
5043 static void execSetupChooseMoveDistance()
5044 {
5045   setup_mode = SETUP_MODE_CHOOSE_MOVE_DISTANCE;
5046
5047   DrawSetupScreen();
5048 }
5049
5050 static void execSetupChooseDropDistance()
5051 {
5052   setup_mode = SETUP_MODE_CHOOSE_DROP_DISTANCE;
5053
5054   DrawSetupScreen();
5055 }
5056
5057 static void execSetupTouch()
5058 {
5059   if (touch_controls == NULL)
5060   {
5061     int i;
5062
5063     for (i = 0; touch_controls_list[i].value != NULL; i++)
5064     {
5065       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5066       char identifier[32], name[32];
5067       char *value = touch_controls_list[i].value;
5068       char *text = touch_controls_list[i].text;
5069
5070       ti->node_top = &touch_controls;
5071       ti->sort_priority = i;
5072
5073       sprintf(identifier, "%s", value);
5074       sprintf(name, "%s", text);
5075
5076       setString(&ti->identifier, identifier);
5077       setString(&ti->name, name);
5078       setString(&ti->name_sorting, name);
5079       setString(&ti->infotext, "Control Type");
5080
5081       pushTreeInfo(&touch_controls, ti);
5082     }
5083
5084     /* sort touch control values to start with lowest touch control value */
5085     sortTreeInfo(&touch_controls);
5086
5087     /* set current touch control value to configured touch control value */
5088     touch_control_current =
5089       getTreeInfoFromIdentifier(touch_controls, setup.touch.control_type);
5090
5091     /* if that fails, set current touch control to reliable default value */
5092     if (touch_control_current == NULL)
5093       touch_control_current =
5094         getTreeInfoFromIdentifier(touch_controls, TOUCH_CONTROL_DEFAULT);
5095
5096     /* if that also fails, set current touch control to first available value */
5097     if (touch_control_current == NULL)
5098       touch_control_current = touch_controls;
5099   }
5100
5101   if (move_distances == NULL)
5102   {
5103     int i;
5104
5105     for (i = 0; distances_list[i].value != -1; i++)
5106     {
5107       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5108       char identifier[32], name[32];
5109       int value = distances_list[i].value;
5110       char *text = distances_list[i].text;
5111
5112       ti->node_top = &move_distances;
5113       ti->sort_priority = value;
5114
5115       sprintf(identifier, "%d", value);
5116       sprintf(name, "%s", text);
5117
5118       setString(&ti->identifier, identifier);
5119       setString(&ti->name, name);
5120       setString(&ti->name_sorting, name);
5121       setString(&ti->infotext, "Move Distance");
5122
5123       pushTreeInfo(&move_distances, ti);
5124     }
5125
5126     /* sort distance values to start with lowest distance value */
5127     sortTreeInfo(&move_distances);
5128
5129     /* set current distance value to configured distance value */
5130     move_distance_current =
5131       getTreeInfoFromIdentifier(move_distances,
5132                                 i_to_a(setup.touch.move_distance));
5133
5134     /* if that fails, set current distance to reliable default value */
5135     if (move_distance_current == NULL)
5136       move_distance_current =
5137         getTreeInfoFromIdentifier(move_distances, i_to_a(1));
5138
5139     /* if that also fails, set current distance to first available value */
5140     if (move_distance_current == NULL)
5141       move_distance_current = move_distances;
5142   }
5143
5144   if (drop_distances == NULL)
5145   {
5146     int i;
5147
5148     for (i = 0; distances_list[i].value != -1; i++)
5149     {
5150       TreeInfo *ti = newTreeInfo_setDefaults(TREE_TYPE_UNDEFINED);
5151       char identifier[32], name[32];
5152       int value = distances_list[i].value;
5153       char *text = distances_list[i].text;
5154
5155       ti->node_top = &drop_distances;
5156       ti->sort_priority = value;
5157
5158       sprintf(identifier, "%d", value);
5159       sprintf(name, "%s", text);
5160
5161       setString(&ti->identifier, identifier);
5162       setString(&ti->name, name);
5163       setString(&ti->name_sorting, name);
5164       setString(&ti->infotext, "Drop Distance");
5165
5166       pushTreeInfo(&drop_distances, ti);
5167     }
5168
5169     /* sort distance values to start with lowest distance value */
5170     sortTreeInfo(&drop_distances);
5171
5172     /* set current distance value to configured distance value */
5173     drop_distance_current =
5174       getTreeInfoFromIdentifier(drop_distances,
5175                                 i_to_a(setup.touch.drop_distance));
5176
5177     /* if that fails, set current distance to reliable default value */
5178     if (drop_distance_current == NULL)
5179       drop_distance_current =
5180         getTreeInfoFromIdentifier(drop_distances, i_to_a(1));
5181
5182     /* if that also fails, set current distance to first available value */
5183     if (drop_distance_current == NULL)
5184       drop_distance_current = drop_distances;
5185   }
5186
5187   setup.touch.control_type = touch_control_current->identifier;
5188   setup.touch.move_distance = atoi(move_distance_current->identifier);
5189   setup.touch.drop_distance = atoi(drop_distance_current->identifier);
5190
5191   /* needed for displaying volume text instead of identifier */
5192   touch_controls_text = touch_control_current->name;
5193   move_distance_text = move_distance_current->name;
5194   drop_distance_text = drop_distance_current->name;
5195
5196   setup_mode = SETUP_MODE_TOUCH;
5197
5198   DrawSetupScreen();
5199 }
5200
5201 static void execSetupArtwork()
5202 {
5203 #if 0
5204   printf("::: '%s', '%s', '%s'\n",
5205          artwork.gfx_current->subdir,
5206          artwork.gfx_current->fullpath,
5207          artwork.gfx_current->basepath);
5208 #endif
5209
5210   setup.graphics_set = artwork.gfx_current->identifier;
5211   setup.sounds_set = artwork.snd_current->identifier;
5212   setup.music_set = artwork.mus_current->identifier;
5213
5214   /* needed if last screen (setup choice) changed graphics, sounds or music */
5215   ReloadCustomArtwork(0);
5216
5217   /* needed for displaying artwork name instead of artwork identifier */
5218   graphics_set_name = artwork.gfx_current->name;
5219   sounds_set_name = artwork.snd_current->name;
5220   music_set_name = artwork.mus_current->name;
5221
5222   setup_mode = SETUP_MODE_ARTWORK;
5223
5224   DrawSetupScreen();
5225 }
5226
5227 static void execSetupChooseGraphics()
5228 {
5229   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
5230
5231   DrawSetupScreen();
5232 }
5233
5234 static void execSetupChooseSounds()
5235 {
5236   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
5237
5238   DrawSetupScreen();
5239 }
5240
5241 static void execSetupChooseMusic()
5242 {
5243   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
5244
5245   DrawSetupScreen();
5246 }
5247
5248 static void execSetupInput()
5249 {
5250   setup_mode = SETUP_MODE_INPUT;
5251
5252   DrawSetupScreen();
5253 }
5254
5255 static void execSetupShortcuts()
5256 {
5257   setup_mode = SETUP_MODE_SHORTCUTS;
5258
5259   DrawSetupScreen();
5260 }
5261
5262 static void execSetupShortcuts1()
5263 {
5264   setup_mode = SETUP_MODE_SHORTCUTS_1;
5265
5266   DrawSetupScreen();
5267 }
5268
5269 static void execSetupShortcuts2()
5270 {
5271   setup_mode = SETUP_MODE_SHORTCUTS_2;
5272
5273   DrawSetupScreen();
5274 }
5275
5276 static void execSetupShortcuts3()
5277 {
5278   setup_mode = SETUP_MODE_SHORTCUTS_3;
5279
5280   DrawSetupScreen();
5281 }
5282
5283 static void execSetupShortcuts4()
5284 {
5285   setup_mode = SETUP_MODE_SHORTCUTS_4;
5286
5287   DrawSetupScreen();
5288 }
5289
5290 static void execSetupShortcuts5()
5291 {
5292   setup_mode = SETUP_MODE_SHORTCUTS_5;
5293
5294   DrawSetupScreen();
5295 }
5296
5297 static void execExitSetup()
5298 {
5299   SetGameStatus(GAME_MODE_MAIN);
5300
5301   DrawMainMenu();
5302 }
5303
5304 static void execSaveAndExitSetup()
5305 {
5306   SaveSetup();
5307   execExitSetup();
5308 }
5309
5310 static struct TokenInfo setup_info_main[] =
5311 {
5312   { TYPE_ENTER_MENU,    execSetupGame,          "Game & Menu"           },
5313   { TYPE_ENTER_MENU,    execSetupEditor,        "Editor"                },
5314   { TYPE_ENTER_MENU,    execSetupGraphics,      "Graphics"              },
5315   { TYPE_ENTER_MENU,    execSetupSound,         "Sound & Music"         },
5316   { TYPE_ENTER_MENU,    execSetupArtwork,       "Custom Artwork"        },
5317   { TYPE_ENTER_MENU,    execSetupInput,         "Input Devices"         },
5318   { TYPE_ENTER_MENU,    execSetupTouch,         "Touch Controls"        },
5319   { TYPE_ENTER_MENU,    execSetupShortcuts,     "Key Shortcuts"         },
5320   { TYPE_EMPTY,         NULL,                   ""                      },
5321   { TYPE_LEAVE_MENU,    execExitSetup,          "Exit"                  },
5322   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   "Save and Exit"         },
5323
5324   { 0,                  NULL,                   NULL                    }
5325 };
5326
5327 static struct TokenInfo setup_info_game[] =
5328 {
5329   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode (Multi-Player):" },
5330   { TYPE_YES_NO,        &setup.input_on_focus,  "Only Move Focussed Player:" },
5331   { TYPE_SWITCH,        &setup.time_limit,      "Time Limit:"           },
5332   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
5333   { TYPE_SWITCH,        &setup.skip_levels,     "Skip Unsolved Levels:" },
5334   { TYPE_SWITCH,        &setup.increment_levels,"Increment Solved Levels:" },
5335   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record Tapes:"    },
5336   { TYPE_ENTER_LIST,    execSetupChooseGameSpeed, "Game Speed:"         },
5337   { TYPE_STRING,        &game_speed_text,       ""                      },
5338 #if 1
5339   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
5340   { TYPE_STRING,        &scroll_delay_text,     ""                      },
5341 #endif
5342   { TYPE_ENTER_LIST, execSetupChooseSnapshotMode,"Game Engine Snapshot Mode:" },
5343   { TYPE_STRING,        &snapshot_mode_text,    ""                      },
5344   { TYPE_SWITCH,        &setup.show_snapshot_buttons,"Show Snapshot Buttons:" },
5345   { TYPE_EMPTY,         NULL,                   ""                      },
5346   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5347
5348   { 0,                  NULL,                   NULL                    }
5349 };
5350
5351 static struct TokenInfo setup_info_editor[] =
5352 {
5353 #if 0
5354   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "Boulder Dash:" },
5355   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
5356   { TYPE_SWITCH, &setup.editor.el_emerald_mine_club,    "Emerald Mine Club:" },
5357   { TYPE_SWITCH,        &setup.editor.el_more,          "Rocks'n'Diamonds:" },
5358   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
5359   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
5360   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamond Caves II:" },
5361   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX-Boulderdash:" },
5362   { TYPE_SWITCH,        &setup.editor.el_chars,         "Text Characters:" },
5363   { TYPE_SWITCH, &setup.editor.el_steel_chars, "Text Characters (Steel):" },
5364 #endif
5365   { TYPE_SWITCH,        &setup.editor.el_classic,  "Classic Elements:" },
5366   { TYPE_SWITCH,        &setup.editor.el_custom,  "Custom & Group Elements:" },
5367 #if 0
5368   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
5369 #endif
5370   { TYPE_SWITCH, &setup.editor.el_user_defined, "User defined element list:" },
5371   { TYPE_SWITCH,        &setup.editor.el_dynamic,  "Dynamic level elements:" },
5372   { TYPE_EMPTY,         NULL,                   ""                      },
5373 #if 0
5374   { TYPE_SWITCH,        &setup.editor.el_by_game,   "Show elements by game:" },
5375   { TYPE_SWITCH,        &setup.editor.el_by_type,   "Show elements by type:" },
5376   { TYPE_EMPTY,         NULL,                   ""                      },
5377 #endif
5378   { TYPE_SWITCH, &setup.editor.show_element_token,      "Show element token:" },
5379   { TYPE_EMPTY,         NULL,                   ""                      },
5380   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5381
5382   { 0,                  NULL,                   NULL                    }
5383 };
5384
5385 static struct TokenInfo setup_info_graphics[] =
5386 {
5387 #if defined(TARGET_SDL2) && !defined(PLATFORM_ANDROID)
5388   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
5389   { TYPE_ENTER_LIST,    execSetupChooseWindowSize, "Window Scaling:"    },
5390   { TYPE_STRING,        &window_size_text,      ""                      },
5391   { TYPE_ENTER_LIST,    execSetupChooseScalingType, "Anti-Aliasing:"    },
5392   { TYPE_STRING,        &scaling_type_text,     ""                      },
5393   { TYPE_ENTER_LIST,    execSetupChooseRenderingMode, "Special Rendering:" },
5394   { TYPE_STRING,        &rendering_mode_text,   ""                      },
5395 #endif
5396 #if 0
5397   { TYPE_ENTER_LIST,    execSetupChooseScrollDelay, "Scroll Delay:"     },
5398   { TYPE_STRING,        &scroll_delay_text,     ""                      },
5399 #endif
5400   { TYPE_SWITCH,        &setup.fade_screens,    "Fade Screens:"         },
5401   { TYPE_SWITCH,        &setup.quick_switch,    "Quick Player Focus Switch:" },
5402   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Menu Doors:"     },
5403   { TYPE_SWITCH,        &setup.show_titlescreen,"Show Title Screens:"   },
5404   { TYPE_SWITCH,        &setup.toons,           "Show Menu Animations:" },
5405   { TYPE_ECS_AGA,       &setup.prefer_aga_graphics,"EMC graphics preference:" },
5406   { TYPE_SWITCH, &setup.sp_show_border_elements,"Supaplex Border Elements:" },
5407   { TYPE_SWITCH,        &setup.small_game_graphics, "Small Game Graphics:" },
5408   { TYPE_EMPTY,         NULL,                   ""                      },
5409   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5410
5411   { 0,                  NULL,                   NULL                    }
5412 };
5413
5414 static struct TokenInfo setup_info_sound[] =
5415 {
5416   { TYPE_SWITCH,        &setup.sound_simple,    "Sound Effects (Normal):"  },
5417   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Effects (Looping):" },
5418   { TYPE_SWITCH,        &setup.sound_music,     "Music:"                },
5419   { TYPE_EMPTY,         NULL,                   ""                      },
5420   { TYPE_ENTER_LIST,    execSetupChooseVolumeSimple, "Sound Volume (Normal):" },
5421   { TYPE_STRING,        &volume_simple_text,    ""                      },
5422   { TYPE_ENTER_LIST,    execSetupChooseVolumeLoops, "Sound Volume (Looping):" },
5423   { TYPE_STRING,        &volume_loops_text,     ""                      },
5424   { TYPE_ENTER_LIST,    execSetupChooseVolumeMusic, "Music Volume:"     },
5425   { TYPE_STRING,        &volume_music_text,     ""                      },
5426   { TYPE_EMPTY,         NULL,                   ""                      },
5427   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5428
5429   { 0,                  NULL,                   NULL                    }
5430 };
5431
5432 static struct TokenInfo setup_info_artwork[] =
5433 {
5434   { TYPE_ENTER_LIST,    execSetupChooseGraphics,"Custom Graphics:"      },
5435   { TYPE_STRING,        &graphics_set_name,     ""                      },
5436   { TYPE_ENTER_LIST,    execSetupChooseSounds,  "Custom Sounds:"        },
5437   { TYPE_STRING,        &sounds_set_name,       ""                      },
5438   { TYPE_ENTER_LIST,    execSetupChooseMusic,   "Custom Music:"         },
5439   { TYPE_STRING,        &music_set_name,        ""                      },
5440   { TYPE_EMPTY,         NULL,                   ""                      },
5441   { TYPE_YES_NO_AUTO,&setup.override_level_graphics,"Override Level Graphics:"},
5442   { TYPE_YES_NO_AUTO,&setup.override_level_sounds,  "Override Level Sounds:"  },
5443   { TYPE_YES_NO_AUTO,&setup.override_level_music,   "Override Level Music:"   },
5444   { TYPE_EMPTY,         NULL,                   ""                      },
5445   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5446
5447   { 0,                  NULL,                   NULL                    }
5448 };
5449
5450 static struct TokenInfo setup_info_input[] =
5451 {
5452   { TYPE_SWITCH,        NULL,                   "Player:"               },
5453   { TYPE_SWITCH,        NULL,                   "Device:"               },
5454   { TYPE_SWITCH,        NULL,                   ""                      },
5455   { TYPE_EMPTY,         NULL,                   ""                      },
5456   { TYPE_EMPTY,         NULL,                   ""                      },
5457   { TYPE_EMPTY,         NULL,                   ""                      },
5458   { TYPE_EMPTY,         NULL,                   ""                      },
5459   { TYPE_EMPTY,         NULL,                   ""                      },
5460   { TYPE_EMPTY,         NULL,                   ""                      },
5461   { TYPE_EMPTY,         NULL,                   ""                      },
5462   { TYPE_EMPTY,         NULL,                   ""                      },
5463   { TYPE_EMPTY,         NULL,                   ""                      },
5464   { TYPE_EMPTY,         NULL,                   ""                      },
5465   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5466
5467   { 0,                  NULL,                   NULL                    }
5468 };
5469
5470 static struct TokenInfo setup_info_touch[] =
5471 {
5472   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
5473   { TYPE_STRING,        &touch_controls_text,   ""                      },
5474   { TYPE_EMPTY,         NULL,                   ""                      },
5475   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5476
5477   { 0,                  NULL,                   NULL                    }
5478 };
5479
5480 static struct TokenInfo setup_info_touch_wipe_gestures[] =
5481 {
5482   { TYPE_ENTER_LIST,    execSetupChooseTouchControls, "Touch Control Type:" },
5483   { TYPE_STRING,        &touch_controls_text,   ""                      },
5484   { TYPE_EMPTY,         NULL,                   ""                      },
5485   { TYPE_ENTER_LIST,    execSetupChooseMoveDistance, "Move Trigger Distance:" },
5486   { TYPE_STRING,        &move_distance_text,    ""                      },
5487   { TYPE_ENTER_LIST,    execSetupChooseDropDistance, "Drop Trigger Distance:" },
5488   { TYPE_STRING,        &drop_distance_text,    ""                      },
5489   { TYPE_EMPTY,         NULL,                   ""                      },
5490   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5491
5492   { 0,                  NULL,                   NULL                    }
5493 };
5494
5495 static struct TokenInfo setup_info_shortcuts[] =
5496 {
5497   { TYPE_ENTER_MENU,    execSetupShortcuts1,    "Various Keys"          },
5498   { TYPE_ENTER_MENU,    execSetupShortcuts2,    "Player Focus"          },
5499   { TYPE_ENTER_MENU,    execSetupShortcuts3,    "Tape Buttons"          },
5500   { TYPE_ENTER_MENU,    execSetupShortcuts4,    "Sound & Music"         },
5501   { TYPE_ENTER_MENU,    execSetupShortcuts5,    "TAS Snap Keys"         },
5502   { TYPE_EMPTY,         NULL,                   ""                      },
5503   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
5504
5505   { 0,                  NULL,                   NULL                    }
5506 };
5507
5508 static struct TokenInfo setup_info_shortcuts_1[] =
5509 {
5510   { TYPE_KEYTEXT,       NULL,           "Quick Save Game to Tape:",     },
5511   { TYPE_KEY,           &setup.shortcut.save_game, ""                   },
5512   { TYPE_KEYTEXT,       NULL,           "Quick Load Game from Tape:",   },
5513   { TYPE_KEY,           &setup.shortcut.load_game, ""                   },
5514   { TYPE_KEYTEXT,       NULL,           "Start Game & Toggle Pause:",   },
5515   { TYPE_KEY,           &setup.shortcut.toggle_pause, ""                },
5516   { TYPE_EMPTY,         NULL,                   ""                      },
5517   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on 'Esc' Key:"     },
5518   { TYPE_YES_NO, &setup.ask_on_escape_editor,   "Ask on 'Esc' Key (Editor):" },
5519   { TYPE_EMPTY,         NULL,                   ""                      },
5520   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5521
5522   { 0,                  NULL,                   NULL                    }
5523 };
5524
5525 static struct TokenInfo setup_info_shortcuts_2[] =
5526 {
5527   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 1:",       },
5528   { TYPE_KEY,           &setup.shortcut.focus_player[0], ""             },
5529   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 2:",       },
5530   { TYPE_KEY,           &setup.shortcut.focus_player[1], ""             },
5531   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 3:",       },
5532   { TYPE_KEY,           &setup.shortcut.focus_player[2], ""             },
5533   { TYPE_KEYTEXT,       NULL,           "Set Focus to Player 4:",       },
5534   { TYPE_KEY,           &setup.shortcut.focus_player[3], ""             },
5535   { TYPE_KEYTEXT,       NULL,           "Set Focus to All Players:",    },
5536   { TYPE_KEY,           &setup.shortcut.focus_player_all, ""            },
5537   { TYPE_EMPTY,         NULL,                   ""                      },
5538   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5539
5540   { 0,                  NULL,                   NULL                    }
5541 };
5542
5543 static struct TokenInfo setup_info_shortcuts_3[] =
5544 {
5545   { TYPE_KEYTEXT,       NULL,                   "Eject Tape:",          },
5546   { TYPE_KEY,           &setup.shortcut.tape_eject, ""                  },
5547   { TYPE_KEYTEXT,       NULL,                   "Warp / Single Step:",  },
5548   { TYPE_KEY,           &setup.shortcut.tape_extra, ""                  },
5549   { TYPE_KEYTEXT,       NULL,                   "Stop Tape:",           },
5550   { TYPE_KEY,           &setup.shortcut.tape_stop, ""                   },
5551   { TYPE_KEYTEXT,       NULL,                   "Pause / Unpause Tape:",},
5552   { TYPE_KEY,           &setup.shortcut.tape_pause, ""                  },
5553   { TYPE_KEYTEXT,       NULL,                   "Record Tape:",         },
5554   { TYPE_KEY,           &setup.shortcut.tape_record, ""                 },
5555   { TYPE_KEYTEXT,       NULL,                   "Play Tape:",           },
5556   { TYPE_KEY,           &setup.shortcut.tape_play, ""                   },
5557   { TYPE_EMPTY,         NULL,                   ""                      },
5558   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5559
5560   { 0,                  NULL,                   NULL                    }
5561 };
5562
5563 static struct TokenInfo setup_info_shortcuts_4[] =
5564 {
5565   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Normal):", },
5566   { TYPE_KEY,           &setup.shortcut.sound_simple, ""                },
5567   { TYPE_KEYTEXT,       NULL,           "Toggle Sound Effects (Looping):", },
5568   { TYPE_KEY,           &setup.shortcut.sound_loops, ""                 },
5569   { TYPE_KEYTEXT,       NULL,           "Toggle Music:",                },
5570   { TYPE_KEY,           &setup.shortcut.sound_music, ""                 },
5571   { TYPE_EMPTY,         NULL,                   ""                      },
5572   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5573
5574   { 0,                  NULL,                   NULL                    }
5575 };
5576
5577 static struct TokenInfo setup_info_shortcuts_5[] =
5578 {
5579   { TYPE_KEYTEXT,       NULL,                   "Snap Left:",           },
5580   { TYPE_KEY,           &setup.shortcut.snap_left, ""                   },
5581   { TYPE_KEYTEXT,       NULL,                   "Snap Right:",          },
5582   { TYPE_KEY,           &setup.shortcut.snap_right, ""                  },
5583   { TYPE_KEYTEXT,       NULL,                   "Snap Up:",             },
5584   { TYPE_KEY,           &setup.shortcut.snap_up, ""                     },
5585   { TYPE_KEYTEXT,       NULL,                   "Snap Down:",           },
5586   { TYPE_KEY,           &setup.shortcut.snap_down, ""                   },
5587   { TYPE_EMPTY,         NULL,                   ""                      },
5588   { TYPE_LEAVE_MENU,    execSetupShortcuts,     "Back"                  },
5589
5590   { 0,                  NULL,                   NULL                    }
5591 };
5592
5593 static Key getSetupKey()
5594 {
5595   Key key = KSYM_UNDEFINED;
5596   boolean got_key_event = FALSE;
5597
5598   while (!got_key_event)
5599   {
5600     if (PendingEvent())         /* got event */
5601     {
5602       Event event;
5603
5604       NextEvent(&event);
5605
5606       switch (event.type)
5607       {
5608         case EVENT_KEYPRESS:
5609           {
5610             key = GetEventKey((KeyEvent *)&event, TRUE);
5611
5612             /* press 'Escape' or 'Enter' to keep the existing key binding */
5613             if (key == KSYM_Escape || key == KSYM_Return)
5614               key = KSYM_UNDEFINED;     /* keep old value */
5615
5616             got_key_event = TRUE;
5617           }
5618           break;
5619
5620         case EVENT_KEYRELEASE:
5621           key_joystick_mapping = 0;
5622           break;
5623
5624         default:
5625           HandleOtherEvents(&event);
5626           break;
5627       }
5628     }
5629
5630     BackToFront();
5631   }
5632
5633   return key;
5634 }
5635
5636 static int getSetupValueFont(int type, void *value)
5637 {
5638   if (type & TYPE_GHOSTED)
5639     return FONT_OPTION_OFF;
5640   else if (type & TYPE_KEY)
5641     return (type & TYPE_QUERY ? FONT_INPUT_1_ACTIVE : FONT_VALUE_1);
5642   else if (type & TYPE_STRING)
5643     return FONT_VALUE_2;
5644   else if (type & TYPE_ECS_AGA)
5645     return FONT_VALUE_1;
5646   else if (type & TYPE_BOOLEAN_STYLE)
5647     return (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
5648   else if (type & TYPE_YES_NO_AUTO)
5649     return (*(int *)value == AUTO  ? FONT_OPTION_ON :
5650             *(int *)value == FALSE ? FONT_OPTION_OFF : FONT_OPTION_ON);
5651   else
5652     return FONT_VALUE_1;
5653 }
5654
5655 static int getSetupValueFontNarrow(int type, int font_nr)
5656 {
5657   return (font_nr == FONT_VALUE_1    ? FONT_VALUE_NARROW :
5658           font_nr == FONT_OPTION_ON  ? FONT_OPTION_ON_NARROW :
5659           font_nr == FONT_OPTION_OFF ? FONT_OPTION_OFF_NARROW :
5660           font_nr);
5661 }
5662
5663 static void drawSetupValue(int screen_pos, int setup_info_pos_raw)
5664 {
5665   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
5666   struct TokenInfo *si = &setup_info[si_pos];
5667   boolean font_draw_xoffset_modified = FALSE;
5668   boolean scrollbar_needed = (num_setup_info < max_setup_info);
5669   int font_draw_xoffset_old = -1;
5670   int xoffset = (scrollbar_needed ? -1 : 0);
5671   int menu_screen_value_xpos = MENU_SCREEN_VALUE_XPOS + xoffset;
5672   int menu_screen_max_xpos = MENU_SCREEN_MAX_XPOS + xoffset;
5673   int xpos = menu_screen_value_xpos;
5674   int ypos = MENU_SCREEN_START_YPOS + screen_pos;
5675   int startx = mSX + xpos * 32;
5676   int starty = mSY + ypos * 32;
5677   int font_nr, font_nr_default, font_width_default;
5678   int type = si->type;
5679   void *value = si->value;
5680   char *value_string = getSetupValue(type, value);
5681   int i;
5682
5683   if (value_string == NULL)
5684     return;
5685
5686   if (type & TYPE_KEY)
5687   {
5688     xpos = MENU_SCREEN_START_XPOS;
5689
5690     if (type & TYPE_QUERY)
5691       value_string = "<press key>";
5692   }
5693   else if (type & TYPE_STRING)
5694   {
5695     int max_value_len = (SCR_FIELDX - 2) * 2;
5696
5697     xpos = MENU_SCREEN_START_XPOS;
5698
5699     if (strlen(value_string) > max_value_len)
5700       value_string[max_value_len] = '\0';
5701   }
5702   else if (type & TYPE_YES_NO_AUTO)
5703   {
5704     xpos = menu_screen_value_xpos - 1;
5705   }
5706
5707   startx = mSX + xpos * 32;
5708   starty = mSY + ypos * 32;
5709   font_nr_default = getSetupValueFont(type, value);
5710   font_width_default = getFontWidth(font_nr_default);
5711
5712   font_nr = font_nr_default;
5713
5714   // special check if right-side setup values moved left due to scrollbar
5715   if (scrollbar_needed && xpos > MENU_SCREEN_START_XPOS)
5716   {
5717     int max_menu_text_length = 26;      // maximum text length for classic menu
5718     int font_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
5719     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
5720     int text_font_nr = getMenuTextFont(FONT_MENU_2);
5721     int text_font_xoffset = getFontBitmapInfo(text_font_nr)->draw_xoffset;
5722     int text_width = max_menu_text_length * getFontWidth(text_font_nr);
5723
5724     if (startx + font_xoffset < text_startx + text_width + text_font_xoffset)
5725     {
5726       xpos += 1;
5727       startx = mSX + xpos * 32;
5728
5729       font_nr = getSetupValueFontNarrow(type, font_nr);
5730     }
5731   }
5732
5733   /* downward compatibility correction for Juergen Bonhagen's menu settings */
5734   if (setup_mode != SETUP_MODE_INPUT)
5735   {
5736     int max_menu_text_length_big = (menu_screen_value_xpos -
5737                                     MENU_SCREEN_START_XPOS);
5738     int max_menu_text_length_medium = max_menu_text_length_big * 2;
5739     int check_font_nr = FONT_OPTION_ON; /* known font that needs correction */
5740     int font1_xoffset = getFontBitmapInfo(font_nr)->draw_xoffset;
5741     int font2_xoffset = getFontBitmapInfo(check_font_nr)->draw_xoffset;
5742     int text_startx = mSX + MENU_SCREEN_START_XPOS * 32;
5743     int text_font_nr = getMenuTextFont(FONT_MENU_2);
5744     int text_font_xoffset = getFontBitmapInfo(text_font_nr)->draw_xoffset;
5745     int text_width = max_menu_text_length_medium * getFontWidth(text_font_nr);
5746     boolean correct_font_draw_xoffset = FALSE;
5747
5748     if (xpos == MENU_SCREEN_START_XPOS &&
5749         startx + font1_xoffset < text_startx + text_font_xoffset)
5750       correct_font_draw_xoffset = TRUE;
5751
5752     if (xpos == menu_screen_value_xpos &&
5753         startx + font2_xoffset < text_startx + text_width + text_font_xoffset)
5754       correct_font_draw_xoffset = TRUE;
5755
5756     /* check if setup value would overlap with setup text when printed */
5757     /* (this can happen for extreme/wrong values for font draw offset) */
5758     if (correct_font_draw_xoffset)
5759     {
5760       font_draw_xoffset_old = getFontBitmapInfo(font_nr)->draw_xoffset;
5761       font_draw_xoffset_modified = TRUE;
5762
5763       if (type & TYPE_KEY)
5764         getFontBitmapInfo(font_nr)->draw_xoffset += 2 * getFontWidth(font_nr);
5765       else if (!(type & TYPE_STRING))
5766         getFontBitmapInfo(font_nr)->draw_xoffset = text_font_xoffset + 20 -
5767           max_menu_text_length_medium * (16 - getFontWidth(text_font_nr));
5768     }
5769   }
5770
5771   for (i = 0; i <= menu_screen_max_xpos - xpos; i++)
5772     DrawText(startx + i * font_width_default, starty, " ", font_nr_default);
5773
5774   DrawText(startx, starty, value_string, font_nr);
5775
5776   if (font_draw_xoffset_modified)
5777     getFontBitmapInfo(font_nr)->draw_xoffset = font_draw_xoffset_old;
5778 }
5779
5780 static void changeSetupValue(int screen_pos, int setup_info_pos_raw, int dx)
5781 {
5782   int si_pos = (setup_info_pos_raw < 0 ? screen_pos : setup_info_pos_raw);
5783   struct TokenInfo *si = &setup_info[si_pos];
5784
5785   if (si->type & TYPE_BOOLEAN_STYLE)
5786   {
5787     *(boolean *)si->value ^= TRUE;
5788   }
5789   else if (si->type & TYPE_YES_NO_AUTO)
5790   {
5791     *(int *)si->value =
5792       (dx == -1 ?
5793        (*(int *)si->value == AUTO ? TRUE :
5794         *(int *)si->value == TRUE ? FALSE : AUTO) :
5795        (*(int *)si->value == TRUE ? AUTO :
5796         *(int *)si->value == AUTO ? FALSE : TRUE));
5797   }
5798   else if (si->type & TYPE_KEY)
5799   {
5800     Key key;
5801
5802     si->type |= TYPE_QUERY;
5803     drawSetupValue(screen_pos, setup_info_pos_raw);
5804     si->type &= ~TYPE_QUERY;
5805
5806     key = getSetupKey();
5807     if (key != KSYM_UNDEFINED)
5808       *(Key *)si->value = key;
5809   }
5810
5811   drawSetupValue(screen_pos, setup_info_pos_raw);
5812
5813   // fullscreen state may have changed at this point
5814   if (si->value == &setup.fullscreen)
5815     ToggleFullscreenOrChangeWindowScalingIfNeeded();
5816 }
5817
5818 static struct TokenInfo *getSetupInfoFinal(struct TokenInfo *setup_info_orig)
5819 {
5820   static struct TokenInfo *setup_info_hide = NULL;
5821   int list_size = 0;
5822   int list_pos = 0;
5823   int i;
5824
5825   /* determine maximum list size of target list */
5826   while (setup_info_orig[list_size++].type != 0);
5827
5828   /* free, allocate and clear memory for target list */
5829   checked_free(setup_info_hide);
5830   setup_info_hide = checked_calloc(list_size * sizeof(struct TokenInfo));
5831
5832   /* copy setup info list without setup entries marked as hidden */
5833   for (i = 0; setup_info_orig[i].type != 0; i++)
5834     if (!hideSetupEntry(setup_info_orig[i].value))
5835       setup_info_hide[list_pos++] = setup_info_orig[i];
5836
5837   return setup_info_hide;
5838 }
5839
5840 static void DrawSetupScreen_Generic()
5841 {
5842   int fade_mask = REDRAW_FIELD;
5843   boolean redraw_all = FALSE;
5844   char *title_string = NULL;
5845   int i;
5846
5847   if (CheckIfGlobalBorderHasChanged())
5848     fade_mask = REDRAW_ALL;
5849
5850   UnmapAllGadgets();
5851   FadeMenuSoundsAndMusic();
5852
5853   FreeScreenGadgets();
5854   CreateScreenGadgets();
5855
5856   if (redraw_mask & REDRAW_ALL)
5857     redraw_all = TRUE;
5858
5859   FadeOut(fade_mask);
5860
5861   /* needed if different viewport properties defined for setup screen */
5862   ChangeViewportPropertiesIfNeeded();
5863
5864   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
5865
5866   ClearField();
5867
5868   OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
5869
5870   if (setup_mode == SETUP_MODE_MAIN)
5871   {
5872     setup_info = setup_info_main;
5873     title_string = "Setup";
5874   }
5875   else if (setup_mode == SETUP_MODE_GAME)
5876   {
5877     setup_info = setup_info_game;
5878     title_string = "Setup Game";
5879   }
5880   else if (setup_mode == SETUP_MODE_EDITOR)
5881   {
5882     setup_info = setup_info_editor;
5883     title_string = "Setup Editor";
5884   }
5885   else if (setup_mode == SETUP_MODE_GRAPHICS)
5886   {
5887     setup_info = setup_info_graphics;
5888     title_string = "Setup Graphics";
5889   }
5890   else if (setup_mode == SETUP_MODE_SOUND)
5891   {
5892     setup_info = setup_info_sound;
5893     title_string = "Setup Sound";
5894   }
5895   else if (setup_mode == SETUP_MODE_ARTWORK)
5896   {
5897     setup_info = setup_info_artwork;
5898     title_string = "Custom Artwork";
5899   }
5900   else if (setup_mode == SETUP_MODE_TOUCH)
5901   {
5902     setup_info = setup_info_touch;
5903     title_string = "Setup Touch Ctrls";
5904
5905     if (strEqual(setup.touch.control_type, TOUCH_CONTROL_WIPE_GESTURES))
5906       setup_info = setup_info_touch_wipe_gestures;
5907   }
5908   else if (setup_mode == SETUP_MODE_SHORTCUTS)
5909   {
5910     setup_info = setup_info_shortcuts;
5911     title_string = "Setup Shortcuts";
5912   }
5913   else if (setup_mode == SETUP_MODE_SHORTCUTS_1)
5914   {
5915     setup_info = setup_info_shortcuts_1;
5916     title_string = "Setup Shortcuts";
5917   }
5918   else if (setup_mode == SETUP_MODE_SHORTCUTS_2)
5919   {
5920     setup_info = setup_info_shortcuts_2;
5921     title_string = "Setup Shortcuts";
5922   }
5923   else if (setup_mode == SETUP_MODE_SHORTCUTS_3)
5924   {
5925     setup_info = setup_info_shortcuts_3;
5926     title_string = "Setup Shortcuts";
5927   }
5928   else if (setup_mode == SETUP_MODE_SHORTCUTS_4)
5929   {
5930     setup_info = setup_info_shortcuts_4;
5931     title_string = "Setup Shortcuts";
5932   }
5933   else if (setup_mode == SETUP_MODE_SHORTCUTS_5)
5934   {
5935     setup_info = setup_info_shortcuts_5;
5936     title_string = "Setup Shortcuts";
5937   }
5938
5939   /* use modified setup info without setup entries marked as hidden */
5940   setup_info = getSetupInfoFinal(setup_info);
5941
5942   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, title_string);
5943
5944   // determine maximal number of setup entries that can be displayed on screen
5945   num_setup_info = 0;
5946   for (i = 0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
5947     num_setup_info++;
5948
5949   // determine maximal number of setup entries available for this setup screen
5950   max_setup_info = 0;
5951   for (i = 0; setup_info[i].type != 0; i++)
5952     max_setup_info++;
5953
5954   HandleSetupScreen_Generic(0, 0, 0, 0, MB_MENU_INITIALIZE);
5955
5956   MapScreenGadgets(max_setup_info);
5957
5958   if (redraw_all)
5959     redraw_mask = fade_mask = REDRAW_ALL;
5960
5961   DrawMaskedBorder(fade_mask);
5962
5963   FadeIn(fade_mask);
5964 }
5965
5966 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
5967 {
5968   menu_info = setup_info;
5969
5970   HandleMenuScreen(mx, my, dx, dy, button,
5971                    setup_mode, num_setup_info, max_setup_info);
5972 }
5973
5974 void DrawSetupScreen_Input()
5975 {
5976   int i;
5977
5978   FadeOut(REDRAW_FIELD);
5979
5980   ClearField();
5981
5982   setup_info = setup_info_input;
5983
5984   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Setup Input");
5985
5986   for (i = 0; setup_info[i].type != 0 && i < MAX_MENU_ENTRIES_ON_SCREEN; i++)
5987   {
5988     if (setup_info[i].type & (TYPE_ENTER_MENU|TYPE_ENTER_LIST))
5989       initCursor(i, IMG_MENU_BUTTON_ENTER_MENU);
5990     else if (setup_info[i].type & (TYPE_LEAVE_MENU|TYPE_LEAVE_LIST))
5991       initCursor(i, IMG_MENU_BUTTON_LEAVE_MENU);
5992     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
5993       initCursor(i, IMG_MENU_BUTTON);
5994
5995     DrawCursorAndText_Setup(i, -1, FALSE);
5996   }
5997
5998   /* create gadgets for setup input menu screen */
5999   FreeScreenGadgets();
6000   CreateScreenGadgets();
6001
6002   /* map gadgets for setup input menu screen */
6003   MapScreenMenuGadgets(SCREEN_MASK_INPUT);
6004
6005   HandleSetupScreen_Input(0, 0, 0, 0, MB_MENU_INITIALIZE);
6006
6007   FadeIn(REDRAW_FIELD);
6008 }
6009
6010 static void setJoystickDeviceToNr(char *device_name, int device_nr)
6011 {
6012   if (device_name == NULL)
6013     return;
6014
6015   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
6016     device_nr = 0;
6017
6018   if (strlen(device_name) > 1)
6019   {
6020     char c1 = device_name[strlen(device_name) - 1];
6021     char c2 = device_name[strlen(device_name) - 2];
6022
6023     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
6024       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
6025   }
6026   else
6027     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
6028             strlen(device_name));
6029 }
6030
6031 static void drawPlayerSetupInputInfo(int player_nr, boolean active)
6032 {
6033   int i;
6034   static struct SetupKeyboardInfo custom_key;
6035   static struct
6036   {
6037     Key *key;
6038     char *text;
6039   } custom[] =
6040   {
6041     { &custom_key.left,  "Axis/Pad Left"  },
6042     { &custom_key.right, "Axis/Pad Right" },
6043     { &custom_key.up,    "Axis/Pad Up"    },
6044     { &custom_key.down,  "Axis/Pad Down"  },
6045     { &custom_key.snap,  "Button 1/A/X"   },
6046     { &custom_key.drop,  "Button 2/B/Y"   }
6047   };
6048   static char *joystick_name[MAX_PLAYERS] =
6049   {
6050     "Joystick1",
6051     "Joystick2",
6052     "Joystick3",
6053     "Joystick4"
6054   };
6055   int text_font_nr = (active ? FONT_MENU_1_ACTIVE : FONT_MENU_1);
6056
6057   custom_key = setup.input[player_nr].key;
6058
6059   DrawText(mSX + 11 * 32, mSY + 2 * 32, int2str(player_nr + 1, 1),
6060            FONT_INPUT_1_ACTIVE);
6061
6062   ClearRectangleOnBackground(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
6063                              TILEX, TILEY);
6064   DrawFixedGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
6065                               PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
6066
6067   if (setup.input[player_nr].use_joystick)
6068   {
6069     char *device_name = setup.input[player_nr].joy.device_name;
6070     int joystick_nr = getJoystickNrFromDeviceName(device_name);
6071     boolean joystick_active = CheckJoystickOpened(joystick_nr);
6072     char *text = joystick_name[joystick_nr];
6073     int font_nr = (joystick_active ? FONT_VALUE_1 : FONT_VALUE_OLD);
6074
6075     DrawText(mSX + 8 * 32, mSY + 3 * 32, text, font_nr);
6076     DrawText(mSX + 32, mSY + 4 * 32, "Configure", text_font_nr);
6077   }
6078   else
6079   {
6080     DrawText(mSX + 8 * 32, mSY + 3 * 32, "Keyboard ", FONT_VALUE_1);
6081     DrawText(mSX + 1 * 32, mSY + 4 * 32, "Customize", text_font_nr);
6082   }
6083
6084   DrawText(mSX + 32, mSY + 5 * 32, "Actual Settings:", FONT_MENU_1);
6085
6086   drawCursorXY(1, 4, IMG_MENU_BUTTON_LEFT);
6087   drawCursorXY(1, 5, IMG_MENU_BUTTON_RIGHT);
6088   drawCursorXY(1, 6, IMG_MENU_BUTTON_UP);
6089   drawCursorXY(1, 7, IMG_MENU_BUTTON_DOWN);
6090
6091   DrawText(mSX + 2 * 32, mSY +  6 * 32, ":", FONT_VALUE_OLD);
6092   DrawText(mSX + 2 * 32, mSY +  7 * 32, ":", FONT_VALUE_OLD);
6093   DrawText(mSX + 2 * 32, mSY +  8 * 32, ":", FONT_VALUE_OLD);
6094   DrawText(mSX + 2 * 32, mSY +  9 * 32, ":", FONT_VALUE_OLD);
6095   DrawText(mSX + 1 * 32, mSY + 10 * 32, "Snap Field:", FONT_VALUE_OLD);
6096   DrawText(mSX + 1 * 32, mSY + 12 * 32, "Drop Element:", FONT_VALUE_OLD);
6097
6098   for (i = 0; i < 6; i++)
6099   {
6100     int ypos = 6 + i + (i > 3 ? i-3 : 0);
6101
6102     DrawText(mSX + 3 * 32, mSY + ypos * 32,
6103              "              ", FONT_VALUE_1);
6104     DrawText(mSX + 3 * 32, mSY + ypos * 32,
6105              (setup.input[player_nr].use_joystick ?
6106               custom[i].text :
6107               getKeyNameFromKey(*custom[i].key)), FONT_VALUE_1);
6108   }
6109 }
6110
6111 static int input_player_nr = 0;
6112
6113 void HandleSetupScreen_Input_Player(int step, int direction)
6114 {
6115   int old_player_nr = input_player_nr;
6116   int new_player_nr;
6117
6118   new_player_nr = old_player_nr + step * direction;
6119   if (new_player_nr < 0)
6120     new_player_nr = 0;
6121   if (new_player_nr > MAX_PLAYERS - 1)
6122     new_player_nr = MAX_PLAYERS - 1;
6123
6124   if (new_player_nr != old_player_nr)
6125   {
6126     input_player_nr = new_player_nr;
6127
6128     drawPlayerSetupInputInfo(input_player_nr, FALSE);
6129   }
6130 }
6131
6132 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
6133 {
6134   static int choice = 0;
6135   int x = 0;
6136   int y = choice;
6137   int pos_start  = SETUPINPUT_SCREEN_POS_START;
6138   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
6139   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
6140   int pos_end    = SETUPINPUT_SCREEN_POS_END;
6141
6142   if (button == MB_MENU_INITIALIZE)
6143   {
6144     drawPlayerSetupInputInfo(input_player_nr, (choice == 2));
6145
6146     DrawCursorAndText_Setup(choice, -1, TRUE);
6147
6148     return;
6149   }
6150   else if (button == MB_MENU_LEAVE)
6151   {
6152     setup_mode = SETUP_MODE_MAIN;
6153     DrawSetupScreen();
6154     InitJoysticks();
6155
6156     return;
6157   }
6158
6159   if (mx || my)         /* mouse input */
6160   {
6161     x = (mx - mSX) / 32;
6162     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
6163   }
6164   else if (dx || dy)    /* keyboard input */
6165   {
6166     if (dx && choice == 0)
6167       x = (dx < 0 ? 10 : 12);
6168     else if ((dx && choice == 1) ||
6169              (dx == -1 && choice == pos_end))
6170       button = MB_MENU_CHOICE;
6171     else if (dy)
6172       y = choice + dy;
6173
6174     if (y >= pos_empty1 && y <= pos_empty2)
6175       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
6176   }
6177
6178   if (y == 0 && dx != 0 && button)
6179   {
6180     HandleSetupScreen_Input_Player(1, dx < 0 ? -1 : +1);
6181   }
6182   else if (IN_VIS_FIELD(x, y) &&        // (does not use "IN_VIS_MENU()" yet)
6183            y >= pos_start && y <= pos_end &&
6184            !(y >= pos_empty1 && y <= pos_empty2))
6185   {
6186     if (button)
6187     {
6188       if (y != choice)
6189       {
6190         DrawCursorAndText_Setup(choice, -1, FALSE);
6191         DrawCursorAndText_Setup(y, -1, TRUE);
6192
6193         drawPlayerSetupInputInfo(input_player_nr, (y == 2));
6194
6195         choice = y;
6196       }
6197     }
6198     else
6199     {
6200       if (y == 1)
6201       {
6202         char *device_name = setup.input[input_player_nr].joy.device_name;
6203
6204         if (!setup.input[input_player_nr].use_joystick)
6205         {
6206           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
6207
6208           setJoystickDeviceToNr(device_name, new_device_nr);
6209           setup.input[input_player_nr].use_joystick = TRUE;
6210         }
6211         else
6212         {
6213           int device_nr = getJoystickNrFromDeviceName(device_name);
6214           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
6215
6216           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
6217             setup.input[input_player_nr].use_joystick = FALSE;
6218           else
6219             setJoystickDeviceToNr(device_name, new_device_nr);
6220         }
6221
6222         drawPlayerSetupInputInfo(input_player_nr, FALSE);
6223       }
6224       else if (y == 2)
6225       {
6226         if (setup.input[input_player_nr].use_joystick)
6227           ConfigureJoystick(input_player_nr);
6228         else
6229           CustomizeKeyboard(input_player_nr);
6230       }
6231       else if (y == pos_end)
6232       {
6233         InitJoysticks();
6234
6235         FadeSetLeaveMenu();
6236
6237         setup_mode = SETUP_MODE_MAIN;
6238         DrawSetupScreen();
6239       }
6240     }
6241   }
6242 }
6243
6244 void CustomizeKeyboard(int player_nr)
6245 {
6246   int i;
6247   int step_nr;
6248   boolean finished = FALSE;
6249   static struct SetupKeyboardInfo custom_key;
6250   static struct
6251   {
6252     Key *key;
6253     char *text;
6254   } customize_step[] =
6255   {
6256     { &custom_key.left,  "Move Left"    },
6257     { &custom_key.right, "Move Right"   },
6258     { &custom_key.up,    "Move Up"      },
6259     { &custom_key.down,  "Move Down"    },
6260     { &custom_key.snap,  "Snap Field"   },
6261     { &custom_key.drop,  "Drop Element" }
6262   };
6263
6264   /* read existing key bindings from player setup */
6265   custom_key = setup.input[player_nr].key;
6266
6267   FadeSetEnterMenu();
6268   FadeOut(REDRAW_FIELD);
6269
6270   ClearField();
6271
6272   DrawTextSCentered(mSY - SY + 16, FONT_TITLE_1, "Keyboard Input");
6273
6274   step_nr = 0;
6275   DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
6276            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
6277   DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
6278            "Key:", FONT_INPUT_1_ACTIVE);
6279   DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6280            getKeyNameFromKey(*customize_step[step_nr].key), FONT_VALUE_OLD);
6281
6282   FadeIn(REDRAW_FIELD);
6283
6284   while (!finished)
6285   {
6286     if (PendingEvent())         /* got event */
6287     {
6288       Event event;
6289
6290       NextEvent(&event);
6291
6292       switch (event.type)
6293       {
6294         case EVENT_KEYPRESS:
6295           {
6296             Key key = GetEventKey((KeyEvent *)&event, FALSE);
6297
6298             if (key == KSYM_Escape || (key == KSYM_Return && step_nr == 6))
6299             {
6300               if (key == KSYM_Escape)
6301                 FadeSkipNextFadeIn();
6302
6303               finished = TRUE;
6304               break;
6305             }
6306
6307             /* all keys configured -- wait for "Escape" or "Return" key */
6308             if (step_nr == 6)
6309               break;
6310
6311             /* press 'Enter' to keep the existing key binding */
6312             if (key == KSYM_Return)
6313               key = *customize_step[step_nr].key;
6314
6315             /* check if key already used */
6316             for (i = 0; i < step_nr; i++)
6317               if (*customize_step[i].key == key)
6318                 break;
6319             if (i < step_nr)
6320               break;
6321
6322             /* got new key binding */
6323             *customize_step[step_nr].key = key;
6324             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6325                      "             ", FONT_VALUE_1);
6326             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6327                      getKeyNameFromKey(key), FONT_VALUE_1);
6328             step_nr++;
6329
6330             /* un-highlight last query */
6331             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1)) * 32,
6332                      customize_step[step_nr - 1].text, FONT_MENU_1);
6333             DrawText(mSX, mSY + (2 + 2 * (step_nr - 1) + 1) * 32,
6334                      "Key:", FONT_MENU_1);
6335
6336             /* press 'Enter' to leave */
6337             if (step_nr == 6)
6338             {
6339               DrawText(mSX + 16, mSY + 15 * 32 + 16,
6340                        "Press Enter", FONT_TITLE_1);
6341               break;
6342             }
6343
6344             /* query next key binding */
6345             DrawText(mSX, mSY + (2 + 2 * step_nr) * 32,
6346                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
6347             DrawText(mSX, mSY + (2 + 2 * step_nr + 1) * 32,
6348                      "Key:", FONT_INPUT_1_ACTIVE);
6349             DrawText(mSX + 4 * 32, mSY + (2 + 2 * step_nr + 1) * 32,
6350                      getKeyNameFromKey(*customize_step[step_nr].key),
6351                      FONT_VALUE_OLD);
6352           }
6353           break;
6354
6355         case EVENT_KEYRELEASE:
6356           key_joystick_mapping = 0;
6357           break;
6358
6359         default:
6360           HandleOtherEvents(&event);
6361           break;
6362       }
6363     }
6364
6365     BackToFront();
6366   }
6367
6368   /* write new key bindings back to player setup */
6369   setup.input[player_nr].key = custom_key;
6370
6371   DrawSetupScreen_Input();
6372 }
6373
6374 /* game controller mapping generator by Gabriel Jacobo <gabomdq@gmail.com> */
6375
6376 #define MARKER_BUTTON           1
6377 #define MARKER_AXIS_X           2
6378 #define MARKER_AXIS_Y           3
6379
6380 static boolean ConfigureJoystickMapButtonsAndAxes(SDL_Joystick *joystick)
6381 {
6382 #if defined(TARGET_SDL2)
6383   static boolean bitmaps_initialized = FALSE;
6384   boolean screen_initialized = FALSE;
6385   static Bitmap *controller, *button, *axis_x, *axis_y;
6386   char *name;
6387   boolean success = TRUE;
6388   boolean done = FALSE, next = FALSE;
6389   Event event;
6390   int alpha = 200, alpha_step = -1;
6391   int alpha_ticks = 0;
6392   char mapping[4096], temp[4096];
6393   int font_name = FONT_TEXT_1;
6394   int font_info = FONT_REQUEST;
6395   int ystep1 = getFontHeight(font_name) + 2;
6396   int ystep2 = getFontHeight(font_info) + 2;
6397   int i, j;
6398
6399   struct
6400   {
6401     int x, y;
6402     int marker;
6403     char *field;
6404     int axis, button, hat, hat_value;
6405     char mapping[4096];
6406   }
6407   *step, *prev_step, steps[] =
6408   {
6409     { 356, 155, MARKER_BUTTON, "a",             },
6410     { 396, 122, MARKER_BUTTON, "b",             },
6411     { 320, 125, MARKER_BUTTON, "x",             },
6412     { 358,  95, MARKER_BUTTON, "y",             },
6413     { 162, 125, MARKER_BUTTON, "back",          },
6414     { 216, 125, MARKER_BUTTON, "guide",         },
6415     { 271, 125, MARKER_BUTTON, "start",         },
6416     { 110, 200, MARKER_BUTTON, "dpleft",        },
6417     { 146, 228, MARKER_BUTTON, "dpdown",        },
6418     { 178, 200, MARKER_BUTTON, "dpright",       },
6419     { 146, 172, MARKER_BUTTON, "dpup",          },
6420     {  50,  40, MARKER_BUTTON, "leftshoulder",  },
6421     {  88, -10, MARKER_AXIS_Y, "lefttrigger",   },
6422     { 382,  40, MARKER_BUTTON, "rightshoulder", },
6423     { 346, -10, MARKER_AXIS_Y, "righttrigger",  },
6424     {  73, 141, MARKER_BUTTON, "leftstick",     },
6425     { 282, 210, MARKER_BUTTON, "rightstick",    },
6426     {  73, 141, MARKER_AXIS_X, "leftx",         },
6427     {  73, 141, MARKER_AXIS_Y, "lefty",         },
6428     { 282, 210, MARKER_AXIS_X, "rightx",        },
6429     { 282, 210, MARKER_AXIS_Y, "righty",        },
6430   };
6431
6432   unsigned int event_frame_delay = 0;
6433   unsigned int event_frame_delay_value = GAME_FRAME_DELAY;
6434
6435   ResetDelayCounter(&event_frame_delay);
6436
6437   if (!bitmaps_initialized)
6438   {
6439     controller = LoadCustomImage("joystick/controller.png");
6440     button     = LoadCustomImage("joystick/button.png");
6441     axis_x     = LoadCustomImage("joystick/axis_x.png");
6442     axis_y     = LoadCustomImage("joystick/axis_y.png");
6443
6444     bitmaps_initialized = TRUE;
6445   }
6446
6447   name = getFormattedJoystickName(SDL_JoystickName(joystick));
6448
6449 #if DEBUG_JOYSTICKS
6450   /* print info about the joystick we are watching */
6451   Error(ERR_DEBUG, "watching joystick %d: (%s)\n",
6452         SDL_JoystickInstanceID(joystick), name);
6453   Error(ERR_DEBUG, "joystick has %d axes, %d hats, %d balls, and %d buttons\n",
6454         SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
6455         SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
6456 #endif
6457
6458   /* initialize mapping with GUID and name */
6459   SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, sizeof(temp));
6460
6461   snprintf(mapping, sizeof(mapping), "%s,%s,platform:%s,",
6462            temp, name, SDL_GetPlatform());
6463
6464   /* loop through all steps (buttons and axes), getting joystick events */
6465   for (i = 0; i < SDL_arraysize(steps) && !done;)
6466   {
6467     Bitmap *marker = button;    /* initialize with reliable default value */
6468
6469     step = &steps[i];
6470     strcpy(step->mapping, mapping);
6471     step->axis = -1;
6472     step->button = -1;
6473     step->hat = -1;
6474     step->hat_value = -1;
6475
6476     marker = (step->marker == MARKER_BUTTON ? button :
6477               step->marker == MARKER_AXIS_X ? axis_x :
6478               step->marker == MARKER_AXIS_Y ? axis_y : marker);
6479
6480     next = FALSE;
6481
6482     while (!done && !next)
6483     {
6484       alpha += alpha_step * (int)(SDL_GetTicks() - alpha_ticks) / 5;
6485       alpha_ticks = SDL_GetTicks();
6486
6487       if (alpha >= 255)
6488       {
6489         alpha = 255;
6490         alpha_step = -1;
6491       }
6492       else if (alpha < 128)
6493       {
6494         alpha = 127;
6495         alpha_step = 1;
6496       }
6497
6498       int controller_x = SX + (SXSIZE - controller->width) / 2;
6499       int controller_y = SY + ystep2;
6500
6501       int marker_x = controller_x + step->x;
6502       int marker_y = controller_y + step->y;
6503
6504       int ystart1 = mSY - 2 * SY + controller_y + controller->height;
6505       int ystart2 = ystart1 + ystep1 + ystep2;
6506
6507       ClearField();
6508
6509       DrawTextSCentered(ystart1, font_name, name);
6510
6511       DrawTextSCentered(ystart2 + 0 * ystep2, font_info,
6512                         "Press buttons and move axes on");
6513       DrawTextSCentered(ystart2 + 1 * ystep2, font_info,
6514                         "your controller when indicated.");
6515       DrawTextSCentered(ystart2 + 2 * ystep2, font_info,
6516                         "(Your controller may look different.)");
6517
6518 #if defined(PLATFORM_ANDROID)
6519       DrawTextSCentered(ystart2 + 4 * ystep2, font_info,
6520                         "To correct a mistake,");
6521       DrawTextSCentered(ystart2 + 5 * ystep2, font_info,
6522                         "press the 'back' button.");
6523       DrawTextSCentered(ystart2 + 6 * ystep2, font_info,
6524                         "To skip a button or axis,");
6525       DrawTextSCentered(ystart2 + 7 * ystep2, font_info,
6526                         "press the 'menu' button.");
6527 #else
6528       DrawTextSCentered(ystart2 + 4 * ystep2, font_info,
6529                         "To correct a mistake,");
6530       DrawTextSCentered(ystart2 + 5 * ystep2, font_info,
6531                         "press the 'backspace' key.");
6532       DrawTextSCentered(ystart2 + 6 * ystep2, font_info,
6533                         "To skip a button or axis,");
6534       DrawTextSCentered(ystart2 + 7 * ystep2, font_info,
6535                         "press the 'return' key.");
6536
6537       DrawTextSCentered(ystart2 + 8 * ystep2, font_info,
6538                         "To exit, press the 'escape' key.");
6539 #endif
6540
6541       BlitBitmapMasked(controller, drawto, 0, 0,
6542                        controller->width, controller->height,
6543                        controller_x, controller_y);
6544
6545       SDL_SetSurfaceAlphaMod(marker->surface_masked, alpha);
6546
6547       BlitBitmapMasked(marker, drawto, 0, 0,
6548                        marker->width, marker->height,
6549                        marker_x, marker_y);
6550
6551       if (!screen_initialized)
6552         FadeIn(REDRAW_FIELD);
6553       else
6554         BackToFront();
6555
6556       screen_initialized = TRUE;
6557
6558       while (NextValidEvent(&event))
6559       {
6560         switch (event.type)
6561         {
6562           case SDL_JOYAXISMOTION:
6563             if (event.jaxis.value > 20000 ||
6564                 event.jaxis.value < -20000)
6565             {
6566               for (j = 0; j < i; j++)
6567                 if (steps[j].axis == event.jaxis.axis)
6568                   break;
6569
6570               if (j == i)
6571               {
6572                 if (step->marker != MARKER_AXIS_X &&
6573                     step->marker != MARKER_AXIS_Y)
6574                   break;
6575
6576                 step->axis = event.jaxis.axis;
6577                 strcat(mapping, step->field);
6578                 snprintf(temp, sizeof(temp), ":a%u,", event.jaxis.axis);
6579                 strcat(mapping, temp);
6580                 i++;
6581                 next = TRUE;
6582               }
6583             }
6584
6585             break;
6586
6587           case SDL_JOYHATMOTION:
6588             /* ignore centering; we're probably just coming back
6589                to the center from the previous item we set */
6590             if (event.jhat.value == SDL_HAT_CENTERED)
6591               break;
6592
6593             for (j = 0; j < i; j++)
6594               if (steps[j].hat == event.jhat.hat &&
6595                   steps[j].hat_value == event.jhat.value)
6596                 break;
6597
6598             if (j == i)
6599             {
6600               step->hat = event.jhat.hat;
6601               step->hat_value = event.jhat.value;
6602               strcat(mapping, step->field);
6603               snprintf(temp, sizeof(temp), ":h%u.%u,",
6604                        event.jhat.hat, event.jhat.value );
6605               strcat(mapping, temp);
6606               i++;
6607               next = TRUE;
6608             }
6609
6610             break;
6611
6612           case SDL_JOYBALLMOTION:
6613             break;
6614
6615           case SDL_JOYBUTTONUP:
6616             for (j = 0; j < i; j++)
6617               if (steps[j].button == event.jbutton.button)
6618                 break;
6619
6620             if (j == i)
6621             {
6622               step->button = event.jbutton.button;
6623               strcat(mapping, step->field);
6624               snprintf(temp, sizeof(temp), ":b%u,", event.jbutton.button);
6625               strcat(mapping, temp);
6626               i++;
6627               next = TRUE;
6628             }
6629
6630             break;
6631
6632           case SDL_FINGERDOWN:
6633           case SDL_MOUSEBUTTONDOWN:
6634             /* skip this step */
6635             i++;
6636             next = TRUE;
6637
6638             break;
6639
6640           case SDL_KEYDOWN:
6641             if (event.key.keysym.sym == KSYM_BackSpace ||
6642                 event.key.keysym.sym == KSYM_Back)
6643             {
6644               if (i == 0)
6645               {
6646                 /* leave screen */
6647                 success = FALSE;
6648                 done = TRUE;
6649               }
6650
6651               /* undo this step */
6652               prev_step = &steps[i - 1];
6653               strcpy(mapping, prev_step->mapping);
6654               i--;
6655               next = TRUE;
6656
6657               break;
6658             }
6659
6660             if (event.key.keysym.sym == KSYM_space ||
6661                 event.key.keysym.sym == KSYM_Return ||
6662                 event.key.keysym.sym == KSYM_Menu)
6663             {
6664               /* skip this step */
6665               i++;
6666               next = TRUE;
6667
6668               break;
6669             }
6670
6671             if (event.key.keysym.sym == KSYM_Escape)
6672             {
6673               /* leave screen */
6674               success = FALSE;
6675               done = TRUE;
6676             }
6677
6678             break;
6679
6680           case SDL_QUIT:
6681             program.exit_function(0);
6682             break;
6683
6684           default:
6685             break;
6686         }
6687
6688         // do not handle events for longer than standard frame delay period
6689         if (DelayReached(&event_frame_delay, event_frame_delay_value))
6690           break;
6691       }
6692     }
6693   }
6694
6695   if (success)
6696   {
6697 #if DEBUG_JOYSTICKS
6698     Error(ERR_DEBUG, "New game controller mapping:\n\n%s\n\n", mapping);
6699 #endif
6700
6701     // activate mapping for this game
6702     SDL_GameControllerAddMapping(mapping);
6703
6704     // save mapping to personal mappings
6705     SaveSetup_AddGameControllerMapping(mapping);
6706   }
6707
6708   /* wait until the last pending event was removed from event queue */
6709   while (NextValidEvent(&event));
6710
6711   return success;
6712 #else
6713   return TRUE;
6714 #endif
6715 }
6716
6717 static int ConfigureJoystickMain(int player_nr)
6718 {
6719   char *device_name = setup.input[player_nr].joy.device_name;
6720   int joystick_nr = getJoystickNrFromDeviceName(device_name);
6721   boolean joystick_active = CheckJoystickOpened(joystick_nr);
6722   int success = FALSE;
6723   int i;
6724
6725   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
6726     return JOYSTICK_NOT_AVAILABLE;
6727
6728   if (!joystick_active || !setup.input[player_nr].use_joystick)
6729     return JOYSTICK_NOT_AVAILABLE;
6730
6731   FadeSetEnterMenu();
6732   FadeOut(REDRAW_FIELD);
6733
6734   // close all joystick devices (potentially opened as game controllers)
6735   for (i = 0; i < SDL_NumJoysticks(); i++)
6736     SDLCloseJoystick(i);
6737
6738   // open joystick device as plain joystick to configure as game controller
6739   SDL_Joystick *joystick = SDL_JoystickOpen(joystick_nr);
6740
6741   // as the joystick was successfully opened before, this should not happen
6742   if (joystick == NULL)
6743     return FALSE;
6744
6745   // create new game controller mapping (buttons and axes) for joystick device
6746   success = ConfigureJoystickMapButtonsAndAxes(joystick);
6747
6748   // close joystick (and maybe re-open as configured game controller later)
6749   SDL_JoystickClose(joystick);
6750
6751   // re-open all joystick devices (potentially as game controllers)
6752   for (i = 0; i < SDL_NumJoysticks(); i++)
6753     SDLOpenJoystick(i);
6754
6755   // clear all joystick input actions for all joystick devices
6756   SDLClearJoystickState();
6757
6758   return (success ? JOYSTICK_CONFIGURED : JOYSTICK_NOT_CONFIGURED);
6759 }
6760
6761 void ConfigureJoystick(int player_nr)
6762 {
6763   boolean state = ConfigureJoystickMain(player_nr);
6764
6765   if (state != JOYSTICK_NOT_CONFIGURED)
6766   {
6767     boolean success = (state == JOYSTICK_CONFIGURED);
6768     char *message = (success ? " IS CONFIGURED! " : " NOT AVAILABLE! ");
6769     char *device_name = setup.input[player_nr].joy.device_name;
6770     int nr = getJoystickNrFromDeviceName(device_name) + 1;
6771     int xpos = mSX - SX;
6772     int ypos = mSY - SY;
6773     unsigned int wait_frame_delay = 0;
6774     unsigned int wait_frame_delay_value = 2000;
6775
6776     ResetDelayCounter(&wait_frame_delay);
6777
6778     ClearField();
6779
6780     DrawTextF(xpos + 16, ypos + 6 * 32, FONT_TITLE_1, "   JOYSTICK %d   ", nr);
6781     DrawTextF(xpos + 16, ypos + 7 * 32, FONT_TITLE_1, message);
6782
6783     while (!DelayReached(&wait_frame_delay, wait_frame_delay_value))
6784       BackToFront();
6785
6786     ClearEventQueue();
6787   }
6788
6789   DrawSetupScreen_Input();
6790 }
6791
6792 void DrawSetupScreen()
6793 {
6794   if (setup_mode == SETUP_MODE_INPUT)
6795     DrawSetupScreen_Input();
6796   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
6797     DrawChooseTree(&game_speed_current);
6798   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
6799     DrawChooseTree(&scroll_delay_current);
6800   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
6801     DrawChooseTree(&snapshot_mode_current);
6802   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6803     DrawChooseTree(&window_size_current);
6804   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
6805     DrawChooseTree(&scaling_type_current);
6806   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
6807     DrawChooseTree(&rendering_mode_current);
6808   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
6809     DrawChooseTree(&artwork.gfx_current);
6810   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
6811     DrawChooseTree(&artwork.snd_current);
6812   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
6813     DrawChooseTree(&artwork.mus_current);
6814   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
6815     DrawChooseTree(&volume_simple_current);
6816   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
6817     DrawChooseTree(&volume_loops_current);
6818   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
6819     DrawChooseTree(&volume_music_current);
6820   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
6821     DrawChooseTree(&touch_control_current);
6822   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
6823     DrawChooseTree(&move_distance_current);
6824   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
6825     DrawChooseTree(&drop_distance_current);
6826   else
6827     DrawSetupScreen_Generic();
6828
6829   PlayMenuSoundsAndMusic();
6830 }
6831
6832 void RedrawSetupScreenAfterFullscreenToggle()
6833 {
6834   if (setup_mode == SETUP_MODE_GRAPHICS ||
6835       setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6836   {
6837     // update list selection from "setup.window_scaling_percent"
6838     execSetupGraphics_setWindowSizes(TRUE);
6839
6840     DrawSetupScreen();
6841   }
6842 }
6843
6844 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
6845 {
6846   if (setup_mode == SETUP_MODE_INPUT)
6847     HandleSetupScreen_Input(mx, my, dx, dy, button);
6848   else if (setup_mode == SETUP_MODE_CHOOSE_GAME_SPEED)
6849     HandleChooseTree(mx, my, dx, dy, button, &game_speed_current);
6850   else if (setup_mode == SETUP_MODE_CHOOSE_SCROLL_DELAY)
6851     HandleChooseTree(mx, my, dx, dy, button, &scroll_delay_current);
6852   else if (setup_mode == SETUP_MODE_CHOOSE_SNAPSHOT_MODE)
6853     HandleChooseTree(mx, my, dx, dy, button, &snapshot_mode_current);
6854   else if (setup_mode == SETUP_MODE_CHOOSE_WINDOW_SIZE)
6855     HandleChooseTree(mx, my, dx, dy, button, &window_size_current);
6856   else if (setup_mode == SETUP_MODE_CHOOSE_SCALING_TYPE)
6857     HandleChooseTree(mx, my, dx, dy, button, &scaling_type_current);
6858   else if (setup_mode == SETUP_MODE_CHOOSE_RENDERING)
6859     HandleChooseTree(mx, my, dx, dy, button, &rendering_mode_current);
6860   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
6861     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
6862   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
6863     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
6864   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
6865     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
6866   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_SIMPLE)
6867     HandleChooseTree(mx, my, dx, dy, button, &volume_simple_current);
6868   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_LOOPS)
6869     HandleChooseTree(mx, my, dx, dy, button, &volume_loops_current);
6870   else if (setup_mode == SETUP_MODE_CHOOSE_VOLUME_MUSIC)
6871     HandleChooseTree(mx, my, dx, dy, button, &volume_music_current);
6872   else if (setup_mode == SETUP_MODE_CHOOSE_TOUCH_CONTROL)
6873     HandleChooseTree(mx, my, dx, dy, button, &touch_control_current);
6874   else if (setup_mode == SETUP_MODE_CHOOSE_MOVE_DISTANCE)
6875     HandleChooseTree(mx, my, dx, dy, button, &move_distance_current);
6876   else if (setup_mode == SETUP_MODE_CHOOSE_DROP_DISTANCE)
6877     HandleChooseTree(mx, my, dx, dy, button, &drop_distance_current);
6878   else
6879     HandleSetupScreen_Generic(mx, my, dx, dy, button);
6880 }
6881
6882 void HandleGameActions()
6883 {
6884   if (game_status != GAME_MODE_PLAYING)
6885     return;
6886
6887   GameActions();        /* main game loop */
6888
6889   if (tape.auto_play && !tape.playing)
6890     AutoPlayTape();     /* continue automatically playing next tape */
6891 }
6892
6893
6894 /* ---------- new screen button stuff -------------------------------------- */
6895
6896 static void getScreenMenuButtonPos(int *x, int *y, int gadget_id)
6897 {
6898   switch (gadget_id)
6899   {
6900     case SCREEN_CTRL_ID_PREV_LEVEL:
6901       *x = mSX + GDI_ACTIVE_POS(menu.main.button.prev_level.x);
6902       *y = mSY + GDI_ACTIVE_POS(menu.main.button.prev_level.y);
6903       break;
6904
6905     case SCREEN_CTRL_ID_NEXT_LEVEL:
6906       *x = mSX + GDI_ACTIVE_POS(menu.main.button.next_level.x);
6907       *y = mSY + GDI_ACTIVE_POS(menu.main.button.next_level.y);
6908       break;
6909
6910     case SCREEN_CTRL_ID_PREV_PLAYER:
6911       *x = mSX + TILEX * 10;
6912       *y = mSY + TILEY * MENU_SCREEN_START_YPOS;
6913       break;
6914
6915     case SCREEN_CTRL_ID_NEXT_PLAYER:
6916       *x = mSX + TILEX * 12;
6917       *y = mSY + TILEY * MENU_SCREEN_START_YPOS;
6918       break;
6919
6920     default:
6921       Error(ERR_EXIT, "unknown gadget ID %d", gadget_id);
6922   }
6923 }
6924
6925 static struct
6926 {
6927   int gfx_unpressed, gfx_pressed;
6928   void (*get_gadget_position)(int *, int *, int);
6929   int gadget_id;
6930   int screen_mask;
6931   char *infotext;
6932 } menubutton_info[NUM_SCREEN_MENUBUTTONS] =
6933 {
6934   {
6935     IMG_MENU_BUTTON_PREV_LEVEL, IMG_MENU_BUTTON_PREV_LEVEL_ACTIVE,
6936     getScreenMenuButtonPos,
6937     SCREEN_CTRL_ID_PREV_LEVEL,
6938     SCREEN_MASK_MAIN,
6939     "last level"
6940   },
6941   {
6942     IMG_MENU_BUTTON_NEXT_LEVEL, IMG_MENU_BUTTON_NEXT_LEVEL_ACTIVE,
6943     getScreenMenuButtonPos,
6944     SCREEN_CTRL_ID_NEXT_LEVEL,
6945     SCREEN_MASK_MAIN,
6946     "next level"
6947   },
6948   {
6949     IMG_MENU_BUTTON_LEFT, IMG_MENU_BUTTON_LEFT_ACTIVE,
6950     getScreenMenuButtonPos,
6951     SCREEN_CTRL_ID_PREV_PLAYER,
6952     SCREEN_MASK_INPUT,
6953     "last player"
6954   },
6955   {
6956     IMG_MENU_BUTTON_RIGHT, IMG_MENU_BUTTON_RIGHT_ACTIVE,
6957     getScreenMenuButtonPos,
6958     SCREEN_CTRL_ID_NEXT_PLAYER,
6959     SCREEN_MASK_INPUT,
6960     "next player"
6961   },
6962 };
6963
6964 static struct
6965 {
6966   int gfx_unpressed, gfx_pressed;
6967   int x, y;
6968   int gadget_id;
6969   char *infotext;
6970 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
6971 {
6972   {
6973     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
6974     -1, -1,     /* these values are not constant, but can change at runtime */
6975     SCREEN_CTRL_ID_SCROLL_UP,
6976     "scroll up"
6977   },
6978   {
6979     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
6980     -1, -1,     /* these values are not constant, but can change at runtime */
6981     SCREEN_CTRL_ID_SCROLL_DOWN,
6982     "scroll down"
6983   }
6984 };
6985
6986 static struct
6987 {
6988   int gfx_unpressed, gfx_pressed;
6989   int x, y;
6990   int width, height;
6991   int type;
6992   int gadget_id;
6993   char *infotext;
6994 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
6995 {
6996   {
6997     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
6998     -1, -1,     /* these values are not constant, but can change at runtime */
6999     -1, -1,     /* these values are not constant, but can change at runtime */
7000     GD_TYPE_SCROLLBAR_VERTICAL,
7001     SCREEN_CTRL_ID_SCROLL_VERTICAL,
7002     "scroll level series vertically"
7003   }
7004 };
7005
7006 static void CreateScreenMenubuttons()
7007 {
7008   struct GadgetInfo *gi;
7009   unsigned int event_mask;
7010   int i;
7011
7012   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
7013   {
7014     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7015     int gfx_unpressed, gfx_pressed;
7016     int x, y, width, height;
7017     int gd_x1, gd_x2, gd_y1, gd_y2;
7018     int id = menubutton_info[i].gadget_id;
7019
7020     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
7021
7022     menubutton_info[i].get_gadget_position(&x, &y, id);
7023
7024     width = SC_MENUBUTTON_XSIZE;
7025     height = SC_MENUBUTTON_YSIZE;
7026
7027     gfx_unpressed = menubutton_info[i].gfx_unpressed;
7028     gfx_pressed   = menubutton_info[i].gfx_pressed;
7029     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7030     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7031     gd_x1 = graphic_info[gfx_unpressed].src_x;
7032     gd_y1 = graphic_info[gfx_unpressed].src_y;
7033     gd_x2 = graphic_info[gfx_pressed].src_x;
7034     gd_y2 = graphic_info[gfx_pressed].src_y;
7035
7036     gi = CreateGadget(GDI_CUSTOM_ID, id,
7037                       GDI_CUSTOM_TYPE_ID, i,
7038                       GDI_INFO_TEXT, menubutton_info[i].infotext,
7039                       GDI_X, x,
7040                       GDI_Y, y,
7041                       GDI_WIDTH, width,
7042                       GDI_HEIGHT, height,
7043                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
7044                       GDI_STATE, GD_BUTTON_UNPRESSED,
7045                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7046                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7047                       GDI_DIRECT_DRAW, FALSE,
7048                       GDI_EVENT_MASK, event_mask,
7049                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7050                       GDI_END);
7051
7052     if (gi == NULL)
7053       Error(ERR_EXIT, "cannot create gadget");
7054
7055     screen_gadget[id] = gi;
7056   }
7057 }
7058
7059 static void CreateScreenScrollbuttons()
7060 {
7061   struct GadgetInfo *gi;
7062   unsigned int event_mask;
7063   int i;
7064
7065   /* these values are not constant, but can change at runtime */
7066   scrollbutton_info[0].x = SC_SCROLL_UP_XPOS;
7067   scrollbutton_info[0].y = SC_SCROLL_UP_YPOS;
7068   scrollbutton_info[1].x = SC_SCROLL_DOWN_XPOS;
7069   scrollbutton_info[1].y = SC_SCROLL_DOWN_YPOS;
7070
7071   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
7072   {
7073     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7074     int gfx_unpressed, gfx_pressed;
7075     int x, y, width, height;
7076     int gd_x1, gd_x2, gd_y1, gd_y2;
7077     int id = scrollbutton_info[i].gadget_id;
7078
7079     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
7080
7081     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
7082     y = mSY + scrollbutton_info[i].y;
7083     width = SC_SCROLLBUTTON_XSIZE;
7084     height = SC_SCROLLBUTTON_YSIZE;
7085
7086     /* correct scrollbar position if placed outside menu (playfield) area */
7087     if (x > SX + SC_SCROLL_UP_XPOS)
7088       x = SX + SC_SCROLL_UP_XPOS;
7089
7090     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
7091       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
7092                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
7093
7094     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
7095     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
7096     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7097     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7098     gd_x1 = graphic_info[gfx_unpressed].src_x;
7099     gd_y1 = graphic_info[gfx_unpressed].src_y;
7100     gd_x2 = graphic_info[gfx_pressed].src_x;
7101     gd_y2 = graphic_info[gfx_pressed].src_y;
7102
7103     gi = CreateGadget(GDI_CUSTOM_ID, id,
7104                       GDI_CUSTOM_TYPE_ID, i,
7105                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
7106                       GDI_X, x,
7107                       GDI_Y, y,
7108                       GDI_WIDTH, width,
7109                       GDI_HEIGHT, height,
7110                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
7111                       GDI_STATE, GD_BUTTON_UNPRESSED,
7112                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7113                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7114                       GDI_DIRECT_DRAW, FALSE,
7115                       GDI_EVENT_MASK, event_mask,
7116                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7117                       GDI_END);
7118
7119     if (gi == NULL)
7120       Error(ERR_EXIT, "cannot create gadget");
7121
7122     screen_gadget[id] = gi;
7123   }
7124 }
7125
7126 static void CreateScreenScrollbars()
7127 {
7128   int i;
7129
7130   /* these values are not constant, but can change at runtime */
7131   scrollbar_info[0].x = SC_SCROLL_VERTICAL_XPOS;
7132   scrollbar_info[0].y = SC_SCROLL_VERTICAL_YPOS;
7133   scrollbar_info[0].width  = SC_SCROLL_VERTICAL_XSIZE;
7134   scrollbar_info[0].height = SC_SCROLL_VERTICAL_YSIZE;
7135
7136   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
7137   {
7138     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
7139     int gfx_unpressed, gfx_pressed;
7140     int x, y, width, height;
7141     int gd_x1, gd_x2, gd_y1, gd_y2;
7142     struct GadgetInfo *gi;
7143     int items_max, items_visible, item_position;
7144     unsigned int event_mask;
7145     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
7146     int id = scrollbar_info[i].gadget_id;
7147
7148     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
7149
7150     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
7151     y = mSY + scrollbar_info[i].y;
7152     width  = scrollbar_info[i].width;
7153     height = scrollbar_info[i].height;
7154
7155     /* correct scrollbar position if placed outside menu (playfield) area */
7156     if (x > SX + SC_SCROLL_VERTICAL_XPOS)
7157       x = SX + SC_SCROLL_VERTICAL_XPOS;
7158
7159     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
7160       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
7161
7162     items_max = num_page_entries;
7163     items_visible = num_page_entries;
7164     item_position = 0;
7165
7166     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
7167     gfx_pressed   = scrollbar_info[i].gfx_pressed;
7168     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
7169     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
7170     gd_x1 = graphic_info[gfx_unpressed].src_x;
7171     gd_y1 = graphic_info[gfx_unpressed].src_y;
7172     gd_x2 = graphic_info[gfx_pressed].src_x;
7173     gd_y2 = graphic_info[gfx_pressed].src_y;
7174
7175     gi = CreateGadget(GDI_CUSTOM_ID, id,
7176                       GDI_CUSTOM_TYPE_ID, i,
7177                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
7178                       GDI_X, x,
7179                       GDI_Y, y,
7180                       GDI_WIDTH, width,
7181                       GDI_HEIGHT, height,
7182                       GDI_TYPE, scrollbar_info[i].type,
7183                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
7184                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
7185                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
7186                       GDI_WHEEL_AREA_X, SX,
7187                       GDI_WHEEL_AREA_Y, SY,
7188                       GDI_WHEEL_AREA_WIDTH, SXSIZE,
7189                       GDI_WHEEL_AREA_HEIGHT, SYSIZE,
7190                       GDI_STATE, GD_BUTTON_UNPRESSED,
7191                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
7192                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
7193                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
7194                       GDI_DIRECT_DRAW, FALSE,
7195                       GDI_EVENT_MASK, event_mask,
7196                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
7197                       GDI_END);
7198
7199     if (gi == NULL)
7200       Error(ERR_EXIT, "cannot create gadget");
7201
7202     screen_gadget[id] = gi;
7203   }
7204 }
7205
7206 void CreateScreenGadgets()
7207 {
7208   CreateScreenMenubuttons();
7209
7210   CreateScreenScrollbuttons();
7211   CreateScreenScrollbars();
7212 }
7213
7214 void FreeScreenGadgets()
7215 {
7216   int i;
7217
7218   for (i = 0; i < NUM_SCREEN_GADGETS; i++)
7219     FreeGadget(screen_gadget[i]);
7220 }
7221
7222 void MapScreenMenuGadgets(int screen_mask)
7223 {
7224   int i;
7225
7226   for (i = 0; i < NUM_SCREEN_MENUBUTTONS; i++)
7227     if (screen_mask & menubutton_info[i].screen_mask)
7228       MapGadget(screen_gadget[menubutton_info[i].gadget_id]);
7229 }
7230
7231 void MapScreenGadgets(int num_entries)
7232 {
7233   int i;
7234
7235   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
7236     return;
7237
7238   for (i = 0; i < NUM_SCREEN_SCROLLBUTTONS; i++)
7239     MapGadget(screen_gadget[scrollbutton_info[i].gadget_id]);
7240
7241   for (i = 0; i < NUM_SCREEN_SCROLLBARS; i++)
7242     MapGadget(screen_gadget[scrollbar_info[i].gadget_id]);
7243 }
7244
7245 void MapScreenTreeGadgets(TreeInfo *ti)
7246 {
7247   MapScreenGadgets(numTreeInfoInGroup(ti));
7248 }
7249
7250 static void HandleScreenGadgets(struct GadgetInfo *gi)
7251 {
7252   int id = gi->custom_id;
7253   int button = gi->event.button;
7254   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
7255
7256   switch (id)
7257   {
7258     case SCREEN_CTRL_ID_PREV_LEVEL:
7259       HandleMainMenu_SelectLevel(step, -1, NO_DIRECT_LEVEL_SELECT);
7260       break;
7261
7262     case SCREEN_CTRL_ID_NEXT_LEVEL:
7263       HandleMainMenu_SelectLevel(step, +1, NO_DIRECT_LEVEL_SELECT);
7264       break;
7265
7266     case SCREEN_CTRL_ID_PREV_PLAYER:
7267       HandleSetupScreen_Input_Player(step, -1);
7268       break;
7269
7270     case SCREEN_CTRL_ID_NEXT_PLAYER:
7271       HandleSetupScreen_Input_Player(step, +1);
7272       break;
7273
7274     case SCREEN_CTRL_ID_SCROLL_UP:
7275       if (game_status == GAME_MODE_LEVELS)
7276         HandleChooseLevelSet(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7277       else if (game_status == GAME_MODE_LEVELNR)
7278         HandleChooseLevelNr(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7279       else if (game_status == GAME_MODE_SETUP)
7280         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7281       else if (game_status == GAME_MODE_INFO)
7282         HandleInfoScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
7283       break;
7284
7285     case SCREEN_CTRL_ID_SCROLL_DOWN:
7286       if (game_status == GAME_MODE_LEVELS)
7287         HandleChooseLevelSet(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7288       else if (game_status == GAME_MODE_LEVELNR)
7289         HandleChooseLevelNr(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7290       else if (game_status == GAME_MODE_SETUP)
7291         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7292       else if (game_status == GAME_MODE_INFO)
7293         HandleInfoScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
7294       break;
7295
7296     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
7297       if (game_status == GAME_MODE_LEVELS)
7298         HandleChooseLevelSet(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
7299       else if (game_status == GAME_MODE_LEVELNR)
7300         HandleChooseLevelNr(0,0,999,gi->event.item_position,MB_MENU_INITIALIZE);
7301       else if (game_status == GAME_MODE_SETUP)
7302         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
7303       else if (game_status == GAME_MODE_INFO)
7304         HandleInfoScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
7305       break;
7306
7307     default:
7308       break;
7309   }
7310 }