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