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