e47e922b58225dfecc853c235af9df667b40acbc
[rocksndiamonds.git] / src / screens.c
1 /***********************************************************
2 * Rocks'n'Diamonds -- McDuffin Strikes Back!               *
3 *----------------------------------------------------------*
4 * (c) 1995-2002 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * screens.c                                                *
12 ***********************************************************/
13
14 #include "libgame/libgame.h"
15
16 #include "screens.h"
17 #include "events.h"
18 #include "game.h"
19 #include "tools.h"
20 #include "editor.h"
21 #include "files.h"
22 #include "tape.h"
23 #include "cartoons.h"
24 #include "network.h"
25 #include "init.h"
26
27 /* screens in the setup menu */
28 #define SETUP_MODE_MAIN                 0
29 #define SETUP_MODE_GAME                 1
30 #define SETUP_MODE_EDITOR               2
31 #define SETUP_MODE_INPUT                3
32 #define SETUP_MODE_SHORTCUT             4
33 #define SETUP_MODE_GRAPHICS             5
34 #define SETUP_MODE_SOUND                6
35 #define SETUP_MODE_ARTWORK              7
36 #define SETUP_MODE_CHOOSE_GRAPHICS      8
37 #define SETUP_MODE_CHOOSE_SOUNDS        9
38 #define SETUP_MODE_CHOOSE_MUSIC         10
39
40 #define MAX_SETUP_MODES                 11
41
42 /* for input setup functions */
43 #define SETUPINPUT_SCREEN_POS_START     0
44 #define SETUPINPUT_SCREEN_POS_END       (SCR_FIELDY - 4)
45 #define SETUPINPUT_SCREEN_POS_EMPTY1    (SETUPINPUT_SCREEN_POS_START + 3)
46 #define SETUPINPUT_SCREEN_POS_EMPTY2    (SETUPINPUT_SCREEN_POS_END - 1)
47
48 /* for various menu stuff  */
49 #define MAX_MENU_ENTRIES_ON_SCREEN      (SCR_FIELDY - 2)
50 #define MENU_SCREEN_START_YPOS          2
51 #define MENU_SCREEN_VALUE_XPOS          14
52
53 /* buttons and scrollbars identifiers */
54 #define SCREEN_CTRL_ID_SCROLL_UP        0
55 #define SCREEN_CTRL_ID_SCROLL_DOWN      1
56 #define SCREEN_CTRL_ID_SCROLL_VERTICAL  2
57
58 #define NUM_SCREEN_SCROLLBUTTONS        2
59 #define NUM_SCREEN_SCROLLBARS           1
60 #define NUM_SCREEN_GADGETS              3
61
62 /* forward declarations of internal functions */
63 static void HandleScreenGadgets(struct GadgetInfo *);
64 static void HandleSetupScreen_Generic(int, int, int, int, int);
65 static void HandleSetupScreen_Input(int, int, int, int, int);
66 static void CustomizeKeyboard(int);
67 static void CalibrateJoystick(int);
68 static void execSetupArtwork(void);
69 static void HandleChooseTree(int, int, int, int, int, TreeInfo **);
70
71 static struct GadgetInfo *screen_gadget[NUM_SCREEN_GADGETS];
72 static int setup_mode = SETUP_MODE_MAIN;
73
74 #define mSX (SX + (game_status >= GAME_MODE_MAIN &&     \
75                    game_status <= GAME_MODE_SETUP ?     \
76                    menu.draw_xoffset[game_status] : menu.draw_xoffset_default))
77 #define mSY (SY + (game_status >= GAME_MODE_MAIN &&     \
78                    game_status <= GAME_MODE_SETUP ?     \
79                    menu.draw_yoffset[game_status] : menu.draw_yoffset_default))
80
81 #define NUM_MENU_ENTRIES_ON_SCREEN (menu.list_size[game_status] > 2 ?   \
82                                     menu.list_size[game_status] :       \
83                                     MAX_MENU_ENTRIES_ON_SCREEN)
84
85 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
86 #define NUM_SCROLLBAR_BITMAPS           2
87 static Bitmap *scrollbar_bitmap[NUM_SCROLLBAR_BITMAPS];
88 #endif
89
90
91 static void drawCursorExt(int xpos, int ypos, int color, int graphic)
92 {
93   static int cursor_array[SCR_FIELDY];
94
95   if (xpos == 0)
96   {
97     if (graphic != 0)
98       cursor_array[ypos] = graphic;
99     else
100       graphic = cursor_array[ypos];
101   }
102
103   if (color == FC_RED)
104     graphic = (graphic == IMG_MENU_BUTTON_LEFT  ? IMG_MENU_BUTTON_LEFT_ACTIVE :
105                graphic == IMG_MENU_BUTTON_RIGHT ? IMG_MENU_BUTTON_RIGHT_ACTIVE:
106                IMG_MENU_BUTTON_ACTIVE);
107
108   ypos += MENU_SCREEN_START_YPOS;
109
110   DrawBackground(mSX + xpos * TILEX, mSY + ypos * TILEY, TILEX, TILEY);
111   DrawGraphicThruMaskExt(drawto, mSX + xpos * TILEX, mSY + ypos * TILEY,
112                          graphic, 0);
113 }
114
115 static void initCursor(int ypos, int graphic)
116 {
117   drawCursorExt(0, ypos, FC_BLUE, graphic);
118 }
119
120 static void drawCursor(int ypos, int color)
121 {
122   drawCursorExt(0, ypos, color, 0);
123 }
124
125 static void drawCursorXY(int xpos, int ypos, int graphic)
126 {
127   drawCursorExt(xpos, ypos, -1, graphic);
128 }
129
130 static void drawChooseTreeCursor(int ypos, int color)
131 {
132   int last_game_status = game_status;   /* save current game status */
133
134   /* force LEVELS draw offset on artwork setup screen */
135   game_status = GAME_MODE_LEVELS;
136
137   drawCursorExt(0, ypos, color, 0);
138
139   game_status = last_game_status;       /* restore current game status */
140 }
141
142 static void PlayMenuSound()
143 {
144   int sound = menu.sound[game_status];
145
146   if (sound == SND_UNDEFINED)
147     return;
148
149   if (sound_info[sound].loop)
150     PlaySoundLoop(sound);
151   else
152     PlaySound(sound);
153 }
154
155 static void PlayMenuSoundIfLoop()
156 {
157   int sound = menu.sound[game_status];
158
159   if (sound == SND_UNDEFINED)
160     return;
161
162   if (sound_info[sound].loop)
163     PlaySoundLoop(sound);
164 }
165
166 static void PlayMenuMusic()
167 {
168   int music = menu.music[game_status];
169
170   if (music == MUS_UNDEFINED)
171     return;
172
173   PlayMusic(music);
174 }
175
176 void DrawHeadline()
177 {
178   int text1_width = getTextWidth(PROGRAM_TITLE_STRING,     FONT_TITLE_1);
179   int text2_width = getTextWidth(PROGRAM_COPYRIGHT_STRING, FONT_TITLE_2);
180   int x1 = SX + (SXSIZE - text1_width) / 2;
181   int x2 = SX + (SXSIZE - text2_width) / 2;
182
183   DrawText(x1, SY + 8,  PROGRAM_TITLE_STRING,     FONT_TITLE_1);
184   DrawText(x2, SY + 46, PROGRAM_COPYRIGHT_STRING, FONT_TITLE_2);
185 }
186
187 static void ToggleFullscreenIfNeeded()
188 {
189   if (setup.fullscreen != video.fullscreen_enabled)
190   {
191     /* save old door content */
192     BlitBitmap(backbuffer, bitmap_db_door,
193                DX, DY, DXSIZE, DYSIZE, DOOR_GFX_PAGEX1, DOOR_GFX_PAGEY1);
194
195     /* toggle fullscreen */
196     ChangeVideoModeIfNeeded(setup.fullscreen);
197     setup.fullscreen = video.fullscreen_enabled;
198
199     /* redraw background to newly created backbuffer */
200     BlitBitmap(graphic_info[IMG_GLOBAL_BORDER].bitmap, backbuffer,
201                0,0, WIN_XSIZE,WIN_YSIZE, 0,0);
202
203     /* restore old door content */
204     BlitBitmap(bitmap_db_door, backbuffer,
205                DOOR_GFX_PAGEX1, DOOR_GFX_PAGEY1, DXSIZE, DYSIZE, DX, DY);
206
207     redraw_mask = REDRAW_ALL;
208   }
209 }
210
211 void DrawMainMenu()
212 {
213   static LevelDirTree *leveldir_last_valid = NULL;
214   char *name_text = (!options.network && setup.team_mode ? "Team:" : "Name:");
215   int name_width  = getTextWidth("Name:",  FONT_MENU_1);
216   int level_width = getTextWidth("Level:", FONT_MENU_1);
217   int i;
218
219   UnmapAllGadgets();
220   FadeSoundsAndMusic();
221
222   KeyboardAutoRepeatOn();
223   ActivateJoystick();
224
225   SetDrawDeactivationMask(REDRAW_NONE);
226   SetDrawBackgroundMask(REDRAW_FIELD);
227
228   audio.sound_deactivated = FALSE;
229
230   /* needed if last screen was the playing screen, invoked from level editor */
231   if (level_editor_test_game)
232   {
233     game_status = GAME_MODE_EDITOR;
234     DrawLevelEd();
235
236     return;
237   }
238
239   /* needed if last screen was the editor screen */
240   UndrawSpecialEditorDoor();
241
242   /* needed if last screen was the setup screen and fullscreen state changed */
243   ToggleFullscreenIfNeeded();
244
245   /* leveldir_current may be invalid (level group, parent link) */
246   if (!validLevelSeries(leveldir_current))
247     leveldir_current = getFirstValidTreeInfoEntry(leveldir_last_valid);
248
249   /* store valid level series information */
250   leveldir_last_valid = leveldir_current;
251
252   /* needed if last screen (level choice) changed graphics, sounds or music */
253   ReloadCustomArtwork();
254
255 #ifdef TARGET_SDL
256   SetDrawtoField(DRAW_BACKBUFFER);
257 #endif
258
259   /* map gadgets for main menu screen */
260   MapTapeButtons();
261
262   /* level_nr may have been set to value over handicap with level editor */
263   if (setup.handicap && level_nr > leveldir_current->handicap_level)
264     level_nr = leveldir_current->handicap_level;
265
266   GetPlayerConfig();
267   LoadLevel(level_nr);
268
269   SetMainBackgroundImage(IMG_BACKGROUND_MAIN);
270   ClearWindow();
271
272   DrawHeadline();
273
274   DrawText(mSX + 32, mSY + 2*32, name_text, FONT_MENU_1);
275   DrawText(mSX + 32, mSY + 3*32, "Level:", FONT_MENU_1);
276   DrawText(mSX + 32, mSY + 4*32, "Hall Of Fame", FONT_MENU_1);
277   DrawText(mSX + 32, mSY + 5*32, "Level Creator", FONT_MENU_1);
278   DrawText(mSX + 32, mSY + 6*32, "Info Screen", FONT_MENU_1);
279   DrawText(mSX + 32, mSY + 7*32, "Start Game", FONT_MENU_1);
280   DrawText(mSX + 32, mSY + 8*32, "Setup", FONT_MENU_1);
281   DrawText(mSX + 32, mSY + 9*32, "Quit", FONT_MENU_1);
282
283   DrawText(mSX + 32 + name_width, mSY + 2*32, setup.player_name, FONT_INPUT_1);
284   DrawText(mSX + level_width + 5 * 32, mSY + 3*32, int2str(level_nr,3),
285            FONT_VALUE_1);
286
287   DrawMicroLevel(MICROLEV_XPOS, MICROLEV_YPOS, TRUE);
288
289   DrawTextF(mSX + 32 + level_width - 2, mSY + 3*32 + 1, FONT_TEXT_3, "%d-%d",
290             leveldir_current->first_level, leveldir_current->last_level);
291
292   if (leveldir_current->readonly)
293   {
294     DrawTextS(mSX + level_width + 9 * 32 - 2,
295               mSY + 3 * 32 + 1 - 7, FONT_TEXT_3, "READ");
296     DrawTextS(mSX + level_width + 9 * 32 - 2,
297               mSY + 3 * 32 + 1 + 7, FONT_TEXT_3, "ONLY");
298   }
299
300   for(i=0; i<8; i++)
301     initCursor(i, (i == 1 || i == 6 ? IMG_MENU_BUTTON_RIGHT :IMG_MENU_BUTTON));
302
303   drawCursorXY(level_width/32 + 4, 1, IMG_MENU_BUTTON_LEFT);
304   drawCursorXY(level_width/32 + 8, 1, IMG_MENU_BUTTON_RIGHT);
305
306   DrawText(SX + 56, SY + 326, "A Game by Artsoft Entertainment", FONT_TITLE_2);
307
308   FadeToFront();
309   InitAnimation();
310   HandleMainMenu(0,0, 0,0, MB_MENU_INITIALIZE);
311
312   TapeStop();
313   if (TAPE_IS_EMPTY(tape))
314     LoadTape(level_nr);
315   DrawCompleteVideoDisplay();
316
317   PlayMenuSound();
318   PlayMenuMusic();
319
320   OpenDoor(DOOR_CLOSE_1 | DOOR_OPEN_2);
321
322 #if 0
323   ClearEventQueue();
324 #endif
325 }
326
327 static void gotoTopLevelDir()
328 {
329   /* move upwards to top level directory */
330   while (leveldir_current->node_parent)
331   {
332     /* write a "path" into level tree for easy navigation to last level */
333     if (leveldir_current->node_parent->node_group->cl_first == -1)
334     {
335       int num_leveldirs = numTreeInfoInGroup(leveldir_current);
336       int leveldir_pos = posTreeInfo(leveldir_current);
337       int num_page_entries;
338       int cl_first, cl_cursor;
339
340       if (num_leveldirs <= NUM_MENU_ENTRIES_ON_SCREEN)
341         num_page_entries = num_leveldirs;
342       else
343         num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
344
345       cl_first = MAX(0, leveldir_pos - num_page_entries + 1);
346       cl_cursor = leveldir_pos - cl_first;
347
348       leveldir_current->node_parent->node_group->cl_first = cl_first;
349       leveldir_current->node_parent->node_group->cl_cursor = cl_cursor;
350     }
351
352     leveldir_current = leveldir_current->node_parent;
353   }
354 }
355
356 void HandleMainMenu(int mx, int my, int dx, int dy, int button)
357 {
358   static int choice = 5;
359   int x = 0;
360   int y = choice;
361
362   if (button == MB_MENU_INITIALIZE)
363   {
364     drawCursor(choice, FC_RED);
365     return;
366   }
367
368   if (mx || my)         /* mouse input */
369   {
370     x = (mx - mSX) / 32;
371     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
372   }
373   else if (dx || dy)    /* keyboard input */
374   {
375     if (dx && choice == 1)
376       x = (dx < 0 ? 10 : 14);
377     else if (dy)
378       y = choice + dy;
379   }
380
381   if (y == 1 && ((x == 10 && level_nr > leveldir_current->first_level) ||
382                  (x == 14 && level_nr < leveldir_current->last_level)) &&
383       button)
384   {
385     static unsigned long level_delay = 0;
386     int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
387     int new_level_nr, old_level_nr = level_nr;
388
389     new_level_nr = level_nr + (x == 10 ? -step : +step);
390     if (new_level_nr < leveldir_current->first_level)
391       new_level_nr = leveldir_current->first_level;
392     if (new_level_nr > leveldir_current->last_level)
393       new_level_nr = leveldir_current->last_level;
394
395     if (setup.handicap && new_level_nr > leveldir_current->handicap_level)
396       new_level_nr = leveldir_current->handicap_level;
397
398     if (old_level_nr == new_level_nr ||
399         !DelayReached(&level_delay, GADGET_FRAME_DELAY))
400       goto out;
401
402     level_nr = new_level_nr;
403
404     DrawText(mSX + 11 * 32, mSY + 3 * 32, int2str(level_nr, 3), FONT_VALUE_1);
405
406     LoadLevel(level_nr);
407     DrawMicroLevel(MICROLEV_XPOS, MICROLEV_YPOS, TRUE);
408
409     TapeErase();
410     LoadTape(level_nr);
411     DrawCompleteVideoDisplay();
412
413     /* needed because DrawMicroLevel() takes some time */
414     BackToFront();
415     SyncDisplay();
416     DelayReached(&level_delay, 0);      /* reset delay counter */
417   }
418   else if (x == 0 && y >= 0 && y <= 7)
419   {
420     if (button)
421     {
422       if (y != choice)
423       {
424         drawCursor(y, FC_RED);
425         drawCursor(choice, FC_BLUE);
426         choice = y;
427       }
428     }
429     else
430     {
431       if (y == 0)
432       {
433         game_status = GAME_MODE_PSEUDO_TYPENAME;
434         HandleTypeName(strlen(setup.player_name), 0);
435       }
436       else if (y == 1)
437       {
438         if (leveldir_first)
439         {
440           game_status = GAME_MODE_LEVELS;
441           SaveLevelSetup_LastSeries();
442           SaveLevelSetup_SeriesInfo();
443
444           gotoTopLevelDir();
445
446           DrawChooseLevel();
447         }
448       }
449       else if (y == 2)
450       {
451         game_status = GAME_MODE_SCORES;
452         DrawHallOfFame(-1);
453       }
454       else if (y == 3)
455       {
456         if (leveldir_current->readonly &&
457             strcmp(setup.player_name, "Artsoft") != 0)
458           Request("This level is read only !", REQ_CONFIRM);
459         game_status = GAME_MODE_EDITOR;
460         DrawLevelEd();
461       }
462       else if (y == 4)
463       {
464         game_status = GAME_MODE_INFO;
465         DrawHelpScreen();
466       }
467       else if (y == 5)
468       {
469         if (setup.autorecord)
470           TapeStartRecording();
471
472 #if defined(PLATFORM_UNIX)
473         if (options.network)
474           SendToServer_StartPlaying();
475         else
476 #endif
477         {
478           game_status = GAME_MODE_PLAYING;
479           StopAnimation();
480           InitGame();
481         }
482       }
483       else if (y == 6)
484       {
485         game_status = GAME_MODE_SETUP;
486         setup_mode = SETUP_MODE_MAIN;
487         DrawSetupScreen();
488       }
489       else if (y == 7)
490       {
491         SaveLevelSetup_LastSeries();
492         SaveLevelSetup_SeriesInfo();
493         if (Request("Do you really want to quit ?", REQ_ASK | REQ_STAY_CLOSED))
494           game_status = GAME_MODE_QUIT;
495       }
496     }
497   }
498
499   out:
500
501   if (game_status == GAME_MODE_MAIN)
502   {
503     DrawMicroLevel(MICROLEV_XPOS, MICROLEV_YPOS, FALSE);
504     DoAnimation();
505   }
506
507   BackToFront();
508 }
509
510
511 #define MAX_HELPSCREEN_ELS      10
512 #define HA_NEXT                 -999
513 #define HA_END                  -1000
514
515 static long helpscreen_state;
516 static int helpscreen_step[MAX_HELPSCREEN_ELS];
517 static int helpscreen_frame[MAX_HELPSCREEN_ELS];
518
519 #if 0
520 static int helpscreen_action[] =
521 {
522   IMG_PLAYER_1_MOVING_DOWN,             16,
523   IMG_PLAYER_1_MOVING_UP,               16,
524   IMG_PLAYER_1_MOVING_LEFT,             16,
525   IMG_PLAYER_1_MOVING_RIGHT,            16,
526   IMG_PLAYER_1_PUSHING_LEFT,            16,
527   IMG_PLAYER_1_PUSHING_RIGHT,           16,                     HA_NEXT,
528
529   IMG_SAND,                             -1,                     HA_NEXT,
530
531   IMG_EMPTY_SPACE,                      -1,                     HA_NEXT,
532
533   IMG_QUICKSAND_EMPTY,                  -1,                     HA_NEXT,
534
535   IMG_STEELWALL,                        -1,                     HA_NEXT,
536
537   IMG_WALL,                             -1,                     HA_NEXT,
538
539   IMG_EXPANDABLE_WALL_GROWING_LEFT,     20,
540   IMG_WALL,                             50,
541   IMG_EMPTY_SPACE,                      20,
542   IMG_EXPANDABLE_WALL_GROWING_RIGHT,    20,
543   IMG_WALL,                             50,
544   IMG_EMPTY_SPACE,                      20,
545   IMG_EXPANDABLE_WALL_GROWING_UP,       20,
546   IMG_WALL,                             50,
547   IMG_EMPTY_SPACE,                      20,
548   IMG_EXPANDABLE_WALL_GROWING_DOWN,     20,
549   IMG_WALL,                             50,
550   IMG_EMPTY_SPACE,                      20,                     HA_NEXT,
551
552   IMG_INVISIBLE_WALL,                   -1,                     HA_NEXT,
553
554   IMG_WALL_SLIPPERY,                    -1,                     HA_NEXT,
555
556   IMG_FONT_GAME_INFO,                   -1,                     HA_NEXT,
557
558   IMG_EMERALD,                          -1,                     HA_NEXT,
559
560   IMG_DIAMOND,                          -1,                     HA_NEXT,
561
562   IMG_BD_DIAMOND,                       -1,                     HA_NEXT,
563
564   IMG_EMERALD_YELLOW,                   50,
565   IMG_EMERALD_RED,                      50,
566   IMG_EMERALD_PURPLE,                   50,                     HA_NEXT,
567
568   IMG_BD_ROCK,                          -1,                     HA_NEXT,
569
570   IMG_BOMB,                             100,
571   IMG_EXPLOSION,                        16,
572   IMG_EMPTY_SPACE,                      10,                     HA_NEXT,
573
574   IMG_NUT,                              100,
575   IMG_NUT_BREAKING,                     6,
576   IMG_EMERALD,                          20,                     HA_NEXT,
577
578   IMG_WALL_EMERALD,                     100,
579   IMG_EXPLOSION,                        16,
580   IMG_EMERALD,                          20,                     HA_NEXT,
581
582   IMG_WALL_DIAMOND,                     100,
583   IMG_EXPLOSION,                        16,
584   IMG_DIAMOND,                          20,                     HA_NEXT,
585
586   IMG_WALL_BD_DIAMOND,                  100,
587   IMG_EXPLOSION,                        16,
588   IMG_BD_DIAMOND,                       20,                     HA_NEXT,
589
590   IMG_WALL_EMERALD_YELLOW,              100,
591   IMG_EXPLOSION,                        16,
592   IMG_EMERALD_YELLOW,                   20,
593   IMG_WALL_EMERALD_RED,                 100,
594   IMG_EXPLOSION,                        16,
595   IMG_EMERALD_RED,                      20,
596   IMG_WALL_EMERALD_PURPLE,              100,
597   IMG_EXPLOSION,                        16,
598   IMG_EMERALD_PURPLE,                   20,                     HA_NEXT,
599
600   IMG_ACID,                             -1,                     HA_NEXT,
601
602   IMG_KEY_1,                            50,
603   IMG_KEY_2,                            50,
604   IMG_KEY_3,                            50,
605   IMG_KEY_4,                            50,                     HA_NEXT,
606
607   IMG_GATE_1,                           50,
608   IMG_GATE_2,                           50,
609   IMG_GATE_3,                           50,
610   IMG_GATE_4,                           50,                     HA_NEXT,
611
612   IMG_GATE_1_GRAY,                      50,
613   IMG_GATE_2_GRAY,                      50,
614   IMG_GATE_3_GRAY,                      50,
615   IMG_GATE_4_GRAY,                      50,                     HA_NEXT,
616
617   IMG_DYNAMITE,                         -1,                     HA_NEXT,
618
619   IMG_DYNAMITE_ACTIVE,                  96,
620   IMG_EXPLOSION,                        16,
621   IMG_EMPTY_SPACE,                      20,                     HA_NEXT,
622
623   IMG_DYNABOMB_ACTIVE,                  100,
624   IMG_EXPLOSION,                        16,
625   IMG_EMPTY_SPACE,                      20,                     HA_NEXT,
626
627   IMG_DYNABOMB_INCREASE_NUMBER,         -1,                     HA_NEXT,
628
629   IMG_DYNABOMB_INCREASE_SIZE,           -1,                     HA_NEXT,
630
631   IMG_DYNABOMB_INCREASE_POWER,          -1,                     HA_NEXT,
632
633   IMG_SPACESHIP_RIGHT,                  16,
634   IMG_SPACESHIP_UP,                     16,
635   IMG_SPACESHIP_LEFT,                   16,
636   IMG_SPACESHIP_DOWN,                   16,                     HA_NEXT,
637
638   IMG_BUG_RIGHT,                        16,
639   IMG_BUG_UP,                           16,
640   IMG_BUG_LEFT,                         16,
641   IMG_BUG_DOWN,                         16,                     HA_NEXT,
642
643   IMG_BD_BUTTERFLY,                     -1,                     HA_NEXT,
644
645   IMG_BD_FIREFLY,                       -1,                     HA_NEXT,
646
647   IMG_PACMAN_RIGHT,                     16,
648   IMG_PACMAN_UP,                        16,
649   IMG_PACMAN_LEFT,                      16,
650   IMG_PACMAN_DOWN,                      16,                     HA_NEXT,
651
652   IMG_YAMYAM,                           -1,                     HA_NEXT,
653
654   IMG_DARK_YAMYAM,                      -1,                     HA_NEXT,
655
656   IMG_ROBOT,                            -1,                     HA_NEXT,
657
658   IMG_MOLE_MOVING_RIGHT,                16,
659   IMG_MOLE_MOVING_UP,                   16,
660   IMG_MOLE_MOVING_LEFT,                 16,
661   IMG_MOLE_MOVING_DOWN,                 16,                     HA_NEXT,
662
663   IMG_PENGUIN_MOVING_RIGHT,             16,
664   IMG_PENGUIN_MOVING_UP,                16,
665   IMG_PENGUIN_MOVING_LEFT,              16,
666   IMG_PENGUIN_MOVING_DOWN,              16,                     HA_NEXT,
667
668   IMG_PIG_MOVING_RIGHT,                 16,
669   IMG_PIG_MOVING_UP,                    16,
670   IMG_PIG_MOVING_LEFT,                  16,
671   IMG_PIG_MOVING_DOWN,                  16,                     HA_NEXT,
672
673   IMG_DRAGON_MOVING_RIGHT,              16,
674   IMG_DRAGON_MOVING_UP,                 16,
675   IMG_DRAGON_MOVING_LEFT,               16,
676   IMG_DRAGON_MOVING_DOWN,               16,                     HA_NEXT,
677
678   IMG_SATELLITE,                        -1,                     HA_NEXT,
679
680   IMG_ROBOT_WHEEL,                      50,
681   IMG_ROBOT_WHEEL_ACTIVE,               100,                    HA_NEXT,
682
683   IMG_LAMP,                             50,
684   IMG_LAMP_ACTIVE,                      50,                     HA_NEXT,
685
686   IMG_TIME_ORB_FULL,                    50,
687   IMG_TIME_ORB_EMPTY,                   50,                     HA_NEXT,
688
689   IMG_AMOEBA_DROP,                      50,
690   IMG_AMOEBA_GROWING,                   6,
691   IMG_AMOEBA_WET,                       20,                     HA_NEXT,
692
693   IMG_AMOEBA_DEAD,                      -1,                     HA_NEXT,
694
695   IMG_AMOEBA_WET,                       -1,                     HA_NEXT,
696
697   IMG_AMOEBA_WET,                       100,
698   IMG_AMOEBA_GROWING,                   6,                      HA_NEXT,
699
700   IMG_AMOEBA_FULL,                      50,
701   IMG_AMOEBA_DEAD,                      50,
702   IMG_EXPLOSION,                        16,
703   IMG_DIAMOND,                          20,                     HA_NEXT,
704
705   IMG_GAME_OF_LIFE,                     -1,                     HA_NEXT,
706
707   IMG_BIOMAZE,                          -1,                     HA_NEXT,
708
709   IMG_MAGIC_WALL_ACTIVE,                -1,                     HA_NEXT,
710
711   IMG_BD_MAGIC_WALL_ACTIVE,             -1,                     HA_NEXT,
712
713   IMG_EXIT_CLOSED,                      200,
714   IMG_EXIT_OPENING,                     16,
715   IMG_EXIT_OPEN,                        100,                    HA_NEXT,
716
717   IMG_EXIT_OPEN,                        -1,                     HA_NEXT,
718
719   IMG_SOKOBAN_OBJECT,                   -1,                     HA_NEXT,
720
721   IMG_SOKOBAN_FIELD_EMPTY,              -1,                     HA_NEXT,
722
723   IMG_SOKOBAN_FIELD_FULL,               -1,                     HA_NEXT,
724
725   IMG_SPEED_PILL,                       -1,                     HA_NEXT,
726
727   HA_END
728 };
729 #endif
730
731 static char *helpscreen_eltext[][2] =
732 {
733  {"THE HERO:",                          "(Is _this_ guy good old Rockford?)"},
734  {"Normal sand:",                       "You can dig through it"},
735  {"Empty field:",                       "You can walk through it"},
736  {"Quicksand: You cannot pass it,",     "but rocks can fall through it"},
737  {"Massive Wall:",                      "Nothing can go through it"},
738  {"Normal Wall: You can't go through",  "it, but you can bomb it away"},
739  {"Growing Wall: Grows in several di-", "rections if there is an empty field"},
740  {"Invisible Wall: Behaves like normal","wall, but is invisible"},
741  {"Old Wall: Like normal wall, but",    "some things can fall down from it"},
742  {"Letter Wall: Looks like a letter,",  "behaves like a normal wall"},
743  {"Emerald: You must collect enough of","them to finish a level"},
744  {"Diamond: Counts as 3 emeralds, but", "can be destroyed by rocks"},
745  {"Diamond (BD style): Counts like one","emerald and behaves a bit different"},
746  {"Colorful Gems:",                     "Seem to behave like Emeralds"},
747  {"Rock: Smashes several things;",      "Can be moved by the player"},
748  {"Bomb: You can move it, but be",      "careful when dropping it"},
749  {"Nut: Throw a rock on it to open it;","Each nut contains an emerald"},
750  {"Wall with an emerald inside:",       "Bomb the wall away to get it"},
751  {"Wall with a diamond inside:",        "Bomb the wall away to get it"},
752  {"Wall with BD style diamond inside:", "Bomb the wall away to get it"},
753  {"Wall with colorful gem inside:",     "Bomb the wall away to get it"},
754  {"Acid: Things that fall in are gone", "forever (including our hero)"},
755  {"Key: Opens the door that has the",   "same color (red/yellow/green/blue)"},
756  {"Door: Can be opened by the key",     "with the same color"},
757  {"Door: You have to find out the",     "right color of the key for it"},
758  {"Dynamite: Collect it and use it to", "destroy walls or kill enemies"},
759  {"Dynamite: This one explodes after",  "a few seconds"},
760  {"Dyna Bomb: Explodes in 4 directions","with variable explosion size"},
761  {"Dyna Bomb: Increases the number of", "dyna bombs available at a time"},
762  {"Dyna Bomb: Increases the size of",   "explosion of dyna bombs"},
763  {"Dyna Bomb: Increases the power of",  "explosion of dyna bombs"},
764  {"Spaceship: Moves at the left side",  "of walls; don't touch it!"},
765  {"Bug: Moves at the right side",       "of walls; don't touch it!"},
766  {"Butterfly: Moves at the right side", "of walls; don't touch it!"},
767  {"Firefly: Moves at the left side",    "of walls; don't touch it!"},
768  {"Pacman: Eats the amoeba and you,",   "if you're not careful"},
769  {"Cruncher: Eats diamonds and you,",   "if you're not careful"},
770  {"Cruncher (BD style):",               "Eats almost everything"},
771  {"Robot: Tries to kill the player",    ""},
772  {"The mole: Eats the amoeba and turns","empty space into normal sand"},
773  {"The penguin: Guide him to the exit,","but keep him away from monsters!"},
774  {"The Pig: Harmless, but eats all",    "gems it can get"},
775  {"The Dragon: Breathes fire,",         "especially to some monsters"},
776  {"Sonde: Follows you everywhere;",     "harmless, but may block your way"},
777  {"Magic Wheel: Touch it to get rid of","the robots for some seconds"},
778  {"Light Bulb: All of them must be",    "switched on to finish a level"},
779  {"Extra Time Orb: Adds some seconds",  "to the time available for the level"},
780  {"Amoeba Drop: Grows to an amoeba on", "the ground - don't touch it"},
781  {"Dead Amoeba: Does not grow, but",    "can still kill bugs and spaceships"},
782  {"Normal Amoeba: Grows through empty", "fields, sand and quicksand"},
783  {"Dropping Amoeba: This one makes",    "drops that grow to a new amoeba"},
784  {"Living Amoeba (BD style): Contains", "other element, when surrounded"},
785  {"Game Of Life: Behaves like the well","known 'Game Of Life' (2333 style)"},
786  {"Biomaze: A bit like the 'Game Of",   "Life', but builds crazy mazes"},
787  {"Magic Wall: Changes rocks, emeralds","and diamonds when they pass it"},
788  {"Magic Wall (BD style):",             "Changes rocks and BD style diamonds"},
789  {"Exit door: Opens if you have enough","emeralds to finish the level"},
790  {"Open exit door: Enter here to leave","the level and exit the actual game"},
791  {"Sokoban element: Object which must", "be pushed to an empty field"},
792  {"Sokoban element: Empty field where", "a Sokoban object can be placed on"},
793  {"Sokoban element: Field with object", "which can be pushed away"},
794  {"Speed pill: Lets the player run",    "twice as fast as normally"},
795 };
796 static int num_helpscreen_els = sizeof(helpscreen_eltext) / (2*sizeof(char *));
797
798 #if 0
799 static char *helpscreen_music[][3] =
800 {
801   { "Alchemy",                  "Ian Boddy",            "Drive" },
802   { "The Chase",                "Propaganda",           "A Secret Wish" },
803   { "Network 23",               "Tangerine Dream",      "Exit" },
804   { "Czardasz",                 "Robert Pieculewicz",   "Czardasz" },
805   { "21st Century Common Man",  "Tangerine Dream",      "Tyger" },
806   { "Voyager",                  "The Alan Parsons Project","Pyramid" },
807   { "Twilight Painter",         "Tangerine Dream",      "Heartbreakers" }
808 };
809 #endif
810
811 static int num_helpscreen_music = 7;
812 static int helpscreen_musicpos;
813
814 #if 1
815 void DrawHelpScreenElAction(int start, boolean init)
816 {
817   int i = 0, j = 0;
818   int xstart = mSX + 16;
819   int ystart = mSY + 64 + 2 * 32;
820   int ystep = TILEY + 4;
821   int element, action, direction;
822   int graphic;
823   int delay;
824   int sync_frame;
825
826   if (init)
827   {
828     SetMainBackgroundImage(IMG_BACKGROUND_INFO);
829     ClearWindow();
830     DrawHeadline();
831
832     DrawTextSCentered(100, FONT_TEXT_1, "The game elements:");
833
834     DrawTextSCentered(SYSIZE - 20, FONT_TEXT_4,
835                       "Press any key or button for next page");
836   }
837
838   while (demo_anim_info[j].element != -999)
839   {
840     if (i >= start + MAX_HELPSCREEN_ELS || i >= num_helpscreen_els)
841       break;
842     else if (i < start)
843     {
844       while (demo_anim_info[j].element != -1)
845         j++;
846
847       j++;
848       i++;
849
850       continue;
851     }
852
853     j += helpscreen_step[i - start];
854
855     element = demo_anim_info[j].element;
856     action = demo_anim_info[j].action;
857     direction = demo_anim_info[j].direction;
858
859     if (action != -1 && direction != -1)
860       graphic = el_act_dir2img(element, action, direction);
861     else if (action != -1)
862       graphic = el_act2img(element, action);
863     else if (direction != -1)
864       graphic = el_act2img(element, direction);
865     else
866       graphic = el2img(element);
867
868     delay = demo_anim_info[j++].delay;
869
870     if (delay == -1)
871       delay = 1000000;
872
873     if (helpscreen_frame[i - start] == 0)
874     {
875       sync_frame = 0;
876       helpscreen_frame[i - start] = delay - 1;
877     }
878     else
879     {
880       sync_frame = delay - helpscreen_frame[i - start];
881       helpscreen_frame[i - start]--;
882     }
883
884     if (demo_anim_info[j].element == -1)
885     {
886       if (!helpscreen_frame[i - start])
887         helpscreen_step[i - start] = 0;
888     }
889     else
890     {
891       if (!helpscreen_frame[i - start])
892         helpscreen_step[i - start]++;
893       while(demo_anim_info[j].element != -1)
894         j++;
895     }
896
897     j++;
898
899     ClearRectangleOnBackground(drawto, xstart, ystart + (i - start) * ystep,
900                                TILEX, TILEY);
901     DrawGraphicAnimationExt(drawto, xstart, ystart + (i - start) * ystep,
902                             graphic, sync_frame, USE_MASKING);
903
904     if (init)
905       DrawHelpScreenElText(element, action, direction, i - start);
906
907     i++;
908   }
909
910   redraw_mask |= REDRAW_FIELD;
911
912   FrameCounter++;
913 }
914
915 #else
916
917 void DrawHelpScreenElAction(int start)
918 {
919   int i = 0, j = 0;
920   int xstart = mSX + 16;
921   int ystart = mSY + 64 + 2 * 32;
922   int ystep = TILEY + 4;
923   int graphic;
924   int frame_count;
925   int sync_frame;
926
927   while (helpscreen_action[j] != HA_END)
928   {
929     if (i >= start + MAX_HELPSCREEN_ELS || i >= num_helpscreen_els)
930       break;
931     else if (i < start)
932     {
933       while (helpscreen_action[j] != HA_NEXT)
934         j++;
935
936       j++;
937       i++;
938
939       continue;
940     }
941
942     j += 2 * helpscreen_step[i-start];
943     graphic = helpscreen_action[j++];
944     frame_count = helpscreen_action[j++];
945     if (frame_count == -1)
946       frame_count = 1000000;
947
948     if (helpscreen_frame[i-start] == 0)
949     {
950       sync_frame = 0;
951       helpscreen_frame[i-start] = frame_count - 1;
952     }
953     else
954     {
955       sync_frame = frame_count - helpscreen_frame[i-start];
956       helpscreen_frame[i-start]--;
957     }
958
959     if (helpscreen_action[j] == HA_NEXT)
960     {
961       if (!helpscreen_frame[i-start])
962         helpscreen_step[i-start] = 0;
963     }
964     else
965     {
966       if (!helpscreen_frame[i-start])
967         helpscreen_step[i-start]++;
968       while(helpscreen_action[j] != HA_NEXT)
969         j++;
970     }
971     j++;
972
973 #if 1
974     ClearRectangleOnBackground(drawto, xstart, ystart + (i - start) * ystep,
975                                TILEX, TILEY);
976     DrawGraphicAnimationExt(drawto, xstart, ystart + (i - start) * ystep,
977                             graphic, sync_frame, USE_MASKING);
978 #else
979     frame = getGraphicAnimationFrame(graphic, sync_frame);
980
981     DrawGraphicExt(drawto, xstart, ystart + (i-start) * ystep,
982                    graphic, frame);
983 #endif
984
985     i++;
986   }
987
988 #if 1
989   redraw_mask |= REDRAW_FIELD;
990 #else
991   for(i=2; i<16; i++)
992   {
993     MarkTileDirty(0, i);
994     MarkTileDirty(1, i);
995   }
996 #endif
997
998   FrameCounter++;
999 }
1000 #endif
1001
1002 #if 1
1003 void DrawHelpScreenElText(int element, int action, int direction, int ypos)
1004 {
1005   int xstart = mSX + 56;
1006   int ystart = mSY + 65 + 2 * 32;
1007   int ystep = TILEY + 4;
1008   char *text;
1009
1010   text = getListEntry(demo_anim_text, element_info[element].token_name);
1011   if (text == NULL)
1012   {
1013     char token[MAX_LINE_LEN];
1014
1015     strcpy(token, element_info[element].token_name);
1016
1017     if (action != -1)
1018       strcat(token, element_action_info[action].suffix);
1019
1020     if (direction != -1)
1021       strcat(token, element_direction_info[MV_DIR_BIT(direction)].suffix);
1022
1023     text = getListEntry(demo_anim_text, token);
1024
1025     if (text == NULL)
1026       text = "[Oops! No Text found!]";
1027   }
1028
1029 #if 1
1030   DrawTextToTextArea(xstart, ystart + ypos * ystep, text, FONT_TEXT_2, 34,
1031                      34, 2, BLIT_ON_BACKGROUND);
1032 #else
1033   if (strlen(text) > 25)
1034     text[25] = '\0';
1035
1036   DrawText(xstart, ystart + ypos * ystep + 8, text, FONT_TEXT_2);
1037 #endif
1038 }
1039
1040 #else
1041
1042 void DrawHelpScreenElText(int start)
1043 {
1044   int i;
1045   int xstart = mSX + 56, ystart = mSY + 65 + 2 * 32, ystep = TILEY + 4;
1046   int ybottom = SYSIZE - 20;
1047
1048   SetMainBackgroundImage(IMG_BACKGROUND_INFO);
1049   ClearWindow();
1050   DrawHeadline();
1051
1052   DrawTextSCentered(100, FONT_TEXT_1, "The game elements:");
1053
1054   for(i=start; i < start + MAX_HELPSCREEN_ELS && i < num_helpscreen_els; i++)
1055   {
1056     DrawText(xstart,
1057              ystart + (i - start) * ystep + (*helpscreen_eltext[i][1] ? 0 : 8),
1058              helpscreen_eltext[i][0], FONT_TEXT_2);
1059     DrawText(xstart, ystart + (i - start) * ystep + 16,
1060              helpscreen_eltext[i][1], FONT_TEXT_2);
1061   }
1062
1063   DrawTextSCentered(ybottom, FONT_TEXT_4,
1064                     "Press any key or button for next page");
1065 }
1066 #endif
1067
1068 void DrawHelpScreenMusicText(int num)
1069 {
1070   struct MusicFileInfo *list = music_file_info;
1071   int ystart = 150, ystep = 30;
1072   int ybottom = SYSIZE - 20;
1073   int i;
1074
1075   for (i=0; i < num && list; i++)
1076     list = list->next;
1077
1078   FadeSoundsAndMusic();
1079   ClearWindow();
1080   DrawHeadline();
1081
1082   DrawTextSCentered(100, FONT_TEXT_1, "The game background music loops:");
1083
1084 #if 1
1085   DrawTextSCentered(ystart + 0 * ystep, FONT_TEXT_2, "Excerpt from");
1086   DrawTextFCentered(ystart + 1 * ystep, FONT_TEXT_3, "\"%s\"", list->title);
1087   DrawTextSCentered(ystart + 2 * ystep, FONT_TEXT_2, "by");
1088   DrawTextFCentered(ystart + 3 * ystep, FONT_TEXT_3, "%s", list->artist);
1089   DrawTextSCentered(ystart + 4 * ystep, FONT_TEXT_2, "from the album");
1090   DrawTextFCentered(ystart + 5 * ystep, FONT_TEXT_3, "\"%s\"", list->album);
1091 #else
1092   DrawTextSCentered(ystart + 0 * ystep, FONT_TEXT_2, "Excerpt from");
1093   DrawTextFCentered(ystart + 1 * ystep, FONT_TEXT_3,
1094                     "\"%s\"", helpscreen_music[num][0]);
1095   DrawTextSCentered(ystart + 2 * ystep, FONT_TEXT_2, "by");
1096   DrawTextFCentered(ystart + 3 * ystep, FONT_TEXT_3,
1097                     "%s", helpscreen_music[num][1]);
1098   DrawTextSCentered(ystart + 4 * ystep, FONT_TEXT_2, "from the album");
1099   DrawTextFCentered(ystart + 5 * ystep, FONT_TEXT_3,
1100                     "\"%s\"", helpscreen_music[num][2]);
1101 #endif
1102
1103   DrawTextSCentered(ybottom, FONT_TEXT_4,
1104                     "Press any key or button for next page");
1105
1106 #if 0
1107   PlaySoundLoop(background_loop[num]);
1108 #endif
1109 }
1110
1111 void DrawHelpScreenCreditsText()
1112 {
1113   int ystart = 150, ystep = 30;
1114   int ybottom = SYSIZE - 20;
1115
1116   FadeSoundsAndMusic();
1117   ClearWindow();
1118   DrawHeadline();
1119
1120   DrawTextSCentered(100, FONT_TEXT_1, "Credits:");
1121   DrawTextSCentered(ystart + 0 * ystep, FONT_TEXT_2, "DOS port of the game:");
1122   DrawTextSCentered(ystart + 1 * ystep, FONT_TEXT_3, "Guido Schulz");
1123   DrawTextSCentered(ystart + 2 * ystep, FONT_TEXT_2, "Additional toons:");
1124   DrawTextSCentered(ystart + 3 * ystep, FONT_TEXT_3, "Karl Hörnell");
1125   DrawTextSCentered(ystart + 5 * ystep, FONT_TEXT_2,
1126                     "...and many thanks to all contributors");
1127   DrawTextSCentered(ystart + 6 * ystep, FONT_TEXT_2, "of new levels!");
1128
1129   DrawTextSCentered(ybottom, FONT_TEXT_4,
1130                     "Press any key or button for next page");
1131 }
1132
1133 void DrawHelpScreenContactText()
1134 {
1135   int ystart = 150, ystep = 30;
1136   int ybottom = SYSIZE - 20;
1137
1138   ClearWindow();
1139   DrawHeadline();
1140
1141   DrawTextSCentered(100, FONT_TEXT_1, "Program information:");
1142
1143   DrawTextSCentered(ystart + 0 * ystep, FONT_TEXT_2,
1144                     "This game is Freeware!");
1145   DrawTextSCentered(ystart + 1 * ystep, FONT_TEXT_2,
1146                     "If you like it, send e-mail to:");
1147   DrawTextSCentered(ystart + 2 * ystep, FONT_TEXT_3,
1148                     "info@artsoft.org");
1149   DrawTextSCentered(ystart + 3 * ystep, FONT_TEXT_2,
1150                     "or SnailMail to:");
1151   DrawTextSCentered(ystart + 4 * ystep + 0, FONT_TEXT_3,
1152                     "Holger Schemel");
1153   DrawTextSCentered(ystart + 4 * ystep + 20, FONT_TEXT_3,
1154                     "Detmolder Strasse 189");
1155   DrawTextSCentered(ystart + 4 * ystep + 40, FONT_TEXT_3,
1156                     "33604 Bielefeld");
1157   DrawTextSCentered(ystart + 4 * ystep + 60, FONT_TEXT_3,
1158                     "Germany");
1159
1160   DrawTextSCentered(ystart + 7 * ystep, FONT_TEXT_2,
1161                     "If you have created new levels,");
1162   DrawTextSCentered(ystart + 8 * ystep, FONT_TEXT_2,
1163                     "send them to me to include them!");
1164   DrawTextSCentered(ystart + 9 * ystep, FONT_TEXT_2,
1165                     ":-)");
1166
1167   DrawTextSCentered(ybottom, FONT_TEXT_4,
1168                     "Press any key or button for main menu");
1169 }
1170
1171 void DrawHelpScreen()
1172 {
1173   struct MusicFileInfo *list;
1174   int i;
1175
1176   UnmapAllGadgets();
1177   CloseDoor(DOOR_CLOSE_2);
1178
1179   for(i=0;i<MAX_HELPSCREEN_ELS;i++)
1180     helpscreen_step[i] = helpscreen_frame[i] = 0;
1181   helpscreen_musicpos = 0;
1182   helpscreen_state = 0;
1183
1184   LoadDemoAnimInfo();
1185   LoadDemoAnimText();
1186   LoadMusicInfo();
1187
1188   num_helpscreen_els = 0;
1189   for (i=0; demo_anim_info[i].element != -999; i++)
1190     if (demo_anim_info[i].element == -1)
1191       num_helpscreen_els++;
1192
1193   num_helpscreen_music = 0;
1194   for (list = music_file_info; list != NULL; list = list->next)
1195     num_helpscreen_music++;
1196
1197   DrawHelpScreenElAction(0, TRUE);
1198 #if 0
1199   DrawHelpScreenElText(0);
1200 #endif
1201
1202   FadeToFront();
1203   InitAnimation();
1204
1205   PlayMenuSound();
1206   PlayMenuMusic();
1207 }
1208
1209 void HandleHelpScreen(int button)
1210 {
1211   static unsigned long hs_delay = 0;
1212   int num_helpscreen_els_pages =
1213     (num_helpscreen_els + MAX_HELPSCREEN_ELS-1) / MAX_HELPSCREEN_ELS;
1214   int button_released = !button;
1215   int i;
1216
1217   if (button_released)
1218   {
1219     if (helpscreen_state < num_helpscreen_els_pages - 1)
1220     {
1221       for(i=0;i<MAX_HELPSCREEN_ELS;i++)
1222         helpscreen_step[i] = helpscreen_frame[i] = 0;
1223       helpscreen_state++;
1224
1225       FrameCounter = 0;
1226       DrawHelpScreenElAction(helpscreen_state * MAX_HELPSCREEN_ELS, TRUE);
1227 #if 0
1228       DrawHelpScreenElText(helpscreen_state * MAX_HELPSCREEN_ELS);
1229 #endif
1230     }
1231     else if (helpscreen_state <
1232              num_helpscreen_els_pages + num_helpscreen_music - 1)
1233     {
1234       helpscreen_state++;
1235       DrawHelpScreenMusicText(helpscreen_state - num_helpscreen_els_pages);
1236     }
1237     else if (helpscreen_state ==
1238              num_helpscreen_els_pages + num_helpscreen_music - 1)
1239     {
1240       helpscreen_state++;
1241       DrawHelpScreenCreditsText();
1242     }
1243     else if (helpscreen_state ==
1244              num_helpscreen_els_pages + num_helpscreen_music)
1245     {
1246       helpscreen_state++;
1247       DrawHelpScreenContactText();
1248     }
1249     else
1250     {
1251       FadeSoundsAndMusic();
1252
1253       game_status = GAME_MODE_MAIN;
1254       DrawMainMenu();
1255     }
1256   }
1257   else
1258   {
1259     if (DelayReached(&hs_delay, GAME_FRAME_DELAY))
1260     {
1261       if (helpscreen_state < num_helpscreen_els_pages)
1262         DrawHelpScreenElAction(helpscreen_state * MAX_HELPSCREEN_ELS, FALSE);
1263     }
1264
1265     PlayMenuSoundIfLoop();
1266   }
1267
1268   DoAnimation();
1269   BackToFront();
1270 }
1271
1272 void HandleTypeName(int newxpos, Key key)
1273 {
1274   static int xpos = 0, ypos = 2;
1275   int font_width = getFontWidth(FONT_INPUT_1_ACTIVE);
1276   int name_width = getFontWidth(FONT_MENU_1) * strlen("Name:");
1277   int startx = mSX + 32 + name_width;
1278   int starty = mSY + ypos * 32;
1279
1280   if (newxpos)
1281   {
1282     xpos = newxpos;
1283
1284     DrawText(startx, starty, setup.player_name, FONT_INPUT_1_ACTIVE);
1285     DrawText(startx + xpos * font_width, starty, "_", FONT_INPUT_1_ACTIVE);
1286
1287     return;
1288   }
1289
1290   if (((key >= KSYM_A && key <= KSYM_Z) ||
1291        (key >= KSYM_a && key <= KSYM_z)) && 
1292       xpos < MAX_PLAYER_NAME_LEN)
1293   {
1294     char ascii;
1295
1296     if (key >= KSYM_A && key <= KSYM_Z)
1297       ascii = 'A' + (char)(key - KSYM_A);
1298     else
1299       ascii = 'a' + (char)(key - KSYM_a);
1300
1301     setup.player_name[xpos] = ascii;
1302     setup.player_name[xpos + 1] = 0;
1303     xpos++;
1304
1305     DrawText(startx, starty, setup.player_name, FONT_INPUT_1_ACTIVE);
1306     DrawText(startx + xpos * font_width, starty, "_", FONT_INPUT_1_ACTIVE);
1307   }
1308   else if ((key == KSYM_Delete || key == KSYM_BackSpace) && xpos > 0)
1309   {
1310     xpos--;
1311     setup.player_name[xpos] = 0;
1312
1313     DrawText(startx + xpos * font_width, starty, "_ ", FONT_INPUT_1_ACTIVE);
1314   }
1315   else if (key == KSYM_Return && xpos > 0)
1316   {
1317     DrawText(startx, starty, setup.player_name, FONT_INPUT_1);
1318     DrawText(startx + xpos * font_width, starty, " ", FONT_INPUT_1_ACTIVE);
1319
1320     SaveSetup();
1321     game_status = GAME_MODE_MAIN;
1322   }
1323
1324   BackToFront();
1325 }
1326
1327 static void DrawChooseTree(TreeInfo **ti_ptr)
1328 {
1329   UnmapAllGadgets();
1330
1331   FreeScreenGadgets();
1332   CreateScreenGadgets();
1333
1334   CloseDoor(DOOR_CLOSE_2);
1335
1336   ClearWindow();
1337
1338   HandleChooseTree(0,0, 0,0, MB_MENU_INITIALIZE, ti_ptr);
1339   MapChooseTreeGadgets(*ti_ptr);
1340
1341   FadeToFront();
1342   InitAnimation();
1343 }
1344
1345 static void AdjustChooseTreeScrollbar(int id, int first_entry, TreeInfo *ti)
1346 {
1347   struct GadgetInfo *gi = screen_gadget[id];
1348   int items_max, items_visible, item_position;
1349
1350   items_max = numTreeInfoInGroup(ti);
1351   items_visible = NUM_MENU_ENTRIES_ON_SCREEN;
1352   item_position = first_entry;
1353
1354   if (item_position > items_max - items_visible)
1355     item_position = items_max - items_visible;
1356
1357   ModifyGadget(gi, GDI_SCROLLBAR_ITEMS_MAX, items_max,
1358                GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
1359                GDI_SCROLLBAR_ITEM_POSITION, item_position, GDI_END);
1360 }
1361
1362 static void drawChooseTreeList(int first_entry, int num_page_entries,
1363                                TreeInfo *ti)
1364 {
1365   int i;
1366   char buffer[SCR_FIELDX * 2];
1367   int max_buffer_len = (SCR_FIELDX - 2) * 2;
1368   char *title_string = NULL;
1369   int xoffset_setup = 16;
1370   int yoffset_setup = 16;
1371   int xoffset = (ti->type == TREE_TYPE_LEVEL_DIR ? 0 : xoffset_setup);
1372   int yoffset = (ti->type == TREE_TYPE_LEVEL_DIR ? 0 : yoffset_setup);
1373   int last_game_status = game_status;   /* save current game status */
1374
1375   title_string =
1376     (ti->type == TREE_TYPE_LEVEL_DIR ? "Level Directories" :
1377      ti->type == TREE_TYPE_GRAPHICS_DIR ? "Custom Graphics" :
1378      ti->type == TREE_TYPE_SOUNDS_DIR ? "Custom Sounds" :
1379      ti->type == TREE_TYPE_MUSIC_DIR ? "Custom Music" : "");
1380
1381   DrawText(SX + xoffset, SY + yoffset, title_string, FONT_TITLE_1);
1382
1383   /* force LEVELS font on artwork setup screen */
1384   game_status = GAME_MODE_LEVELS;
1385
1386   /* clear tree list area, but not title or scrollbar */
1387   DrawBackground(mSX, mSY + MENU_SCREEN_START_YPOS * 32,
1388                  SXSIZE - 32 + menu.scrollbar_xoffset,
1389                  MAX_MENU_ENTRIES_ON_SCREEN * 32);
1390
1391   for(i=0; i<num_page_entries; i++)
1392   {
1393     TreeInfo *node, *node_first;
1394     int entry_pos = first_entry + i;
1395     int ypos = MENU_SCREEN_START_YPOS + i;
1396
1397     node_first = getTreeInfoFirstGroupEntry(ti);
1398     node = getTreeInfoFromPos(node_first, entry_pos);
1399
1400     strncpy(buffer, node->name , max_buffer_len);
1401     buffer[max_buffer_len] = '\0';
1402
1403     DrawText(mSX + 32, mSY + ypos * 32, buffer, FONT_TEXT_1 + node->color);
1404
1405     if (node->parent_link)
1406       initCursor(i, IMG_MENU_BUTTON_LEFT);
1407     else if (node->level_group)
1408       initCursor(i, IMG_MENU_BUTTON_RIGHT);
1409     else
1410       initCursor(i, IMG_MENU_BUTTON);
1411   }
1412
1413   game_status = last_game_status;       /* restore current game status */
1414
1415   redraw_mask |= REDRAW_FIELD;
1416 }
1417
1418 static void drawChooseTreeInfo(int entry_pos, TreeInfo *ti)
1419 {
1420   TreeInfo *node, *node_first;
1421   int x, last_redraw_mask = redraw_mask;
1422
1423   if (ti->type != TREE_TYPE_LEVEL_DIR)
1424     return;
1425
1426   node_first = getTreeInfoFirstGroupEntry(ti);
1427   node = getTreeInfoFromPos(node_first, entry_pos);
1428
1429   DrawBackground(SX + 32, SY + 32, SXSIZE - 64, 32);
1430
1431   if (node->parent_link)
1432     DrawTextFCentered(40, FONT_TITLE_2, "leave group \"%s\"",
1433                       node->class_desc);
1434   else if (node->level_group)
1435     DrawTextFCentered(40, FONT_TITLE_2, "enter group \"%s\"",
1436                       node->class_desc);
1437   else if (ti->type == TREE_TYPE_LEVEL_DIR)
1438     DrawTextFCentered(40, FONT_TITLE_2, "%3d levels (%s)",
1439                       node->levels, node->class_desc);
1440
1441   /* let BackToFront() redraw only what is needed */
1442   redraw_mask = last_redraw_mask | REDRAW_TILES;
1443   for (x=0; x<SCR_FIELDX; x++)
1444     MarkTileDirty(x, 1);
1445 }
1446
1447 static void HandleChooseTree(int mx, int my, int dx, int dy, int button,
1448                              TreeInfo **ti_ptr)
1449 {
1450   TreeInfo *ti = *ti_ptr;
1451   int x = 0;
1452   int y = ti->cl_cursor;
1453   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
1454   int num_entries = numTreeInfoInGroup(ti);
1455   int num_page_entries;
1456   int last_game_status = game_status;   /* save current game status */
1457
1458   /* force LEVELS draw offset on choose level and artwork setup screen */
1459   game_status = GAME_MODE_LEVELS;
1460
1461   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
1462     num_page_entries = num_entries;
1463   else
1464     num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
1465
1466   game_status = last_game_status;       /* restore current game status */
1467
1468   if (button == MB_MENU_INITIALIZE)
1469   {
1470     int num_entries = numTreeInfoInGroup(ti);
1471     int entry_pos = posTreeInfo(ti);
1472
1473     if (ti->cl_first == -1)
1474     {
1475       /* only on initialization */
1476       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
1477       ti->cl_cursor = entry_pos - ti->cl_first;
1478     }
1479     else if (ti->cl_cursor >= num_page_entries ||
1480              (num_entries > num_page_entries &&
1481               num_entries - ti->cl_first < num_page_entries))
1482     {
1483       /* only after change of list size (by custom graphic configuration) */
1484       ti->cl_first = MAX(0, entry_pos - num_page_entries + 1);
1485       ti->cl_cursor = entry_pos - ti->cl_first;
1486     }
1487
1488     if (dx == 999)      /* first entry is set by scrollbar position */
1489       ti->cl_first = dy;
1490     else
1491       AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
1492                                 ti->cl_first, ti);
1493
1494     drawChooseTreeList(ti->cl_first, num_page_entries, ti);
1495     drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
1496     drawChooseTreeCursor(ti->cl_cursor, FC_RED);
1497
1498     return;
1499   }
1500   else if (button == MB_MENU_LEAVE)
1501   {
1502     if (ti->node_parent)
1503     {
1504       *ti_ptr = ti->node_parent;
1505       DrawChooseTree(ti_ptr);
1506     }
1507     else if (game_status == GAME_MODE_SETUP)
1508     {
1509       execSetupArtwork();
1510     }
1511     else
1512     {
1513       game_status = GAME_MODE_MAIN;
1514       DrawMainMenu();
1515     }
1516
1517     return;
1518   }
1519
1520   if (mx || my)         /* mouse input */
1521   {
1522     int last_game_status = game_status; /* save current game status */
1523
1524     /* force LEVELS draw offset on artwork setup screen */
1525     game_status = GAME_MODE_LEVELS;
1526
1527     x = (mx - mSX) / 32;
1528     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
1529
1530     game_status = last_game_status;     /* restore current game status */
1531   }
1532   else if (dx || dy)    /* keyboard or scrollbar/scrollbutton input */
1533   {
1534     /* move cursor instead of scrolling when already at start/end of list */
1535     if (dy == -1 * SCROLL_LINE && ti->cl_first == 0)
1536       dy = -1;
1537     else if (dy == +1 * SCROLL_LINE &&
1538              ti->cl_first + num_page_entries == num_entries)
1539       dy = 1;
1540
1541     /* handle scrolling screen one line or page */
1542     if (ti->cl_cursor + dy < 0 ||
1543         ti->cl_cursor + dy > num_page_entries - 1)
1544     {
1545       if (ABS(dy) == SCROLL_PAGE)
1546         step = num_page_entries - 1;
1547
1548       if (dy < 0 && ti->cl_first > 0)
1549       {
1550         /* scroll page/line up */
1551
1552         ti->cl_first -= step;
1553         if (ti->cl_first < 0)
1554           ti->cl_first = 0;
1555
1556         drawChooseTreeList(ti->cl_first, num_page_entries, ti);
1557         drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
1558         drawChooseTreeCursor(ti->cl_cursor, FC_RED);
1559         AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
1560                                   ti->cl_first, ti);
1561       }
1562       else if (dy > 0 && ti->cl_first + num_page_entries < num_entries)
1563       {
1564         /* scroll page/line down */
1565
1566         ti->cl_first += step;
1567         if (ti->cl_first + num_page_entries > num_entries)
1568           ti->cl_first = MAX(0, num_entries - num_page_entries);
1569
1570         drawChooseTreeList(ti->cl_first, num_page_entries, ti);
1571         drawChooseTreeInfo(ti->cl_first + ti->cl_cursor, ti);
1572         drawChooseTreeCursor(ti->cl_cursor, FC_RED);
1573         AdjustChooseTreeScrollbar(SCREEN_CTRL_ID_SCROLL_VERTICAL,
1574                                   ti->cl_first, ti);
1575       }
1576
1577       return;
1578     }
1579
1580     /* handle moving cursor one line */
1581     y = ti->cl_cursor + dy;
1582   }
1583
1584   if (dx == 1)
1585   {
1586     TreeInfo *node_first, *node_cursor;
1587     int entry_pos = ti->cl_first + y;
1588
1589     node_first = getTreeInfoFirstGroupEntry(ti);
1590     node_cursor = getTreeInfoFromPos(node_first, entry_pos);
1591
1592     if (node_cursor->node_group)
1593     {
1594       node_cursor->cl_first = ti->cl_first;
1595       node_cursor->cl_cursor = ti->cl_cursor;
1596       *ti_ptr = node_cursor->node_group;
1597       DrawChooseTree(ti_ptr);
1598
1599       return;
1600     }
1601   }
1602   else if (dx == -1 && ti->node_parent)
1603   {
1604     *ti_ptr = ti->node_parent;
1605     DrawChooseTree(ti_ptr);
1606
1607     return;
1608   }
1609
1610   if (x == 0 && y >= 0 && y < num_page_entries)
1611   {
1612     if (button)
1613     {
1614       if (y != ti->cl_cursor)
1615       {
1616         drawChooseTreeCursor(y, FC_RED);
1617         drawChooseTreeCursor(ti->cl_cursor, FC_BLUE);
1618         drawChooseTreeInfo(ti->cl_first + y, ti);
1619         ti->cl_cursor = y;
1620       }
1621     }
1622     else
1623     {
1624       TreeInfo *node_first, *node_cursor;
1625       int entry_pos = ti->cl_first + y;
1626
1627       node_first = getTreeInfoFirstGroupEntry(ti);
1628       node_cursor = getTreeInfoFromPos(node_first, entry_pos);
1629
1630       if (node_cursor->node_group)
1631       {
1632         node_cursor->cl_first = ti->cl_first;
1633         node_cursor->cl_cursor = ti->cl_cursor;
1634         *ti_ptr = node_cursor->node_group;
1635         DrawChooseTree(ti_ptr);
1636       }
1637       else if (node_cursor->parent_link)
1638       {
1639         *ti_ptr = node_cursor->node_parent;
1640         DrawChooseTree(ti_ptr);
1641       }
1642       else
1643       {
1644         node_cursor->cl_first = ti->cl_first;
1645         node_cursor->cl_cursor = ti->cl_cursor;
1646         *ti_ptr = node_cursor;
1647
1648         if (ti->type == TREE_TYPE_LEVEL_DIR)
1649         {
1650           LoadLevelSetup_SeriesInfo();
1651
1652           SaveLevelSetup_LastSeries();
1653           SaveLevelSetup_SeriesInfo();
1654           TapeErase();
1655         }
1656
1657         if (game_status == GAME_MODE_SETUP)
1658         {
1659           execSetupArtwork();
1660         }
1661         else
1662         {
1663           game_status = GAME_MODE_MAIN;
1664           DrawMainMenu();
1665         }
1666       }
1667     }
1668   }
1669
1670 #if 0
1671   if (game_status == GAME_MODE_LEVELS || game_status == GAME_MODE_SETUP)
1672     DoAnimation();
1673
1674   BackToFront();
1675 #endif
1676 }
1677
1678 void DrawChooseLevel()
1679 {
1680   SetMainBackgroundImage(IMG_BACKGROUND_LEVELS);
1681
1682   DrawChooseTree(&leveldir_current);
1683
1684   PlayMenuSound();
1685   PlayMenuMusic();
1686 }
1687
1688 void HandleChooseLevel(int mx, int my, int dx, int dy, int button)
1689 {
1690   HandleChooseTree(mx, my, dx, dy, button, &leveldir_current);
1691
1692   DoAnimation();
1693   BackToFront();
1694 }
1695
1696 void DrawHallOfFame(int highlight_position)
1697 {
1698   UnmapAllGadgets();
1699   FadeSoundsAndMusic();
1700   CloseDoor(DOOR_CLOSE_2);
1701
1702   if (highlight_position < 0) 
1703     LoadScore(level_nr);
1704
1705   FadeToFront();
1706   InitAnimation();
1707
1708   HandleHallOfFame(highlight_position,0, 0,0, MB_MENU_INITIALIZE);
1709
1710   PlayMenuSound();
1711   PlayMenuMusic();
1712 }
1713
1714 static void drawHallOfFameList(int first_entry, int highlight_position)
1715 {
1716   int i;
1717
1718   SetMainBackgroundImage(IMG_BACKGROUND_SCORES);
1719   ClearWindow();
1720
1721   DrawText(mSX + 80, mSY + 8, "Hall Of Fame", FONT_TITLE_1);
1722   DrawTextFCentered(46, FONT_TITLE_2, "HighScores of Level %d", level_nr);
1723
1724   for(i=0; i<NUM_MENU_ENTRIES_ON_SCREEN; i++)
1725   {
1726     int entry = first_entry + i;
1727     boolean active = (entry == highlight_position);
1728     int font_nr1 = (active ? FONT_TEXT_1_ACTIVE : FONT_TEXT_1);
1729     int font_nr2 = (active ? FONT_TEXT_2_ACTIVE : FONT_TEXT_2);
1730     int font_nr3 = (active ? FONT_TEXT_3_ACTIVE : FONT_TEXT_3);
1731     int font_nr4 = (active ? FONT_TEXT_4_ACTIVE : FONT_TEXT_4);
1732     int dx1 = 3 * getFontWidth(font_nr1);
1733     int dx2 = dx1 + getFontWidth(font_nr1);
1734     int dx3 = dx2 + 25 * getFontWidth(font_nr3);
1735     int sy = mSY + 64 + i * 32;
1736
1737     DrawText(mSX, sy, int2str(entry + 1, 3), font_nr1);
1738     DrawText(mSX + dx1, sy, ".", font_nr1);
1739     DrawText(mSX + dx2, sy, ".........................", font_nr3);
1740     if (strcmp(highscore[entry].Name, EMPTY_PLAYER_NAME) != 0)
1741       DrawText(mSX + dx2, sy, highscore[entry].Name, font_nr2);
1742     DrawText(mSX + dx3, sy, int2str(highscore[entry].Score, 5), font_nr4);
1743   }
1744
1745   redraw_mask |= REDRAW_FIELD;
1746 }
1747
1748 void HandleHallOfFame(int mx, int my, int dx, int dy, int button)
1749 {
1750   static int first_entry = 0;
1751   static int highlight_position = 0;
1752   int step = (button == 1 ? 1 : button == 2 ? 5 : 10);
1753   int button_released = !button;
1754
1755   if (button == MB_MENU_INITIALIZE)
1756   {
1757     first_entry = 0;
1758     highlight_position = mx;
1759     drawHallOfFameList(first_entry, highlight_position);
1760
1761     return;
1762   }
1763
1764   if (ABS(dy) == SCROLL_PAGE)           /* handle scrolling one page */
1765     step = NUM_MENU_ENTRIES_ON_SCREEN - 1;
1766
1767   if (dy < 0)
1768   {
1769     if (first_entry > 0)
1770     {
1771       first_entry -= step;
1772       if (first_entry < 0)
1773         first_entry = 0;
1774
1775       drawHallOfFameList(first_entry, highlight_position);
1776     }
1777   }
1778   else if (dy > 0)
1779   {
1780     if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN < MAX_SCORE_ENTRIES)
1781     {
1782       first_entry += step;
1783       if (first_entry + NUM_MENU_ENTRIES_ON_SCREEN > MAX_SCORE_ENTRIES)
1784         first_entry = MAX(0, MAX_SCORE_ENTRIES - NUM_MENU_ENTRIES_ON_SCREEN);
1785
1786       drawHallOfFameList(first_entry, highlight_position);
1787     }
1788   }
1789   else if (button_released)
1790   {
1791     FadeSound(SND_BACKGROUND_SCORES);
1792     game_status = GAME_MODE_MAIN;
1793     DrawMainMenu();
1794   }
1795
1796   if (game_status == GAME_MODE_SCORES)
1797     PlayMenuSoundIfLoop();
1798
1799   DoAnimation();
1800   BackToFront();
1801 }
1802
1803
1804 /* ========================================================================= */
1805 /* setup screen functions                                                    */
1806 /* ========================================================================= */
1807
1808 static struct TokenInfo *setup_info;
1809 static int num_setup_info;
1810
1811 static char *graphics_set_name;
1812 static char *sounds_set_name;
1813 static char *music_set_name;
1814
1815 static void execSetupMain()
1816 {
1817   setup_mode = SETUP_MODE_MAIN;
1818   DrawSetupScreen();
1819 }
1820
1821 static void execSetupGame()
1822 {
1823   setup_mode = SETUP_MODE_GAME;
1824   DrawSetupScreen();
1825 }
1826
1827 static void execSetupEditor()
1828 {
1829   setup_mode = SETUP_MODE_EDITOR;
1830   DrawSetupScreen();
1831 }
1832
1833 static void execSetupGraphics()
1834 {
1835   setup_mode = SETUP_MODE_GRAPHICS;
1836   DrawSetupScreen();
1837 }
1838
1839 static void execSetupSound()
1840 {
1841   setup_mode = SETUP_MODE_SOUND;
1842   DrawSetupScreen();
1843 }
1844
1845 static void execSetupArtwork()
1846 {
1847   setup.graphics_set = artwork.gfx_current->identifier;
1848   setup.sounds_set = artwork.snd_current->identifier;
1849   setup.music_set = artwork.mus_current->identifier;
1850
1851   /* needed if last screen (setup choice) changed graphics, sounds or music */
1852   ReloadCustomArtwork();
1853
1854   /* needed for displaying artwork name instead of artwork identifier */
1855   graphics_set_name = artwork.gfx_current->name;
1856   sounds_set_name = artwork.snd_current->name;
1857   music_set_name = artwork.mus_current->name;
1858
1859   setup_mode = SETUP_MODE_ARTWORK;
1860   DrawSetupScreen();
1861 }
1862
1863 static void execSetupChooseGraphics()
1864 {
1865   setup_mode = SETUP_MODE_CHOOSE_GRAPHICS;
1866   DrawSetupScreen();
1867 }
1868
1869 static void execSetupChooseSounds()
1870 {
1871   setup_mode = SETUP_MODE_CHOOSE_SOUNDS;
1872   DrawSetupScreen();
1873 }
1874
1875 static void execSetupChooseMusic()
1876 {
1877   setup_mode = SETUP_MODE_CHOOSE_MUSIC;
1878   DrawSetupScreen();
1879 }
1880
1881 static void execSetupInput()
1882 {
1883   setup_mode = SETUP_MODE_INPUT;
1884   DrawSetupScreen();
1885 }
1886
1887 static void execSetupShortcut()
1888 {
1889   setup_mode = SETUP_MODE_SHORTCUT;
1890   DrawSetupScreen();
1891 }
1892
1893 static void execExitSetup()
1894 {
1895   game_status = GAME_MODE_MAIN;
1896   DrawMainMenu();
1897 }
1898
1899 static void execSaveAndExitSetup()
1900 {
1901   SaveSetup();
1902   execExitSetup();
1903 }
1904
1905 static struct TokenInfo setup_info_main[] =
1906 {
1907   { TYPE_ENTER_MENU,    execSetupGame,          "Game Settings"         },
1908   { TYPE_ENTER_MENU,    execSetupEditor,        "Editor Settings"       },
1909   { TYPE_ENTER_MENU,    execSetupGraphics,      "Graphics"              },
1910   { TYPE_ENTER_MENU,    execSetupSound,         "Sound & Music"         },
1911   { TYPE_ENTER_MENU,    execSetupArtwork,       "Custom Artwork"        },
1912   { TYPE_ENTER_MENU,    execSetupInput,         "Input Devices"         },
1913   { TYPE_ENTER_MENU,    execSetupShortcut,      "Key Shortcuts"         },
1914   { TYPE_EMPTY,         NULL,                   ""                      },
1915   { TYPE_LEAVE_MENU,    execExitSetup,          "Exit"                  },
1916   { TYPE_LEAVE_MENU,    execSaveAndExitSetup,   "Save and Exit"         },
1917   { 0,                  NULL,                   NULL                    }
1918 };
1919
1920 static struct TokenInfo setup_info_game[] =
1921 {
1922   { TYPE_SWITCH,        &setup.team_mode,       "Team-Mode:"            },
1923   { TYPE_SWITCH,        &setup.handicap,        "Handicap:"             },
1924   { TYPE_SWITCH,        &setup.time_limit,      "Timelimit:"            },
1925   { TYPE_SWITCH,        &setup.autorecord,      "Auto-Record:"          },
1926   { TYPE_EMPTY,         NULL,                   ""                      },
1927   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
1928   { 0,                  NULL,                   NULL                    }
1929 };
1930
1931 static struct TokenInfo setup_info_editor[] =
1932 {
1933   { TYPE_STRING,        NULL,                   "Offer Special Elements:"},
1934   { TYPE_SWITCH,        &setup.editor.el_boulderdash,   "BoulderDash:"  },
1935   { TYPE_SWITCH,        &setup.editor.el_emerald_mine,  "Emerald Mine:" },
1936   { TYPE_SWITCH,        &setup.editor.el_more,          "More:"         },
1937   { TYPE_SWITCH,        &setup.editor.el_sokoban,       "Sokoban:"      },
1938   { TYPE_SWITCH,        &setup.editor.el_supaplex,      "Supaplex:"     },
1939   { TYPE_SWITCH,        &setup.editor.el_diamond_caves, "Diamd. Caves:" },
1940   { TYPE_SWITCH,        &setup.editor.el_dx_boulderdash,"DX Boulderd.:" },
1941   { TYPE_SWITCH,        &setup.editor.el_chars,         "Characters:"   },
1942   { TYPE_SWITCH,        &setup.editor.el_custom,        "Custom:"       },
1943   { TYPE_SWITCH,        &setup.editor.el_custom_more,   "More Custom:"  },
1944   { TYPE_SWITCH,        &setup.editor.el_headlines,     "Headlines:"    },
1945   { TYPE_SWITCH,        &setup.editor.el_user_defined,  "User defined:" },
1946   { TYPE_EMPTY,         NULL,                   ""                      },
1947   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
1948   { 0,                  NULL,                   NULL                    }
1949 };
1950
1951 static struct TokenInfo setup_info_graphics[] =
1952 {
1953   { TYPE_SWITCH,        &setup.fullscreen,      "Fullscreen:"           },
1954   { TYPE_SWITCH,        &setup.scroll_delay,    "Scroll Delay:"         },
1955   { TYPE_SWITCH,        &setup.soft_scrolling,  "Soft Scroll.:"         },
1956 #if 0
1957   { TYPE_SWITCH,        &setup.double_buffering,"Buffered gfx:"         },
1958   { TYPE_SWITCH,        &setup.fading,          "Fading:"               },
1959 #endif
1960   { TYPE_SWITCH,        &setup.quick_doors,     "Quick Doors:"          },
1961   { TYPE_SWITCH,        &setup.toons,           "Toons:"                },
1962   { TYPE_EMPTY,         NULL,                   ""                      },
1963   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
1964   { 0,                  NULL,                   NULL                    }
1965 };
1966
1967 static struct TokenInfo setup_info_sound[] =
1968 {
1969   { TYPE_SWITCH,        &setup.sound_simple,    "Simple Sound:"         },
1970   { TYPE_SWITCH,        &setup.sound_loops,     "Sound Loops:"          },
1971   { TYPE_SWITCH,        &setup.sound_music,     "Game Music:"           },
1972   { TYPE_EMPTY,         NULL,                   ""                      },
1973   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
1974   { 0,                  NULL,                   NULL                    }
1975 };
1976
1977 static struct TokenInfo setup_info_artwork[] =
1978 {
1979   { TYPE_ENTER_MENU,    execSetupChooseGraphics,"Custom Graphics"       },
1980   { TYPE_STRING,        &graphics_set_name,     ""                      },
1981   { TYPE_ENTER_MENU,    execSetupChooseSounds,  "Custom Sounds"         },
1982   { TYPE_STRING,        &sounds_set_name,       ""                      },
1983   { TYPE_ENTER_MENU,    execSetupChooseMusic,   "Custom Music"          },
1984   { TYPE_STRING,        &music_set_name,        ""                      },
1985   { TYPE_EMPTY,         NULL,                   ""                      },
1986   { TYPE_STRING,        NULL,                   "Override Level Artwork:"},
1987   { TYPE_YES_NO,        &setup.override_level_graphics, "Graphics:"     },
1988   { TYPE_YES_NO,        &setup.override_level_sounds,   "Sounds:"       },
1989   { TYPE_YES_NO,        &setup.override_level_music,    "Music:"        },
1990   { TYPE_EMPTY,         NULL,                   ""                      },
1991   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
1992   { 0,                  NULL,                   NULL                    }
1993 };
1994
1995 static struct TokenInfo setup_info_shortcut[] =
1996 {
1997   { TYPE_KEYTEXT,       NULL,                   "Quick Save Game:",     },
1998   { TYPE_KEY,           &setup.shortcut.save_game,      ""              },
1999   { TYPE_KEYTEXT,       NULL,                   "Quick Load Game:",     },
2000   { TYPE_KEY,           &setup.shortcut.load_game,      ""              },
2001   { TYPE_KEYTEXT,       NULL,                   "Toggle Pause:",        },
2002   { TYPE_KEY,           &setup.shortcut.toggle_pause,   ""              },
2003   { TYPE_EMPTY,         NULL,                   ""                      },
2004   { TYPE_YES_NO,        &setup.ask_on_escape,   "Ask on Esc:"           },
2005   { TYPE_EMPTY,         NULL,                   ""                      },
2006   { TYPE_LEAVE_MENU,    execSetupMain,          "Back"                  },
2007   { 0,                  NULL,                   NULL                    }
2008 };
2009
2010 static Key getSetupKey()
2011 {
2012   Key key = KSYM_UNDEFINED;
2013   boolean got_key_event = FALSE;
2014
2015   while (!got_key_event)
2016   {
2017     if (PendingEvent())         /* got event */
2018     {
2019       Event event;
2020
2021       NextEvent(&event);
2022
2023       switch(event.type)
2024       {
2025         case EVENT_KEYPRESS:
2026           {
2027             key = GetEventKey((KeyEvent *)&event, TRUE);
2028
2029             /* press 'Escape' or 'Enter' to keep the existing key binding */
2030             if (key == KSYM_Escape || key == KSYM_Return)
2031               key = KSYM_UNDEFINED;     /* keep old value */
2032
2033             got_key_event = TRUE;
2034           }
2035           break;
2036
2037         case EVENT_KEYRELEASE:
2038           key_joystick_mapping = 0;
2039           break;
2040
2041         default:
2042           HandleOtherEvents(&event);
2043           break;
2044       }
2045     }
2046
2047     DoAnimation();
2048     BackToFront();
2049
2050     /* don't eat all CPU time */
2051     Delay(10);
2052   }
2053
2054   return key;
2055 }
2056
2057 static void drawSetupValue(int pos)
2058 {
2059   int xpos = MENU_SCREEN_VALUE_XPOS;
2060   int ypos = MENU_SCREEN_START_YPOS + pos;
2061   int font_nr = FONT_VALUE_1;
2062   int type = setup_info[pos].type;
2063   void *value = setup_info[pos].value;
2064   char *value_string = (!(type & TYPE_GHOSTED) ? getSetupValue(type, value) :
2065                         "n/a");
2066
2067   if (value_string == NULL)
2068     return;
2069
2070   if (type & TYPE_KEY)
2071   {
2072     xpos = 3;
2073
2074     if (type & TYPE_QUERY)
2075     {
2076       value_string = "<press key>";
2077       font_nr = FONT_INPUT_1_ACTIVE;
2078     }
2079   }
2080   else if (type & TYPE_STRING)
2081   {
2082     int max_value_len = (SCR_FIELDX - 2) * 2;
2083
2084     xpos = 1;
2085     font_nr = FONT_VALUE_2;
2086
2087     if (strlen(value_string) > max_value_len)
2088       value_string[max_value_len] = '\0';
2089   }
2090   else if (type & TYPE_BOOLEAN_STYLE)
2091   {
2092     font_nr = (*(boolean *)value ? FONT_OPTION_ON : FONT_OPTION_OFF);
2093   }
2094
2095   DrawText(mSX + xpos * 32, mSY + ypos * 32,
2096            (xpos == 3 ? "              " : "   "), font_nr);
2097   DrawText(mSX + xpos * 32, mSY + ypos * 32, value_string, font_nr);
2098 }
2099
2100 static void changeSetupValue(int pos)
2101 {
2102   if (setup_info[pos].type & TYPE_BOOLEAN_STYLE)
2103   {
2104     *(boolean *)setup_info[pos].value ^= TRUE;
2105   }
2106   else if (setup_info[pos].type & TYPE_KEY)
2107   {
2108     Key key;
2109
2110     setup_info[pos].type |= TYPE_QUERY;
2111     drawSetupValue(pos);
2112     setup_info[pos].type &= ~TYPE_QUERY;
2113
2114     key = getSetupKey();
2115     if (key != KSYM_UNDEFINED)
2116       *(Key *)setup_info[pos].value = key;
2117   }
2118
2119   drawSetupValue(pos);
2120 }
2121
2122 static void DrawSetupScreen_Generic()
2123 {
2124   char *title_string = NULL;
2125   int i;
2126
2127   UnmapAllGadgets();
2128   CloseDoor(DOOR_CLOSE_2);
2129
2130   ClearWindow();
2131
2132   if (setup_mode == SETUP_MODE_MAIN)
2133   {
2134     setup_info = setup_info_main;
2135     title_string = "Setup";
2136   }
2137   else if (setup_mode == SETUP_MODE_GAME)
2138   {
2139     setup_info = setup_info_game;
2140     title_string = "Setup Game";
2141   }
2142   else if (setup_mode == SETUP_MODE_EDITOR)
2143   {
2144     setup_info = setup_info_editor;
2145     title_string = "Setup Editor";
2146   }
2147   else if (setup_mode == SETUP_MODE_GRAPHICS)
2148   {
2149     setup_info = setup_info_graphics;
2150     title_string = "Setup Graphics";
2151   }
2152   else if (setup_mode == SETUP_MODE_SOUND)
2153   {
2154     setup_info = setup_info_sound;
2155     title_string = "Setup Sound";
2156   }
2157   else if (setup_mode == SETUP_MODE_ARTWORK)
2158   {
2159     setup_info = setup_info_artwork;
2160     title_string = "Custom Artwork";
2161   }
2162   else if (setup_mode == SETUP_MODE_SHORTCUT)
2163   {
2164     setup_info = setup_info_shortcut;
2165     title_string = "Setup Shortcuts";
2166   }
2167
2168   DrawText(mSX + 16, mSY + 16, title_string, FONT_TITLE_1);
2169
2170   num_setup_info = 0;
2171   for(i=0; setup_info[i].type != 0 && i < NUM_MENU_ENTRIES_ON_SCREEN; i++)
2172   {
2173     void *value_ptr = setup_info[i].value;
2174     int ypos = MENU_SCREEN_START_YPOS + i;
2175     int font_nr = FONT_MENU_1;
2176
2177     /* set some entries to "unchangeable" according to other variables */
2178     if ((value_ptr == &setup.sound_simple && !audio.sound_available) ||
2179         (value_ptr == &setup.sound_loops  && !audio.loops_available) ||
2180         (value_ptr == &setup.sound_music  && !audio.music_available) ||
2181         (value_ptr == &setup.fullscreen   && !video.fullscreen_available))
2182       setup_info[i].type |= TYPE_GHOSTED;
2183
2184     if (setup_info[i].type & TYPE_STRING)
2185       font_nr = FONT_MENU_2;
2186
2187     DrawText(mSX + 32, mSY + ypos * 32, setup_info[i].text, font_nr);
2188
2189     if (setup_info[i].type & TYPE_ENTER_MENU)
2190       initCursor(i, IMG_MENU_BUTTON_RIGHT);
2191     else if (setup_info[i].type & TYPE_LEAVE_MENU)
2192       initCursor(i, IMG_MENU_BUTTON_LEFT);
2193     else if (setup_info[i].type & ~TYPE_SKIP_ENTRY)
2194       initCursor(i, IMG_MENU_BUTTON);
2195
2196     if (setup_info[i].type & TYPE_VALUE)
2197       drawSetupValue(i);
2198
2199     num_setup_info++;
2200   }
2201
2202   FadeToFront();
2203   InitAnimation();
2204   HandleSetupScreen_Generic(0,0,0,0,MB_MENU_INITIALIZE);
2205 }
2206
2207 void HandleSetupScreen_Generic(int mx, int my, int dx, int dy, int button)
2208 {
2209   static int choice_store[MAX_SETUP_MODES];
2210   int choice = choice_store[setup_mode];        /* always starts with 0 */
2211   int x = 0;
2212   int y = choice;
2213
2214   if (button == MB_MENU_INITIALIZE)
2215   {
2216     /* advance to first valid menu entry */
2217     while (choice < num_setup_info &&
2218            (setup_info[choice].type & TYPE_SKIP_ENTRY))
2219       choice++;
2220     choice_store[setup_mode] = choice;
2221
2222     drawCursor(choice, FC_RED);
2223     return;
2224   }
2225   else if (button == MB_MENU_LEAVE)
2226   {
2227     for (y=0; y<num_setup_info; y++)
2228     {
2229       if (setup_info[y].type & TYPE_LEAVE_MENU)
2230       {
2231         void (*menu_callback_function)(void) = setup_info[y].value;
2232
2233         menu_callback_function();
2234         break;  /* absolutely needed because function changes 'setup_info'! */
2235       }
2236     }
2237
2238     return;
2239   }
2240
2241   if (mx || my)         /* mouse input */
2242   {
2243     x = (mx - mSX) / 32;
2244     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
2245   }
2246   else if (dx || dy)    /* keyboard input */
2247   {
2248     if (dx)
2249     {
2250       int menu_navigation_type = (dx < 0 ? TYPE_LEAVE_MENU : TYPE_ENTER_MENU);
2251
2252       if ((setup_info[choice].type & menu_navigation_type) ||
2253           (setup_info[choice].type & TYPE_BOOLEAN_STYLE))
2254         button = MB_MENU_CHOICE;
2255     }
2256     else if (dy)
2257       y = choice + dy;
2258
2259     /* jump to next non-empty menu entry (up or down) */
2260     while (y > 0 && y < num_setup_info - 1 &&
2261            (setup_info[y].type & TYPE_SKIP_ENTRY))
2262       y += dy;
2263   }
2264
2265   if (x == 0 && y >= 0 && y < num_setup_info &&
2266       (setup_info[y].type & ~TYPE_SKIP_ENTRY))
2267   {
2268     if (button)
2269     {
2270       if (y != choice)
2271       {
2272         drawCursor(y, FC_RED);
2273         drawCursor(choice, FC_BLUE);
2274         choice = choice_store[setup_mode] = y;
2275       }
2276     }
2277     else if (!(setup_info[y].type & TYPE_GHOSTED))
2278     {
2279       if (setup_info[y].type & TYPE_ENTER_OR_LEAVE_MENU)
2280       {
2281         void (*menu_callback_function)(void) = setup_info[choice].value;
2282
2283         menu_callback_function();
2284       }
2285       else
2286       {
2287         if ((setup_info[y].type & TYPE_KEYTEXT) &&
2288             (setup_info[y + 1].type & TYPE_KEY))
2289           y++;
2290
2291         if (setup_info[y].type & TYPE_VALUE)
2292           changeSetupValue(y);
2293       }
2294     }
2295   }
2296
2297 #if 0
2298   BackToFront();
2299
2300   if (game_status == GAME_MODE_SETUP)
2301     DoAnimation();
2302 #endif
2303 }
2304
2305 void DrawSetupScreen_Input()
2306 {
2307   ClearWindow();
2308
2309   DrawText(mSX+16, mSY+16, "Setup Input", FONT_TITLE_1);
2310
2311   initCursor(0, IMG_MENU_BUTTON);
2312   initCursor(1, IMG_MENU_BUTTON);
2313   initCursor(2, IMG_MENU_BUTTON_RIGHT);
2314   initCursor(13, IMG_MENU_BUTTON_LEFT);
2315
2316   drawCursorXY(10, 0, IMG_MENU_BUTTON_LEFT);
2317   drawCursorXY(12, 0, IMG_MENU_BUTTON_RIGHT);
2318
2319   DrawText(mSX+32, mSY+2*32, "Player:", FONT_MENU_1);
2320   DrawText(mSX+32, mSY+3*32, "Device:", FONT_MENU_1);
2321   DrawText(mSX+32, mSY+15*32, "Back",   FONT_MENU_1);
2322
2323 #if 0
2324   DeactivateJoystickForCalibration();
2325   DrawTextSCentered(SYSIZE - 20, FONT_TEXT_4,
2326                     "Joysticks deactivated on this screen");
2327 #endif
2328
2329   HandleSetupScreen_Input(0,0, 0,0, MB_MENU_INITIALIZE);
2330   FadeToFront();
2331   InitAnimation();
2332 }
2333
2334 static void setJoystickDeviceToNr(char *device_name, int device_nr)
2335 {
2336   if (device_name == NULL)
2337     return;
2338
2339   if (device_nr < 0 || device_nr >= MAX_PLAYERS)
2340     device_nr = 0;
2341
2342   if (strlen(device_name) > 1)
2343   {
2344     char c1 = device_name[strlen(device_name) - 1];
2345     char c2 = device_name[strlen(device_name) - 2];
2346
2347     if (c1 >= '0' && c1 <= '9' && !(c2 >= '0' && c2 <= '9'))
2348       device_name[strlen(device_name) - 1] = '0' + (char)(device_nr % 10);
2349   }
2350   else
2351     strncpy(device_name, getDeviceNameFromJoystickNr(device_nr),
2352             strlen(device_name));
2353 }
2354
2355 static void drawPlayerSetupInputInfo(int player_nr)
2356 {
2357   int i;
2358   static struct SetupKeyboardInfo custom_key;
2359   static struct
2360   {
2361     Key *key;
2362     char *text;
2363   } custom[] =
2364   {
2365     { &custom_key.left,  "Joystick Left"  },
2366     { &custom_key.right, "Joystick Right" },
2367     { &custom_key.up,    "Joystick Up"    },
2368     { &custom_key.down,  "Joystick Down"  },
2369     { &custom_key.snap,  "Button 1"       },
2370     { &custom_key.bomb,  "Button 2"       }
2371   };
2372   static char *joystick_name[MAX_PLAYERS] =
2373   {
2374     "Joystick1",
2375     "Joystick2",
2376     "Joystick3",
2377     "Joystick4"
2378   };
2379
2380   custom_key = setup.input[player_nr].key;
2381
2382   DrawText(mSX+11*32, mSY+2*32, int2str(player_nr +1, 1), FONT_INPUT_1_ACTIVE);
2383 #if 1
2384   DrawGraphicThruMaskExt(drawto, mSX + 8 * TILEX, mSY + 2 * TILEY,
2385                          PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
2386 #else
2387   DrawGraphicThruMask(8, 2, PLAYER_NR_GFX(IMG_PLAYER_1, player_nr), 0);
2388 #endif
2389
2390   if (setup.input[player_nr].use_joystick)
2391   {
2392     char *device_name = setup.input[player_nr].joy.device_name;
2393
2394     DrawText(mSX+8*32, mSY+3*32,
2395              joystick_name[getJoystickNrFromDeviceName(device_name)],
2396              FONT_VALUE_1);
2397     DrawText(mSX+32, mSY+4*32, "Calibrate", FONT_MENU_1);
2398   }
2399   else
2400   {
2401     DrawText(mSX+8*32, mSY+3*32, "Keyboard ", FONT_VALUE_1);
2402     DrawText(mSX+32,   mSY+4*32, "Customize", FONT_MENU_1);
2403   }
2404
2405   DrawText(mSX+32, mSY+5*32, "Actual Settings:", FONT_MENU_1);
2406   drawCursorXY(1, 4, IMG_MENU_BUTTON_LEFT);
2407   drawCursorXY(1, 5, IMG_MENU_BUTTON_RIGHT);
2408   drawCursorXY(1, 6, IMG_MENU_BUTTON_UP);
2409   drawCursorXY(1, 7, IMG_MENU_BUTTON_DOWN);
2410   DrawText(mSX+2*32, mSY+6*32, ":", FONT_VALUE_OLD);
2411   DrawText(mSX+2*32, mSY+7*32, ":", FONT_VALUE_OLD);
2412   DrawText(mSX+2*32, mSY+8*32, ":", FONT_VALUE_OLD);
2413   DrawText(mSX+2*32, mSY+9*32, ":", FONT_VALUE_OLD);
2414   DrawText(mSX+32, mSY+10*32, "Snap Field:", FONT_VALUE_OLD);
2415   DrawText(mSX+32, mSY+12*32, "Place Bomb:", FONT_VALUE_OLD);
2416
2417   for (i=0; i<6; i++)
2418   {
2419     int ypos = 6 + i + (i > 3 ? i-3 : 0);
2420
2421     DrawText(mSX + 3*32, mSY + ypos*32,
2422              "              ", FONT_VALUE_1);
2423     DrawText(mSX + 3*32, mSY + ypos*32,
2424              (setup.input[player_nr].use_joystick ?
2425               custom[i].text :
2426               getKeyNameFromKey(*custom[i].key)), FONT_VALUE_1);
2427   }
2428 }
2429
2430 void HandleSetupScreen_Input(int mx, int my, int dx, int dy, int button)
2431 {
2432   static int choice = 0;
2433   static int player_nr = 0;
2434   int x = 0;
2435   int y = choice;
2436   int pos_start  = SETUPINPUT_SCREEN_POS_START;
2437   int pos_empty1 = SETUPINPUT_SCREEN_POS_EMPTY1;
2438   int pos_empty2 = SETUPINPUT_SCREEN_POS_EMPTY2;
2439   int pos_end    = SETUPINPUT_SCREEN_POS_END;
2440
2441   if (button == MB_MENU_INITIALIZE)
2442   {
2443     drawPlayerSetupInputInfo(player_nr);
2444     drawCursor(choice, FC_RED);
2445     return;
2446   }
2447   else if (button == MB_MENU_LEAVE)
2448   {
2449     setup_mode = SETUP_MODE_MAIN;
2450     DrawSetupScreen();
2451     InitJoysticks();
2452   }
2453
2454   if (mx || my)         /* mouse input */
2455   {
2456     x = (mx - mSX) / 32;
2457     y = (my - mSY) / 32 - MENU_SCREEN_START_YPOS;
2458   }
2459   else if (dx || dy)    /* keyboard input */
2460   {
2461     if (dx && choice == 0)
2462       x = (dx < 0 ? 10 : 12);
2463     else if ((dx && choice == 1) ||
2464              (dx == +1 && choice == 2) ||
2465              (dx == -1 && choice == pos_end))
2466       button = MB_MENU_CHOICE;
2467     else if (dy)
2468       y = choice + dy;
2469
2470     if (y >= pos_empty1 && y <= pos_empty2)
2471       y = (dy > 0 ? pos_empty2 + 1 : pos_empty1 - 1);
2472   }
2473
2474   if (y == 0 && ((x == 0 && !button) || ((x == 10 || x == 12) && button)))
2475   {
2476     static unsigned long delay = 0;
2477
2478     if (!DelayReached(&delay, GADGET_FRAME_DELAY))
2479 #if 1
2480       return;
2481 #else
2482       goto out;
2483 #endif
2484
2485     player_nr = (player_nr + (x == 10 ? -1 : +1) + MAX_PLAYERS) % MAX_PLAYERS;
2486
2487     drawPlayerSetupInputInfo(player_nr);
2488   }
2489   else if (x == 0 && y >= pos_start && y <= pos_end &&
2490            !(y >= pos_empty1 && y <= pos_empty2))
2491   {
2492     if (button)
2493     {
2494       if (y != choice)
2495       {
2496         drawCursor(y, FC_RED);
2497         drawCursor(choice, FC_BLUE);
2498         choice = y;
2499       }
2500     }
2501     else
2502     {
2503       if (y == 1)
2504       {
2505         char *device_name = setup.input[player_nr].joy.device_name;
2506
2507         if (!setup.input[player_nr].use_joystick)
2508         {
2509           int new_device_nr = (dx >= 0 ? 0 : MAX_PLAYERS - 1);
2510
2511           setJoystickDeviceToNr(device_name, new_device_nr);
2512           setup.input[player_nr].use_joystick = TRUE;
2513         }
2514         else
2515         {
2516           int device_nr = getJoystickNrFromDeviceName(device_name);
2517           int new_device_nr = device_nr + (dx >= 0 ? +1 : -1);
2518
2519           if (new_device_nr < 0 || new_device_nr >= MAX_PLAYERS)
2520             setup.input[player_nr].use_joystick = FALSE;
2521           else
2522             setJoystickDeviceToNr(device_name, new_device_nr);
2523         }
2524
2525         drawPlayerSetupInputInfo(player_nr);
2526       }
2527       else if (y == 2)
2528       {
2529         if (setup.input[player_nr].use_joystick)
2530         {
2531           InitJoysticks();
2532           CalibrateJoystick(player_nr);
2533         }
2534         else
2535           CustomizeKeyboard(player_nr);
2536       }
2537       else if (y == pos_end)
2538       {
2539         InitJoysticks();
2540
2541         setup_mode = SETUP_MODE_MAIN;
2542         DrawSetupScreen();
2543       }
2544     }
2545   }
2546
2547 #if 0
2548   BackToFront();
2549
2550   out:
2551
2552   if (game_status == GAME_MODE_SETUP)
2553     DoAnimation();
2554 #endif
2555 }
2556
2557 void CustomizeKeyboard(int player_nr)
2558 {
2559   int i;
2560   int step_nr;
2561   boolean finished = FALSE;
2562   static struct SetupKeyboardInfo custom_key;
2563   static struct
2564   {
2565     Key *key;
2566     char *text;
2567   } customize_step[] =
2568   {
2569     { &custom_key.left,  "Move Left"  },
2570     { &custom_key.right, "Move Right" },
2571     { &custom_key.up,    "Move Up"    },
2572     { &custom_key.down,  "Move Down"  },
2573     { &custom_key.snap,  "Snap Field" },
2574     { &custom_key.bomb,  "Place Bomb" }
2575   };
2576
2577   /* read existing key bindings from player setup */
2578   custom_key = setup.input[player_nr].key;
2579
2580   ClearWindow();
2581   DrawText(mSX + 16, mSY + 16, "Keyboard Input", FONT_TITLE_1);
2582
2583   BackToFront();
2584   InitAnimation();
2585
2586   step_nr = 0;
2587   DrawText(mSX, mSY + (2+2*step_nr)*32,
2588            customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
2589   DrawText(mSX, mSY + (2+2*step_nr+1)*32,
2590            "Key:", FONT_INPUT_1_ACTIVE);
2591   DrawText(mSX + 4*32, mSY + (2+2*step_nr+1)*32,
2592            getKeyNameFromKey(*customize_step[step_nr].key), FONT_VALUE_OLD);
2593
2594   while(!finished)
2595   {
2596     if (PendingEvent())         /* got event */
2597     {
2598       Event event;
2599
2600       NextEvent(&event);
2601
2602       switch(event.type)
2603       {
2604         case EVENT_KEYPRESS:
2605           {
2606             Key key = GetEventKey((KeyEvent *)&event, FALSE);
2607
2608             if (key == KSYM_Escape || (key == KSYM_Return && step_nr == 6))
2609             {
2610               finished = TRUE;
2611               break;
2612             }
2613
2614             /* all keys configured -- wait for "Escape" or "Return" key */
2615             if (step_nr == 6)
2616               break;
2617
2618             /* press 'Enter' to keep the existing key binding */
2619             if (key == KSYM_Return)
2620               key = *customize_step[step_nr].key;
2621
2622             /* check if key already used */
2623             for (i=0; i<step_nr; i++)
2624               if (*customize_step[i].key == key)
2625                 break;
2626             if (i < step_nr)
2627               break;
2628
2629             /* got new key binding */
2630             *customize_step[step_nr].key = key;
2631             DrawText(mSX + 4*32, mSY + (2+2*step_nr+1)*32,
2632                      "             ", FONT_VALUE_1);
2633             DrawText(mSX + 4*32, mSY + (2+2*step_nr+1)*32,
2634                      getKeyNameFromKey(key), FONT_VALUE_1);
2635             step_nr++;
2636
2637             /* un-highlight last query */
2638             DrawText(mSX, mSY+(2+2*(step_nr-1))*32,
2639                      customize_step[step_nr-1].text, FONT_MENU_1);
2640             DrawText(mSX, mSY+(2+2*(step_nr-1)+1)*32,
2641                      "Key:", FONT_MENU_1);
2642
2643             /* press 'Enter' to leave */
2644             if (step_nr == 6)
2645             {
2646               DrawText(mSX + 16, mSY + 15*32+16,
2647                        "Press Enter", FONT_TITLE_1);
2648               break;
2649             }
2650
2651             /* query next key binding */
2652             DrawText(mSX, mSY+(2+2*step_nr)*32,
2653                      customize_step[step_nr].text, FONT_INPUT_1_ACTIVE);
2654             DrawText(mSX, mSY+(2+2*step_nr+1)*32,
2655                      "Key:", FONT_INPUT_1_ACTIVE);
2656             DrawText(mSX + 4*32, mSY+(2+2*step_nr+1)*32,
2657                      getKeyNameFromKey(*customize_step[step_nr].key),
2658                      FONT_VALUE_OLD);
2659           }
2660           break;
2661
2662         case EVENT_KEYRELEASE:
2663           key_joystick_mapping = 0;
2664           break;
2665
2666         default:
2667           HandleOtherEvents(&event);
2668           break;
2669       }
2670     }
2671
2672     DoAnimation();
2673     BackToFront();
2674
2675     /* don't eat all CPU time */
2676     Delay(10);
2677   }
2678
2679   /* write new key bindings back to player setup */
2680   setup.input[player_nr].key = custom_key;
2681
2682   StopAnimation();
2683   DrawSetupScreen_Input();
2684 }
2685
2686 static boolean CalibrateJoystickMain(int player_nr)
2687 {
2688   int new_joystick_xleft = JOYSTICK_XMIDDLE;
2689   int new_joystick_xright = JOYSTICK_XMIDDLE;
2690   int new_joystick_yupper = JOYSTICK_YMIDDLE;
2691   int new_joystick_ylower = JOYSTICK_YMIDDLE;
2692   int new_joystick_xmiddle, new_joystick_ymiddle;
2693
2694   int joystick_fd = joystick.fd[player_nr];
2695   int x, y, last_x, last_y, xpos = 8, ypos = 3;
2696   boolean check[3][3];
2697   int check_remaining = 3 * 3;
2698   int joy_x, joy_y;
2699   int joy_value;
2700   int result = -1;
2701
2702   if (joystick.status == JOYSTICK_NOT_AVAILABLE)
2703     return FALSE;
2704
2705   if (joystick_fd < 0 || !setup.input[player_nr].use_joystick)
2706     return FALSE;
2707
2708   ClearWindow();
2709
2710   for(y=0; y < 3; y++)
2711   {
2712     for(x=0; x < 3; x++)
2713     {
2714       DrawGraphic(xpos + x - 1, ypos + y - 1, IMG_MENU_CALIBRATE_BLUE, 0);
2715       check[x][y] = FALSE;
2716     }
2717   }
2718
2719   DrawText(mSX,      mSY +  6 * 32, " ROTATE JOYSTICK ", FONT_TITLE_1);
2720   DrawText(mSX,      mSY +  7 * 32, "IN ALL DIRECTIONS", FONT_TITLE_1);
2721   DrawText(mSX + 16, mSY +  9 * 32, "  IF ALL BALLS  ",  FONT_TITLE_1);
2722   DrawText(mSX,      mSY + 10 * 32, "   ARE YELLOW,   ", FONT_TITLE_1);
2723   DrawText(mSX,      mSY + 11 * 32, " CENTER JOYSTICK ", FONT_TITLE_1);
2724   DrawText(mSX,      mSY + 12 * 32, "       AND       ", FONT_TITLE_1);
2725   DrawText(mSX,      mSY + 13 * 32, "PRESS ANY BUTTON!", FONT_TITLE_1);
2726
2727   joy_value = Joystick(player_nr);
2728   last_x = (joy_value & JOY_LEFT ? -1 : joy_value & JOY_RIGHT ? +1 : 0);
2729   last_y = (joy_value & JOY_UP   ? -1 : joy_value & JOY_DOWN  ? +1 : 0);
2730
2731   /* eventually uncalibrated center position (joystick could be uncentered) */
2732   if (!ReadJoystick(joystick_fd, &joy_x, &joy_y, NULL, NULL))
2733     return FALSE;
2734
2735   new_joystick_xmiddle = joy_x;
2736   new_joystick_ymiddle = joy_y;
2737
2738   DrawGraphic(xpos + last_x, ypos + last_y, IMG_MENU_CALIBRATE_RED, 0);
2739   BackToFront();
2740
2741   while(Joystick(player_nr) & JOY_BUTTON);      /* wait for released button */
2742   InitAnimation();
2743
2744   while(result < 0)
2745   {
2746     if (PendingEvent())         /* got event */
2747     {
2748       Event event;
2749
2750       NextEvent(&event);
2751
2752       switch(event.type)
2753       {
2754         case EVENT_KEYPRESS:
2755           switch(GetEventKey((KeyEvent *)&event, TRUE))
2756           {
2757             case KSYM_Return:
2758               if (check_remaining == 0)
2759                 result = 1;
2760               break;
2761
2762             case KSYM_Escape:
2763               result = 0;
2764               break;
2765
2766             default:
2767               break;
2768           }
2769           break;
2770
2771         case EVENT_KEYRELEASE:
2772           key_joystick_mapping = 0;
2773           break;
2774
2775         default:
2776           HandleOtherEvents(&event);
2777           break;
2778       }
2779     }
2780
2781     if (!ReadJoystick(joystick_fd, &joy_x, &joy_y, NULL, NULL))
2782       return FALSE;
2783
2784     new_joystick_xleft  = MIN(new_joystick_xleft,  joy_x);
2785     new_joystick_xright = MAX(new_joystick_xright, joy_x);
2786     new_joystick_yupper = MIN(new_joystick_yupper, joy_y);
2787     new_joystick_ylower = MAX(new_joystick_ylower, joy_y);
2788
2789     setup.input[player_nr].joy.xleft = new_joystick_xleft;
2790     setup.input[player_nr].joy.yupper = new_joystick_yupper;
2791     setup.input[player_nr].joy.xright = new_joystick_xright;
2792     setup.input[player_nr].joy.ylower = new_joystick_ylower;
2793     setup.input[player_nr].joy.xmiddle = new_joystick_xmiddle;
2794     setup.input[player_nr].joy.ymiddle = new_joystick_ymiddle;
2795
2796     CheckJoystickData();
2797
2798     joy_value = Joystick(player_nr);
2799
2800     if (joy_value & JOY_BUTTON && check_remaining == 0)
2801       result = 1;
2802
2803     x = (joy_value & JOY_LEFT ? -1 : joy_value & JOY_RIGHT ? +1 : 0);
2804     y = (joy_value & JOY_UP   ? -1 : joy_value & JOY_DOWN  ? +1 : 0);
2805
2806     if (x != last_x || y != last_y)
2807     {
2808       DrawGraphic(xpos + last_x, ypos + last_y, IMG_MENU_CALIBRATE_YELLOW, 0);
2809       DrawGraphic(xpos + x,      ypos + y,      IMG_MENU_CALIBRATE_RED,    0);
2810
2811       last_x = x;
2812       last_y = y;
2813
2814       if (check_remaining > 0 && !check[x+1][y+1])
2815       {
2816         check[x+1][y+1] = TRUE;
2817         check_remaining--;
2818       }
2819
2820 #if 0
2821 #ifdef DEBUG
2822       printf("LEFT / MIDDLE / RIGHT == %d / %d / %d\n",
2823              setup.input[player_nr].joy.xleft,
2824              setup.input[player_nr].joy.xmiddle,
2825              setup.input[player_nr].joy.xright);
2826       printf("UP / MIDDLE / DOWN == %d / %d / %d\n",
2827              setup.input[player_nr].joy.yupper,
2828              setup.input[player_nr].joy.ymiddle,
2829              setup.input[player_nr].joy.ylower);
2830 #endif
2831 #endif
2832
2833     }
2834
2835     DoAnimation();
2836     BackToFront();
2837
2838     /* don't eat all CPU time */
2839     Delay(10);
2840   }
2841
2842   /* calibrated center position (joystick should now be centered) */
2843   if (!ReadJoystick(joystick_fd, &joy_x, &joy_y, NULL, NULL))
2844     return FALSE;
2845
2846   new_joystick_xmiddle = joy_x;
2847   new_joystick_ymiddle = joy_y;
2848
2849   StopAnimation();
2850
2851   DrawSetupScreen_Input();
2852
2853   /* wait until the last pressed button was released */
2854   while (Joystick(player_nr) & JOY_BUTTON)
2855   {
2856     if (PendingEvent())         /* got event */
2857     {
2858       Event event;
2859
2860       NextEvent(&event);
2861       HandleOtherEvents(&event);
2862
2863       Delay(10);
2864     }
2865   }
2866
2867   return TRUE;
2868 }
2869
2870 void CalibrateJoystick(int player_nr)
2871 {
2872   if (!CalibrateJoystickMain(player_nr))
2873   {
2874     ClearWindow();
2875
2876     DrawText(mSX + 16, mSY + 6*32, "  JOYSTICK NOT  ",  FONT_TITLE_1);
2877     DrawText(mSX,      mSY + 7*32, "    AVAILABLE    ", FONT_TITLE_1);
2878     BackToFront();
2879     Delay(2000);        /* show error message for two seconds */
2880   }
2881 }
2882
2883 void DrawSetupScreen()
2884 {
2885   DeactivateJoystick();
2886
2887   SetMainBackgroundImage(IMG_BACKGROUND_SETUP);
2888
2889   if (setup_mode == SETUP_MODE_INPUT)
2890     DrawSetupScreen_Input();
2891   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
2892     DrawChooseTree(&artwork.gfx_current);
2893   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
2894     DrawChooseTree(&artwork.snd_current);
2895   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
2896     DrawChooseTree(&artwork.mus_current);
2897   else
2898     DrawSetupScreen_Generic();
2899
2900   PlayMenuSound();
2901   PlayMenuMusic();
2902 }
2903
2904 void HandleSetupScreen(int mx, int my, int dx, int dy, int button)
2905 {
2906   if (setup_mode == SETUP_MODE_INPUT)
2907     HandleSetupScreen_Input(mx, my, dx, dy, button);
2908   else if (setup_mode == SETUP_MODE_CHOOSE_GRAPHICS)
2909     HandleChooseTree(mx, my, dx, dy, button, &artwork.gfx_current);
2910   else if (setup_mode == SETUP_MODE_CHOOSE_SOUNDS)
2911     HandleChooseTree(mx, my, dx, dy, button, &artwork.snd_current);
2912   else if (setup_mode == SETUP_MODE_CHOOSE_MUSIC)
2913     HandleChooseTree(mx, my, dx, dy, button, &artwork.mus_current);
2914   else
2915     HandleSetupScreen_Generic(mx, my, dx, dy, button);
2916
2917   DoAnimation();
2918   BackToFront();
2919 }
2920
2921 void HandleGameActions()
2922 {
2923   if (game_status != GAME_MODE_PLAYING)
2924     return;
2925
2926   if (local_player->LevelSolved)
2927     GameWon();
2928
2929   if (AllPlayersGone && !TAPE_IS_STOPPED(tape))
2930     TapeStop();
2931
2932   GameActions();
2933
2934   BackToFront();
2935
2936 #if 1
2937   if (tape.auto_play && !tape.playing)
2938     AutoPlayTape();     /* continue automatically playing next tape */
2939 #endif
2940 }
2941
2942 /* ---------- new screen button stuff -------------------------------------- */
2943
2944 /* graphic position and size values for buttons and scrollbars */
2945 #define SC_SCROLLBUTTON_XSIZE           TILEX
2946 #define SC_SCROLLBUTTON_YSIZE           TILEY
2947
2948 #define SC_SCROLL_VERTICAL_XSIZE        SC_SCROLLBUTTON_XSIZE
2949 #define SC_SCROLL_VERTICAL_YSIZE        ((MAX_MENU_ENTRIES_ON_SCREEN - 2) * \
2950                                          SC_SCROLLBUTTON_YSIZE)
2951 #define SC_SCROLL_UP_XPOS               (SXSIZE - SC_SCROLLBUTTON_XSIZE)
2952 #define SC_SCROLL_UP_YPOS               (2 * SC_SCROLLBUTTON_YSIZE)
2953 #define SC_SCROLL_VERTICAL_XPOS         SC_SCROLL_UP_XPOS
2954 #define SC_SCROLL_VERTICAL_YPOS         (SC_SCROLL_UP_YPOS + \
2955                                          SC_SCROLLBUTTON_YSIZE)
2956 #define SC_SCROLL_DOWN_XPOS             SC_SCROLL_UP_XPOS
2957 #define SC_SCROLL_DOWN_YPOS             (SC_SCROLL_VERTICAL_YPOS + \
2958                                          SC_SCROLL_VERTICAL_YSIZE)
2959
2960 #define SC_BORDER_SIZE                  14
2961
2962 static struct
2963 {
2964   int gfx_unpressed, gfx_pressed;
2965   int x, y;
2966   int gadget_id;
2967   char *infotext;
2968 } scrollbutton_info[NUM_SCREEN_SCROLLBUTTONS] =
2969 {
2970   {
2971     IMG_MENU_BUTTON_UP, IMG_MENU_BUTTON_UP_ACTIVE,
2972     SC_SCROLL_UP_XPOS, SC_SCROLL_UP_YPOS,
2973     SCREEN_CTRL_ID_SCROLL_UP,
2974     "scroll up"
2975   },
2976   {
2977     IMG_MENU_BUTTON_DOWN, IMG_MENU_BUTTON_DOWN_ACTIVE,
2978     SC_SCROLL_DOWN_XPOS, SC_SCROLL_DOWN_YPOS,
2979     SCREEN_CTRL_ID_SCROLL_DOWN,
2980     "scroll down"
2981   }
2982 };
2983
2984 static struct
2985 {
2986 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
2987   Bitmap **gfx_unpressed, **gfx_pressed;
2988 #else
2989   int gfx_unpressed, gfx_pressed;
2990 #endif
2991   int x, y;
2992   int width, height;
2993   int type;
2994   int gadget_id;
2995   char *infotext;
2996 } scrollbar_info[NUM_SCREEN_SCROLLBARS] =
2997 {
2998   {
2999 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
3000     &scrollbar_bitmap[0], &scrollbar_bitmap[1],
3001 #else
3002     IMG_MENU_SCROLLBAR, IMG_MENU_SCROLLBAR_ACTIVE,
3003 #endif
3004     SC_SCROLL_VERTICAL_XPOS, SC_SCROLL_VERTICAL_YPOS,
3005     SC_SCROLL_VERTICAL_XSIZE, SC_SCROLL_VERTICAL_YSIZE,
3006     GD_TYPE_SCROLLBAR_VERTICAL,
3007     SCREEN_CTRL_ID_SCROLL_VERTICAL,
3008     "scroll level series vertically"
3009   }
3010 };
3011
3012 static void CreateScreenScrollbuttons()
3013 {
3014   struct GadgetInfo *gi;
3015   unsigned long event_mask;
3016   int i;
3017
3018   for (i=0; i<NUM_SCREEN_SCROLLBUTTONS; i++)
3019   {
3020     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
3021     int gfx_unpressed, gfx_pressed;
3022     int x, y, width, height;
3023     int gd_x1, gd_x2, gd_y1, gd_y2;
3024     int id = scrollbutton_info[i].gadget_id;
3025
3026     event_mask = GD_EVENT_PRESSED | GD_EVENT_REPEATED;
3027
3028     x = mSX + scrollbutton_info[i].x + menu.scrollbar_xoffset;
3029     y = mSY + scrollbutton_info[i].y;
3030     width = SC_SCROLLBUTTON_XSIZE;
3031     height = SC_SCROLLBUTTON_YSIZE;
3032
3033     if (id == SCREEN_CTRL_ID_SCROLL_DOWN)
3034       y = mSY + (SC_SCROLL_VERTICAL_YPOS +
3035                  (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE);
3036
3037     gfx_unpressed = scrollbutton_info[i].gfx_unpressed;
3038     gfx_pressed   = scrollbutton_info[i].gfx_pressed;
3039     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
3040     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
3041     gd_x1 = graphic_info[gfx_unpressed].src_x;
3042     gd_y1 = graphic_info[gfx_unpressed].src_y;
3043     gd_x2 = graphic_info[gfx_pressed].src_x;
3044     gd_y2 = graphic_info[gfx_pressed].src_y;
3045
3046     gi = CreateGadget(GDI_CUSTOM_ID, id,
3047                       GDI_CUSTOM_TYPE_ID, i,
3048                       GDI_INFO_TEXT, scrollbutton_info[i].infotext,
3049                       GDI_X, x,
3050                       GDI_Y, y,
3051                       GDI_WIDTH, width,
3052                       GDI_HEIGHT, height,
3053                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
3054                       GDI_STATE, GD_BUTTON_UNPRESSED,
3055                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
3056                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
3057                       GDI_DIRECT_DRAW, FALSE,
3058                       GDI_EVENT_MASK, event_mask,
3059                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
3060                       GDI_END);
3061
3062     if (gi == NULL)
3063       Error(ERR_EXIT, "cannot create gadget");
3064
3065     screen_gadget[id] = gi;
3066   }
3067 }
3068
3069 static void CreateScreenScrollbars()
3070 {
3071   int i;
3072
3073   for (i=0; i<NUM_SCREEN_SCROLLBARS; i++)
3074   {
3075     Bitmap *gd_bitmap_unpressed, *gd_bitmap_pressed;
3076 #if !defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
3077     int gfx_unpressed, gfx_pressed;
3078 #endif
3079     int x, y, width, height;
3080     int gd_x1, gd_x2, gd_y1, gd_y2;
3081     struct GadgetInfo *gi;
3082     int items_max, items_visible, item_position;
3083     unsigned long event_mask;
3084     int num_page_entries = NUM_MENU_ENTRIES_ON_SCREEN;
3085     int id = scrollbar_info[i].gadget_id;
3086
3087     event_mask = GD_EVENT_MOVING | GD_EVENT_OFF_BORDERS;
3088
3089     x = mSX + scrollbar_info[i].x + menu.scrollbar_xoffset;
3090     y = mSY + scrollbar_info[i].y;
3091     width  = scrollbar_info[i].width;
3092     height = scrollbar_info[i].height;
3093
3094     if (id == SCREEN_CTRL_ID_SCROLL_VERTICAL)
3095       height = (NUM_MENU_ENTRIES_ON_SCREEN - 2) * SC_SCROLLBUTTON_YSIZE;
3096
3097     items_max = num_page_entries;
3098     items_visible = num_page_entries;
3099     item_position = 0;
3100
3101 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
3102     gd_bitmap_unpressed = *scrollbar_info[i].gfx_unpressed;
3103     gd_bitmap_pressed   = *scrollbar_info[i].gfx_pressed;
3104     gd_x1 = 0;
3105     gd_y1 = 0;
3106     gd_x2 = 0;
3107     gd_y2 = 0;
3108 #else
3109     gfx_unpressed = scrollbar_info[i].gfx_unpressed;
3110     gfx_pressed   = scrollbar_info[i].gfx_pressed;
3111     gd_bitmap_unpressed = graphic_info[gfx_unpressed].bitmap;
3112     gd_bitmap_pressed   = graphic_info[gfx_pressed].bitmap;
3113     gd_x1 = graphic_info[gfx_unpressed].src_x;
3114     gd_y1 = graphic_info[gfx_unpressed].src_y;
3115     gd_x2 = graphic_info[gfx_pressed].src_x;
3116     gd_y2 = graphic_info[gfx_pressed].src_y;
3117 #endif
3118
3119     gi = CreateGadget(GDI_CUSTOM_ID, id,
3120                       GDI_CUSTOM_TYPE_ID, i,
3121                       GDI_INFO_TEXT, scrollbar_info[i].infotext,
3122                       GDI_X, x,
3123                       GDI_Y, y,
3124                       GDI_WIDTH, width,
3125                       GDI_HEIGHT, height,
3126                       GDI_TYPE, scrollbar_info[i].type,
3127                       GDI_SCROLLBAR_ITEMS_MAX, items_max,
3128                       GDI_SCROLLBAR_ITEMS_VISIBLE, items_visible,
3129                       GDI_SCROLLBAR_ITEM_POSITION, item_position,
3130                       GDI_STATE, GD_BUTTON_UNPRESSED,
3131                       GDI_DESIGN_UNPRESSED, gd_bitmap_unpressed, gd_x1, gd_y1,
3132                       GDI_DESIGN_PRESSED, gd_bitmap_pressed, gd_x2, gd_y2,
3133                       GDI_BORDER_SIZE, SC_BORDER_SIZE, SC_BORDER_SIZE,
3134                       GDI_DIRECT_DRAW, FALSE,
3135                       GDI_EVENT_MASK, event_mask,
3136                       GDI_CALLBACK_ACTION, HandleScreenGadgets,
3137                       GDI_END);
3138
3139     if (gi == NULL)
3140       Error(ERR_EXIT, "cannot create gadget");
3141
3142     screen_gadget[id] = gi;
3143   }
3144 }
3145
3146 void CreateScreenGadgets()
3147 {
3148   int last_game_status = game_status;   /* save current game status */
3149
3150 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
3151   int i;
3152
3153   for (i=0; i < NUM_SCROLLBAR_BITMAPS; i++)
3154   {
3155     scrollbar_bitmap[i] = CreateBitmap(TILEX, TILEY, DEFAULT_DEPTH);
3156
3157     /* copy pointers to clip mask and GC */
3158     scrollbar_bitmap[i]->clip_mask =
3159       graphic_info[IMG_MENU_SCROLLBAR + i].clip_mask;
3160     scrollbar_bitmap[i]->stored_clip_gc =
3161       graphic_info[IMG_MENU_SCROLLBAR + i].clip_gc;
3162
3163     BlitBitmap(graphic_info[IMG_MENU_SCROLLBAR + i].bitmap,
3164                scrollbar_bitmap[i],
3165                graphic_info[IMG_MENU_SCROLLBAR + i].src_x,
3166                graphic_info[IMG_MENU_SCROLLBAR + i].src_y,
3167                TILEX, TILEY, 0, 0);
3168   }
3169 #endif
3170
3171   /* force LEVELS draw offset for scrollbar / scrollbutton gadgets */
3172   game_status = GAME_MODE_LEVELS;
3173
3174   CreateScreenScrollbuttons();
3175   CreateScreenScrollbars();
3176
3177   game_status = last_game_status;       /* restore current game status */
3178 }
3179
3180 void FreeScreenGadgets()
3181 {
3182   int i;
3183
3184 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
3185   for (i=0; i < NUM_SCROLLBAR_BITMAPS; i++)
3186   {
3187     /* prevent freeing clip mask and GC twice */
3188     scrollbar_bitmap[i]->clip_mask = None;
3189     scrollbar_bitmap[i]->stored_clip_gc = None;
3190
3191     FreeBitmap(scrollbar_bitmap[i]);
3192   }
3193 #endif
3194
3195   for (i=0; i<NUM_SCREEN_GADGETS; i++)
3196     FreeGadget(screen_gadget[i]);
3197 }
3198
3199 void MapChooseTreeGadgets(TreeInfo *ti)
3200 {
3201   int num_entries = numTreeInfoInGroup(ti);
3202   int i;
3203
3204   if (num_entries <= NUM_MENU_ENTRIES_ON_SCREEN)
3205     return;
3206
3207   for (i=0; i<NUM_SCREEN_GADGETS; i++)
3208     MapGadget(screen_gadget[i]);
3209 }
3210
3211 void UnmapChooseTreeGadgets()
3212 {
3213   int i;
3214
3215   for (i=0; i<NUM_SCREEN_GADGETS; i++)
3216     UnmapGadget(screen_gadget[i]);
3217 }
3218
3219 static void HandleScreenGadgets(struct GadgetInfo *gi)
3220 {
3221   int id = gi->custom_id;
3222
3223   if (game_status != GAME_MODE_LEVELS && game_status != GAME_MODE_SETUP)
3224     return;
3225
3226   switch (id)
3227   {
3228     case SCREEN_CTRL_ID_SCROLL_UP:
3229       if (game_status == GAME_MODE_LEVELS)
3230         HandleChooseLevel(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
3231       else if (game_status == GAME_MODE_SETUP)
3232         HandleSetupScreen(0,0, 0, -1 * SCROLL_LINE, MB_MENU_MARK);
3233       break;
3234
3235     case SCREEN_CTRL_ID_SCROLL_DOWN:
3236       if (game_status == GAME_MODE_LEVELS)
3237         HandleChooseLevel(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
3238       else if (game_status == GAME_MODE_SETUP)
3239         HandleSetupScreen(0,0, 0, +1 * SCROLL_LINE, MB_MENU_MARK);
3240       break;
3241
3242     case SCREEN_CTRL_ID_SCROLL_VERTICAL:
3243       if (game_status == GAME_MODE_LEVELS)
3244         HandleChooseLevel(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
3245       else if (game_status == GAME_MODE_SETUP)
3246         HandleSetupScreen(0,0, 999,gi->event.item_position,MB_MENU_INITIALIZE);
3247       break;
3248
3249     default:
3250       break;
3251   }
3252 }