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