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