fixed potential off-by-one buffer overflow bug when recording tapes
[rocksndiamonds.git] / src / tape.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // tape.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "tape.h"
15 #include "init.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "files.h"
19 #include "network.h"
20 #include "anim.h"
21
22 #define DEBUG_TAPE_WHEN_PLAYING                 FALSE
23
24 /* tape button identifiers */
25 #define TAPE_CTRL_ID_EJECT                      0
26 #define TAPE_CTRL_ID_EXTRA                      1
27 #define TAPE_CTRL_ID_STOP                       2
28 #define TAPE_CTRL_ID_PAUSE                      3
29 #define TAPE_CTRL_ID_RECORD                     4
30 #define TAPE_CTRL_ID_PLAY                       5
31
32 #define NUM_TAPE_BUTTONS                        6
33
34 /* values for tape handling */
35 #define TAPE_PAUSE_SECONDS_BEFORE_DEATH         5
36
37 /* forward declaration for internal use */
38 static void HandleTapeButtons(struct GadgetInfo *);
39 static void TapeStopWarpForward();
40
41 static struct GadgetInfo *tape_gadget[NUM_TAPE_BUTTONS];
42
43
44 /* ========================================================================= */
45 /* video tape definitions                                                    */
46 /* ========================================================================= */
47
48 #define VIDEO_INFO_OFF                  (VIDEO_STATE_DATE_OFF   |       \
49                                          VIDEO_STATE_TIME_OFF   |       \
50                                          VIDEO_STATE_FRAME_OFF)
51 #define VIDEO_STATE_OFF                 (VIDEO_STATE_PLAY_OFF   |       \
52                                          VIDEO_STATE_REC_OFF    |       \
53                                          VIDEO_STATE_PAUSE_OFF  |       \
54                                          VIDEO_STATE_FFWD_OFF   |       \
55                                          VIDEO_STATE_WARP_OFF   |       \
56                                          VIDEO_STATE_WARP2_OFF  |       \
57                                          VIDEO_STATE_PBEND_OFF  |       \
58                                          VIDEO_STATE_1STEP_OFF)
59 #define VIDEO_PRESS_OFF                 (VIDEO_PRESS_PLAY_OFF   |       \
60                                          VIDEO_PRESS_REC_OFF    |       \
61                                          VIDEO_PRESS_PAUSE_OFF  |       \
62                                          VIDEO_PRESS_STOP_OFF   |       \
63                                          VIDEO_PRESS_EJECT_OFF)
64 #define VIDEO_ALL_OFF                   (VIDEO_INFO_OFF         |       \
65                                          VIDEO_STATE_OFF        |       \
66                                          VIDEO_PRESS_OFF)
67
68 #define VIDEO_INFO_ON                   (VIDEO_STATE_DATE_ON    |       \
69                                          VIDEO_STATE_TIME_ON    |       \
70                                          VIDEO_STATE_FRAME_ON)
71 #define VIDEO_STATE_ON                  (VIDEO_STATE_PLAY_ON    |       \
72                                          VIDEO_STATE_REC_ON     |       \
73                                          VIDEO_STATE_PAUSE_ON   |       \
74                                          VIDEO_STATE_FFWD_ON    |       \
75                                          VIDEO_STATE_WARP_ON    |       \
76                                          VIDEO_STATE_WARP2_ON   |       \
77                                          VIDEO_STATE_PBEND_ON   |       \
78                                          VIDEO_STATE_1STEP_ON)
79 #define VIDEO_PRESS_ON                  (VIDEO_PRESS_PLAY_ON    |       \
80                                          VIDEO_PRESS_REC_ON     |       \
81                                          VIDEO_PRESS_PAUSE_ON   |       \
82                                          VIDEO_PRESS_STOP_ON    |       \
83                                          VIDEO_PRESS_EJECT_ON)
84 #define VIDEO_ALL_ON                    (VIDEO_INFO_ON          |       \
85                                          VIDEO_STATE_ON         |       \
86                                          VIDEO_PRESS_ON)
87
88 #define VIDEO_INFO                      (VIDEO_INFO_ON | VIDEO_INFO_OFF)
89 #define VIDEO_STATE                     (VIDEO_STATE_ON | VIDEO_STATE_OFF)
90 #define VIDEO_PRESS                     (VIDEO_PRESS_ON | VIDEO_PRESS_OFF)
91 #define VIDEO_ALL                       (VIDEO_ALL_ON | VIDEO_ALL_OFF)
92
93 #define NUM_TAPE_FUNCTIONS              11
94 #define NUM_TAPE_FUNCTION_PARTS         2
95 #define NUM_TAPE_FUNCTION_STATES        2
96
97
98 /* ========================================================================= */
99 /* video display functions                                                   */
100 /* ========================================================================= */
101
102 static void DrawVideoDisplay_Graphics(unsigned int state, unsigned int value)
103 {
104   int i, j, k;
105
106   static struct
107   {
108     int graphic;
109     struct XY *pos;
110   }
111   video_pos[NUM_TAPE_FUNCTIONS][NUM_TAPE_FUNCTION_PARTS] =
112   {
113     {
114       { IMG_GFX_TAPE_LABEL_PLAY,                &tape.label.play        },
115       { IMG_GFX_TAPE_SYMBOL_PLAY,               &tape.symbol.play       },
116     },
117     {
118       { IMG_GFX_TAPE_LABEL_RECORD,              &tape.label.record      },
119       { IMG_GFX_TAPE_SYMBOL_RECORD,             &tape.symbol.record     },
120     },
121     {
122       { IMG_GFX_TAPE_LABEL_PAUSE,               &tape.label.pause       },
123       { IMG_GFX_TAPE_SYMBOL_PAUSE,              &tape.symbol.pause      },
124     },
125     {
126       { IMG_GFX_TAPE_LABEL_DATE,                &tape.label.date        },
127       { -1,                                     NULL                    },
128     },
129     {
130       { IMG_GFX_TAPE_LABEL_TIME,                &tape.label.time        },
131       { -1,                                     NULL                    },
132     },
133     {
134       /* (no label for displaying optional frame) */
135       { -1,                                     NULL                    },
136       { -1,                                     NULL                    },
137     },
138     {
139       { IMG_GFX_TAPE_LABEL_FAST_FORWARD,        &tape.label.fast_forward  },
140       { IMG_GFX_TAPE_SYMBOL_FAST_FORWARD,       &tape.symbol.fast_forward },
141     },
142     {
143       { IMG_GFX_TAPE_LABEL_WARP_FORWARD,        &tape.label.warp_forward  },
144       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD,       &tape.symbol.warp_forward },
145     },
146     {
147       { IMG_GFX_TAPE_LABEL_WARP_FORWARD_BLIND,  &tape.label.warp_forward_blind},
148       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD_BLIND, &tape.symbol.warp_forward_blind},
149     },
150     {
151       { IMG_GFX_TAPE_LABEL_PAUSE_BEFORE_END,    &tape.label.pause_before_end  },
152       { IMG_GFX_TAPE_SYMBOL_PAUSE_BEFORE_END,   &tape.symbol.pause_before_end },
153     },
154     {
155       { IMG_GFX_TAPE_LABEL_SINGLE_STEP,         &tape.label.single_step  },
156       { IMG_GFX_TAPE_SYMBOL_SINGLE_STEP,        &tape.symbol.single_step },
157     },
158   };
159
160   for (k = 0; k < NUM_TAPE_FUNCTION_STATES; k++)        /* on or off states */
161   {
162     for (i = 0; i < NUM_TAPE_FUNCTIONS; i++)            /* record, play, ... */
163     {
164       for (j = 0; j < NUM_TAPE_FUNCTION_PARTS; j++)     /* label or symbol */
165       {
166         int graphic = video_pos[i][j].graphic;
167         struct XY *pos = video_pos[i][j].pos;
168
169         if (graphic == -1 ||
170             pos->x == -1 ||
171             pos->y == -1)
172           continue;
173
174         if (state & (1 << (i * 2 + k)))
175         {
176           struct GraphicInfo *gfx_bg = &graphic_info[IMG_BACKGROUND_TAPE];
177           struct GraphicInfo *gfx = &graphic_info[graphic];
178           Bitmap *gd_bitmap;
179           int gd_x, gd_y;
180           int skip_value =
181             (j == 0 ? VIDEO_DISPLAY_SYMBOL_ONLY : VIDEO_DISPLAY_LABEL_ONLY);
182
183           if (value == skip_value)
184             continue;
185
186           if (k == 1)           /* on */
187           {
188             gd_bitmap = gfx->bitmap;
189             gd_x = gfx->src_x;
190             gd_y = gfx->src_y;
191           }
192           else                  /* off */
193           {
194             gd_bitmap = gfx_bg->bitmap;
195             gd_x = gfx_bg->src_x + pos->x;
196             gd_y = gfx_bg->src_y + pos->y;
197           }
198
199           /* some tape graphics may be undefined -- only draw if defined */
200           if (gd_bitmap != NULL)
201             BlitBitmap(gd_bitmap, drawto, gd_x, gd_y, gfx->width, gfx->height,
202                        VX + pos->x, VY + pos->y);
203
204           redraw_mask |= REDRAW_DOOR_2;
205         }
206       }
207     }
208   }
209 }
210
211
212 #define DATETIME_NONE                   (0)
213
214 #define DATETIME_DATE_YYYY              (1 << 0)
215 #define DATETIME_DATE_YY                (1 << 1)
216 #define DATETIME_DATE_MON               (1 << 2)
217 #define DATETIME_DATE_MM                (1 << 3)
218 #define DATETIME_DATE_DD                (1 << 4)
219
220 #define DATETIME_TIME_HH                (1 << 5)
221 #define DATETIME_TIME_MIN               (1 << 6)
222 #define DATETIME_TIME_MM                (1 << 7)
223 #define DATETIME_TIME_SS                (1 << 8)
224
225 #define DATETIME_FRAME                  (1 << 9)
226
227 #define DATETIME_XOFFSET_1              (1 << 10)
228 #define DATETIME_XOFFSET_2              (1 << 11)
229
230 #define DATETIME_DATE                   (DATETIME_DATE_YYYY     |       \
231                                          DATETIME_DATE_YY       |       \
232                                          DATETIME_DATE_MON      |       \
233                                          DATETIME_DATE_MM       |       \
234                                          DATETIME_DATE_DD)
235
236 #define DATETIME_TIME                   (DATETIME_TIME_HH       |       \
237                                          DATETIME_TIME_MIN      |       \
238                                          DATETIME_TIME_MM       |       \
239                                          DATETIME_TIME_SS)
240
241 #define MAX_DATETIME_STRING_SIZE        32
242
243 static void DrawVideoDisplay_DateTime(unsigned int state, unsigned int value)
244 {
245   int i;
246
247   static char *month_shortnames[] =
248   {
249     "JAN",
250     "FEB",
251     "MAR",
252     "APR",
253     "MAY",
254     "JUN",
255     "JUL",
256     "AUG",
257     "SEP",
258     "OCT",
259     "NOV",
260     "DEC"
261   };
262
263   static struct
264   {
265     struct TextPosInfo *pos;
266     int type;
267   }
268   datetime_info[] =
269   {
270     { &tape.text.date,          DATETIME_DATE_DD                        },
271     { &tape.text.date,          DATETIME_DATE_MON | DATETIME_XOFFSET_1  },
272     { &tape.text.date,          DATETIME_DATE_YY  | DATETIME_XOFFSET_2  },
273     { &tape.text.date_yyyy,     DATETIME_DATE_YYYY                      },
274     { &tape.text.date_yy,       DATETIME_DATE_YY                        },
275     { &tape.text.date_mon,      DATETIME_DATE_MON                       },
276     { &tape.text.date_mm,       DATETIME_DATE_MM                        },
277     { &tape.text.date_dd,       DATETIME_DATE_DD                        },
278
279     { &tape.text.time,          DATETIME_TIME_MIN                       },
280     { &tape.text.time,          DATETIME_TIME_SS  | DATETIME_XOFFSET_1  },
281     { &tape.text.time_hh,       DATETIME_TIME_HH                        },
282     { &tape.text.time_mm,       DATETIME_TIME_MM                        },
283     { &tape.text.time_ss,       DATETIME_TIME_SS                        },
284
285     { &tape.text.frame,         DATETIME_FRAME                          },
286
287     { NULL,                     DATETIME_NONE                           },
288   };
289
290   for (i = 0; datetime_info[i].pos != NULL; i++)
291   {
292     struct TextPosInfo *pos = datetime_info[i].pos;
293     int type = datetime_info[i].type;
294     int xpos, ypos;
295
296     if (pos->x == -1 &&
297         pos->y == -1)
298       continue;
299
300     xpos = VX + pos->x + (type & DATETIME_XOFFSET_1 ? pos->xoffset  :
301                           type & DATETIME_XOFFSET_2 ? pos->xoffset2 : 0);
302     ypos = VY + pos->y;
303
304     if ((type & DATETIME_DATE) && (state & VIDEO_STATE_DATE_ON))
305     {
306       char s[MAX_DATETIME_STRING_SIZE];
307       int year2 = value / 10000;
308       int year4 = (year2 < 70 ? 2000 + year2 : 1900 + year2);
309       int month_index = (value / 100) % 100;
310       int month = month_index + 1;
311       int day = value % 100;
312
313       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
314                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
315                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
316                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
317                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
318
319       DrawText(xpos, ypos, s, pos->font);
320     }
321     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
322     {
323       char s[MAX_DATETIME_STRING_SIZE];
324       int hh = (value / 3600) % 100;
325       int min = value / 60;
326       int mm = (value / 60) % 60;
327       int ss = value % 60;
328
329       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
330                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
331                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
332                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
333
334       DrawText(xpos, ypos, s, pos->font);
335     }
336     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
337     {
338       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
339     }
340   }
341 }
342
343 void DrawVideoDisplay(unsigned int state, unsigned int value)
344 {
345   DrawVideoDisplay_Graphics(state, value);
346   DrawVideoDisplay_DateTime(state, value);
347 }
348
349 void DrawVideoDisplayLabel(unsigned int state)
350 {
351   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
352 }
353
354 void DrawVideoDisplaySymbol(unsigned int state)
355 {
356   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
357 }
358
359 void DrawVideoDisplayCurrentState()
360 {
361   int state = 0;
362
363   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
364
365   if (tape.pausing)
366     state |= VIDEO_STATE_PAUSE_ON;
367
368   if (tape.recording)
369   {
370     state |= VIDEO_STATE_REC_ON;
371
372     if (tape.single_step)
373       state |= VIDEO_STATE_1STEP_ON;
374   }
375   else if (tape.playing)
376   {
377     state |= VIDEO_STATE_PLAY_ON;
378
379     if (!tape.pausing)
380     {
381       if (tape.deactivate_display)
382         state |= VIDEO_STATE_WARP2_ON;
383       else if (tape.warp_forward)
384         state |= VIDEO_STATE_WARP_ON;
385       else if (tape.fast_forward)
386         state |= VIDEO_STATE_FFWD_ON;
387
388       if (tape.pause_before_end)
389         state |= VIDEO_STATE_PBEND_ON;
390     }
391   }
392
393   // draw labels and symbols separately to prevent labels overlapping symbols
394   DrawVideoDisplayLabel(state);
395   DrawVideoDisplaySymbol(state);
396 }
397
398 void DrawCompleteVideoDisplay()
399 {
400   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
401
402   /* draw tape background */
403   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
404              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
405
406   /* draw tape buttons (forced) */
407   RedrawOrRemapTapeButtons();
408
409   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
410
411   if (tape.recording)
412   {
413     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
414     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
415     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
416     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
417
418     if (tape.pausing)
419       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
420   }
421   else if (tape.playing)
422   {
423     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
424     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
425     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
426     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
427
428     if (tape.pausing)
429       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
430   }
431   else if (tape.date && tape.length)
432   {
433     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
434     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
435     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
436   }
437
438   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
439              0, 0);
440 }
441
442 void TapeDeactivateDisplayOn()
443 {
444   SetDrawDeactivationMask(REDRAW_FIELD);
445   audio.sound_deactivated = TRUE;
446 }
447
448 void TapeDeactivateDisplayOff(boolean redraw_display)
449 {
450   SetDrawDeactivationMask(REDRAW_NONE);
451   audio.sound_deactivated = FALSE;
452
453   if (redraw_display)
454   {
455     RedrawPlayfield();
456     DrawGameDoorValues();
457   }
458 }
459
460
461 /* ========================================================================= */
462 /* tape logging functions                                                    */
463 /* ========================================================================= */
464
465 void PrintTapeReplayProgress(boolean replay_finished)
466 {
467   static unsigned int counter_last = -1;
468   unsigned int counter = Counter();
469   unsigned int counter_seconds  = counter / 1000;
470
471   if (!replay_finished)
472   {
473     unsigned int counter_delay = 50;
474
475     if (counter > counter_last + counter_delay)
476     {
477       PrintNoLog("\r");
478       PrintNoLog("Level %03d [%02d:%02d]: [%02d:%02d] - playing tape ... ",
479                  level_nr, tape.length_seconds / 60, tape.length_seconds % 60,
480                  TapeTime / 60, TapeTime % 60);
481
482       counter_last = counter;
483     }
484   }
485   else
486   {
487     PrintNoLog("\r");
488     Print("Level %03d [%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
489           level_nr, tape.length_seconds / 60, tape.length_seconds % 60,
490           counter_seconds / 60, counter_seconds % 60, counter % 1000,
491           (float)counter / tape.length_seconds / 10,
492           tape.auto_play_level_solved ? "solved" : "NOT SOLVED");
493
494     counter_last = -1;
495   }
496 }
497
498
499 /* ========================================================================= */
500 /* tape control functions                                                    */
501 /* ========================================================================= */
502
503 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
504 {
505   struct tm *lt = localtime(&epoch_seconds);
506
507   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
508 }
509
510 void TapeSetDateFromNow()
511 {
512   TapeSetDateFromEpochSeconds(time(NULL));
513 }
514
515 void TapeErase()
516 {
517   int i;
518
519   tape.counter = 0;
520   tape.length = 0;
521   tape.length_frames = 0;
522   tape.length_seconds = 0;
523
524   if (leveldir_current)
525     setString(&tape.level_identifier, leveldir_current->identifier);
526
527   tape.level_nr = level_nr;
528   tape.pos[tape.counter].delay = 0;
529   tape.changed = TRUE;
530
531   tape.random_seed = InitRND(level.random_seed);
532
533   tape.file_version = FILE_VERSION_ACTUAL;
534   tape.game_version = GAME_VERSION_ACTUAL;
535   tape.engine_version = level.game_version;
536
537   TapeSetDateFromNow();
538
539   for (i = 0; i < MAX_PLAYERS; i++)
540     tape.player_participates[i] = FALSE;
541
542   tape.centered_player_nr_next = -1;
543   tape.set_centered_player = FALSE;
544 }
545
546 static void TapeRewind()
547 {
548   tape.counter = 0;
549   tape.delay_played = 0;
550   tape.pause_before_end = FALSE;
551   tape.recording = FALSE;
552   tape.playing = FALSE;
553   tape.fast_forward = FALSE;
554   tape.warp_forward = FALSE;
555   tape.deactivate_display = FALSE;
556   tape.auto_play = (global.autoplay_leveldir != NULL);
557   tape.auto_play_level_solved = FALSE;
558   tape.quick_resume = FALSE;
559   tape.single_step = FALSE;
560
561   tape.centered_player_nr_next = -1;
562   tape.set_centered_player = FALSE;
563
564   InitRND(tape.random_seed);
565 }
566
567 static void TapeSetRandomSeed(int random_seed)
568 {
569   tape.random_seed = InitRND(random_seed);
570 }
571
572 void TapeStartRecording(int random_seed)
573 {
574   if (!TAPE_IS_STOPPED(tape))
575     TapeStop();
576
577   TapeErase();
578   TapeRewind();
579   TapeSetRandomSeed(random_seed);
580
581   tape.recording = TRUE;
582
583   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
584   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
585   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
586   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
587
588   MapTapeWarpButton();
589
590   SetDrawDeactivationMask(REDRAW_NONE);
591   audio.sound_deactivated = FALSE;
592 }
593
594 static void TapeStartGameRecording()
595 {
596   TapeStartRecording(level.random_seed);
597
598 #if defined(NETWORK_AVALIABLE)
599   if (options.network)
600   {
601     SendToServer_StartPlaying();
602
603     return;
604   }
605 #endif
606
607   InitGame();
608 }
609
610 static void TapeAppendRecording()
611 {
612   if (!tape.playing || !tape.pausing)
613     return;
614
615   // stop playing
616   tape.playing = FALSE;
617   tape.fast_forward = FALSE;
618   tape.warp_forward = FALSE;
619   tape.pause_before_end = FALSE;
620   tape.deactivate_display = FALSE;
621
622   // start recording
623   tape.recording = TRUE;
624   tape.changed = TRUE;
625
626   // set current delay (for last played move)
627   tape.pos[tape.counter].delay = tape.delay_played;
628
629   // set current date
630   TapeSetDateFromNow();
631
632   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
633   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
634
635   UpdateAndDisplayGameControlValues();
636 }
637
638 void TapeHaltRecording()
639 {
640   if (!tape.recording)
641     return;
642
643   tape.counter++;
644
645   // initialize delay for next tape entry (to be able to continue recording)
646   if (tape.counter < MAX_TAPE_LEN)
647     tape.pos[tape.counter].delay = 0;
648
649   tape.length = tape.counter;
650   tape.length_frames = GetTapeLengthFrames();
651   tape.length_seconds = GetTapeLengthSeconds();
652 }
653
654 void TapeStopRecording()
655 {
656   TapeHaltRecording();
657
658   tape.recording = FALSE;
659   tape.pausing = FALSE;
660
661   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
662   MapTapeEjectButton();
663 }
664
665 void TapeRecordAction(byte action_raw[MAX_PLAYERS])
666 {
667   byte action[MAX_PLAYERS];
668   int i;
669
670   if (!tape.recording)          /* (record action even when tape is paused) */
671     return;
672
673   if (tape.counter >= MAX_TAPE_LEN - 1)
674   {
675     TapeStopRecording();
676     return;
677   }
678
679   for (i = 0; i < MAX_PLAYERS; i++)
680     action[i] = action_raw[i];
681
682   if (tape.set_centered_player)
683   {
684     for (i = 0; i < MAX_PLAYERS; i++)
685       if (tape.centered_player_nr_next == i ||
686           tape.centered_player_nr_next == -1)
687         action[i] |= KEY_SET_FOCUS;
688
689     tape.set_centered_player = FALSE;
690   }
691
692   if (tape.pos[tape.counter].delay > 0)         /* already stored action */
693   {
694     boolean changed_events = FALSE;
695
696     for (i = 0; i < MAX_PLAYERS; i++)
697       if (tape.pos[tape.counter].action[i] != action[i])
698         changed_events = TRUE;
699
700     if (changed_events || tape.pos[tape.counter].delay >= 255)
701     {
702       tape.counter++;
703       tape.pos[tape.counter].delay = 0;
704     }
705     else
706       tape.pos[tape.counter].delay++;
707   }
708
709   if (tape.pos[tape.counter].delay == 0)        /* store new action */
710   {
711     for (i = 0; i < MAX_PLAYERS; i++)
712       tape.pos[tape.counter].action[i] = action[i];
713
714     tape.pos[tape.counter].delay++;
715   }
716 }
717
718 void TapeTogglePause(boolean toggle_mode)
719 {
720   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
721   {
722     // continue playing in normal mode
723     tape.fast_forward = FALSE;
724     tape.warp_forward = FALSE;
725     tape.deactivate_display = FALSE;
726
727     tape.pause_before_end = FALSE;
728   }
729
730   tape.pausing = !tape.pausing;
731
732   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
733     tape.single_step = FALSE;
734
735   DrawVideoDisplayCurrentState();
736
737   if (tape.deactivate_display)
738   {
739     if (tape.pausing)
740       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
741     else
742       TapeDeactivateDisplayOn();
743   }
744
745   if (tape.quick_resume)
746   {
747     tape.quick_resume = FALSE;
748
749     TapeStopWarpForward();
750     TapeAppendRecording();
751
752     if (!CheckEngineSnapshotSingle())
753       SaveEngineSnapshotSingle();
754
755     // restart step/move snapshots after quick loading tape
756     SaveEngineSnapshotToListInitial();
757
758     // do not map undo/redo buttons after quick loading tape
759     return;
760   }
761
762   if (setup.show_snapshot_buttons &&
763       game_status == GAME_MODE_PLAYING &&
764       CheckEngineSnapshotList())
765   {
766     if (tape.pausing)
767       MapUndoRedoButtons();
768     else if (!tape.single_step)
769       UnmapUndoRedoButtons();
770   }
771 }
772
773 void TapeStartPlaying()
774 {
775   if (TAPE_IS_EMPTY(tape))
776     return;
777
778   if (!TAPE_IS_STOPPED(tape))
779     TapeStop();
780
781   TapeRewind();
782
783   tape.playing = TRUE;
784
785   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
786   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
787   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
788   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
789
790   MapTapeWarpButton();
791
792   SetDrawDeactivationMask(REDRAW_NONE);
793   audio.sound_deactivated = FALSE;
794 }
795
796 static void TapeStartGamePlaying()
797 {
798   TapeStartPlaying();
799
800   InitGame();
801 }
802
803 void TapeStopPlaying()
804 {
805   tape.playing = FALSE;
806   tape.pausing = FALSE;
807
808   if (tape.warp_forward)
809     TapeStopWarpForward();
810
811   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
812   MapTapeEjectButton();
813 }
814
815 byte *TapePlayAction()
816 {
817   int update_delay = FRAMES_PER_SECOND / 2;
818   boolean update_video_display = (FrameCounter % update_delay == 0);
819   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
820   static byte action[MAX_PLAYERS];
821   int i;
822
823   if (!tape.playing || tape.pausing)
824     return NULL;
825
826   if (tape.pause_before_end)  // stop some seconds before end of tape
827   {
828     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
829     {
830       TapeStopWarpForward();
831       TapeTogglePause(TAPE_TOGGLE_MANUAL);
832
833       return NULL;
834     }
835   }
836
837   if (tape.counter >= tape.length)      /* end of tape reached */
838   {
839     if (tape.warp_forward && !tape.auto_play)
840     {
841       TapeStopWarpForward();
842       TapeTogglePause(TAPE_TOGGLE_MANUAL);
843     }
844     else
845     {
846       TapeStop();
847     }
848
849     return NULL;
850   }
851
852   if (update_video_display && !tape.deactivate_display)
853   {
854     int state = 0;
855
856     if (tape.warp_forward)
857       state |= VIDEO_STATE_WARP(update_draw_label_on);
858     else if (tape.fast_forward)
859       state |= VIDEO_STATE_FFWD(update_draw_label_on);
860
861     if (tape.pause_before_end)
862       state |= VIDEO_STATE_PBEND(update_draw_label_on);
863
864     // draw labels and symbols separately to prevent labels overlapping symbols
865     DrawVideoDisplayLabel(state);
866     DrawVideoDisplaySymbol(state);
867   }
868
869   for (i = 0; i < MAX_PLAYERS; i++)
870     action[i] = tape.pos[tape.counter].action[i];
871
872 #if DEBUG_TAPE_WHEN_PLAYING
873   printf("%05d", FrameCounter);
874   for (i = 0; i < MAX_PLAYERS; i++)
875     printf("   %08x", action[i]);
876   printf("\n");
877 #endif
878
879   tape.set_centered_player = FALSE;
880   tape.centered_player_nr_next = -999;
881
882   for (i = 0; i < MAX_PLAYERS; i++)
883   {
884     if (action[i] & KEY_SET_FOCUS)
885     {
886       tape.set_centered_player = TRUE;
887       tape.centered_player_nr_next =
888         (tape.centered_player_nr_next == -999 ? i : -1);
889     }
890
891     action[i] &= ~KEY_SET_FOCUS;
892   }
893
894   tape.delay_played++;
895   if (tape.delay_played >= tape.pos[tape.counter].delay)
896   {
897     tape.counter++;
898     tape.delay_played = 0;
899   }
900
901   if (tape.auto_play)
902     PrintTapeReplayProgress(FALSE);
903
904   return action;
905 }
906
907 void TapeStop()
908 {
909   TapeStopRecording();
910   TapeStopPlaying();
911
912   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
913
914   if (tape.date && tape.length)
915   {
916     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
917     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
918     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
919   }
920 }
921
922 unsigned int GetTapeLengthFrames()
923 {
924   unsigned int tape_length_frames = 0;
925   int i;
926
927   if (TAPE_IS_EMPTY(tape))
928     return(0);
929
930   for (i = 0; i < tape.length; i++)
931     tape_length_frames += tape.pos[i].delay;
932
933   return tape_length_frames;
934 }
935
936 unsigned int GetTapeLengthSeconds()
937 {
938   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
939 }
940
941 static void TapeStartWarpForward(int mode)
942 {
943   tape.fast_forward = (mode & AUTOPLAY_FFWD);
944   tape.warp_forward = (mode & AUTOPLAY_WARP);
945   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
946
947   tape.pausing = FALSE;
948
949   if (tape.deactivate_display)
950     TapeDeactivateDisplayOn();
951
952   DrawVideoDisplayCurrentState();
953 }
954
955 static void TapeStopWarpForward()
956 {
957   tape.fast_forward = FALSE;
958   tape.warp_forward = FALSE;
959   tape.deactivate_display = FALSE;
960
961   tape.pause_before_end = FALSE;
962
963   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
964
965   DrawVideoDisplayCurrentState();
966 }
967
968 static void TapeSingleStep()
969 {
970   if (options.network)
971     return;
972
973   if (!tape.pausing)
974     TapeTogglePause(TAPE_TOGGLE_MANUAL);
975
976   tape.single_step = !tape.single_step;
977
978   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
979 }
980
981 void TapeQuickSave()
982 {
983   if (game_status == GAME_MODE_MAIN)
984   {
985     Request("No game that can be saved!", REQ_CONFIRM);
986
987     return;
988   }
989
990   if (game_status != GAME_MODE_PLAYING)
991     return;
992
993   if (tape.recording)
994     TapeHaltRecording();        /* prepare tape for saving on-the-fly */
995
996   if (TAPE_IS_EMPTY(tape))
997   {
998     Request("No tape that can be saved!", REQ_CONFIRM);
999
1000     return;
1001   }
1002
1003   if (SaveTapeChecked(tape.level_nr))
1004     SaveEngineSnapshotSingle();
1005 }
1006
1007 void TapeQuickLoad()
1008 {
1009   char *filename = getTapeFilename(level_nr);
1010
1011   if (!fileExists(filename))
1012   {
1013     Request("No tape for this level!", REQ_CONFIRM);
1014
1015     return;
1016   }
1017
1018   if (tape.recording && !Request("Stop recording and load tape?",
1019                                  REQ_ASK | REQ_STAY_CLOSED))
1020   {
1021     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1022
1023     return;
1024   }
1025
1026   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1027     return;
1028
1029   if (CheckEngineSnapshotSingle())
1030   {
1031     TapeStartGamePlaying();
1032
1033     LoadEngineSnapshotSingle();
1034
1035     DrawCompleteVideoDisplay();
1036
1037     tape.playing = TRUE;
1038     tape.pausing = TRUE;
1039
1040     TapeStopWarpForward();
1041     TapeAppendRecording();
1042
1043     // restart step/move snapshots after quick loading tape
1044     SaveEngineSnapshotToListInitial();
1045
1046     if (FrameCounter > 0)
1047       return;
1048   }
1049
1050   TapeStop();
1051   TapeErase();
1052
1053   LoadTape(level_nr);
1054
1055   if (!TAPE_IS_EMPTY(tape))
1056   {
1057     TapeStartGamePlaying();
1058     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1059
1060     tape.quick_resume = TRUE;
1061   }
1062   else  /* this should not happen (basically checked above) */
1063   {
1064     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1065
1066     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1067   }
1068 }
1069
1070 void InsertSolutionTape()
1071 {
1072   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1073                             level.native_sp_level->demo.is_available);
1074
1075   if (!fileExists(getSolutionTapeFilename(level_nr)) && !level_has_tape)
1076   {
1077     Request("No solution tape for this level!", REQ_CONFIRM);
1078
1079     return;
1080   }
1081
1082   // if tape recorder already contains a tape, remove it without asking
1083   TapeErase();
1084
1085   LoadSolutionTape(level_nr);
1086
1087   if (TAPE_IS_EMPTY(tape))
1088     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1089
1090   DrawCompleteVideoDisplay();
1091 }
1092
1093
1094 /* ------------------------------------------------------------------------- *
1095  * tape autoplay functions
1096  * ------------------------------------------------------------------------- */
1097
1098 void AutoPlayTape()
1099 {
1100   static LevelDirTree *autoplay_leveldir = NULL;
1101   static boolean autoplay_initialized = FALSE;
1102   static int autoplay_level_nr = -1;
1103   static int num_levels_played = 0;
1104   static int num_levels_solved = 0;
1105   static int num_tape_missing = 0;
1106   static boolean level_failed[MAX_TAPES_PER_SET];
1107   int i;
1108
1109   if (autoplay_initialized)
1110   {
1111     /* just finished auto-playing tape */
1112     PrintTapeReplayProgress(TRUE);
1113
1114     num_levels_played++;
1115
1116     if (tape.auto_play_level_solved)
1117       num_levels_solved++;
1118     else if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1119       level_failed[level_nr] = TRUE;
1120   }
1121   else
1122   {
1123     DrawCompleteVideoDisplay();
1124
1125     audio.sound_enabled = FALSE;
1126     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1127
1128     autoplay_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1129                                                   global.autoplay_leveldir);
1130
1131     if (autoplay_leveldir == NULL)
1132       Error(ERR_EXIT, "no such level identifier: '%s'",
1133             global.autoplay_leveldir);
1134
1135     leveldir_current = autoplay_leveldir;
1136
1137     if (autoplay_leveldir->first_level < 0)
1138       autoplay_leveldir->first_level = 0;
1139     if (autoplay_leveldir->last_level >= MAX_TAPES_PER_SET)
1140       autoplay_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1141
1142     autoplay_level_nr = autoplay_leveldir->first_level;
1143
1144     PrintLine("=", 79);
1145     Print("Automatically playing level tapes\n");
1146     PrintLine("-", 79);
1147     Print("Level series identifier: '%s'\n", autoplay_leveldir->identifier);
1148     Print("Level series name:       '%s'\n", autoplay_leveldir->name);
1149     Print("Level series author:     '%s'\n", autoplay_leveldir->author);
1150     Print("Number of levels:        %d\n",   autoplay_leveldir->levels);
1151     PrintLine("=", 79);
1152     Print("\n");
1153
1154     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1155       level_failed[i] = FALSE;
1156
1157     autoplay_initialized = TRUE;
1158   }
1159
1160   while (autoplay_level_nr <= autoplay_leveldir->last_level)
1161   {
1162     level_nr = autoplay_level_nr++;
1163
1164     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1165       continue;
1166
1167     TapeErase();
1168
1169     LoadLevel(level_nr);
1170
1171     if (level.no_level_file || level.no_valid_file)
1172     {
1173       Print("Level %03d: (no level)\n", level_nr);
1174
1175       continue;
1176     }
1177
1178 #if 0
1179     /* ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY */
1180     Print("Level %03d: (only testing level)\n", level_nr);
1181     continue;
1182 #endif
1183
1184     if (options.mytapes)
1185       LoadTape(level_nr);
1186     else
1187       LoadSolutionTape(level_nr);
1188
1189     if (tape.no_valid_file)
1190     {
1191       num_tape_missing++;
1192
1193       Print("Level %03d: (no tape)\n", level_nr);
1194
1195       continue;
1196     }
1197
1198     InitCounter();
1199
1200     TapeStartGamePlaying();
1201     TapeStartWarpForward(global.autoplay_mode);
1202
1203     return;
1204   }
1205
1206   Print("\n");
1207   PrintLine("=", 79);
1208   Print("Number of levels played: %d\n", num_levels_played);
1209   Print("Number of levels solved: %d (%d%%)\n", num_levels_solved,
1210          (num_levels_played ? num_levels_solved * 100 / num_levels_played :0));
1211   PrintLine("-", 79);
1212   Print("Summary (for automatic parsing by scripts):\n");
1213   Print("LEVELDIR '%s', SOLVED %d/%d (%d%%)",
1214          autoplay_leveldir->identifier, num_levels_solved, num_levels_played,
1215          (num_levels_played ? num_levels_solved * 100 / num_levels_played :0));
1216
1217   if (num_levels_played != num_levels_solved)
1218   {
1219     Print(", FAILED:");
1220     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1221       if (level_failed[i])
1222         Print(" %03d", i);
1223   }
1224
1225   Print("\n");
1226   PrintLine("=", 79);
1227
1228   CloseAllAndExit(0);
1229 }
1230
1231
1232 /* ---------- new tape button stuff ---------------------------------------- */
1233
1234 static struct
1235 {
1236   int graphic;
1237   struct XY *pos;
1238   int gadget_id;
1239   char *infotext;
1240 } tapebutton_info[NUM_TAPE_BUTTONS] =
1241 {
1242   {
1243     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1244     TAPE_CTRL_ID_EJECT,                 "eject tape"
1245   },
1246   {
1247     /* (same position as "eject" button) */
1248     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1249     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1250   },
1251   {
1252     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1253     TAPE_CTRL_ID_STOP,                  "stop tape"
1254   },
1255   {
1256     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1257     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1258   },
1259   {
1260     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1261     TAPE_CTRL_ID_RECORD,                "record tape"
1262   },
1263   {
1264     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1265     TAPE_CTRL_ID_PLAY,                  "play tape"
1266   }
1267 };
1268
1269 void CreateTapeButtons()
1270 {
1271   int i;
1272
1273   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1274   {
1275     struct GraphicInfo *gfx = &graphic_info[tapebutton_info[i].graphic];
1276     struct XY *pos = tapebutton_info[i].pos;
1277     struct GadgetInfo *gi;
1278     int gd_x = gfx->src_x;
1279     int gd_y = gfx->src_y;
1280     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1281     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1282     int id = i;
1283
1284     gi = CreateGadget(GDI_CUSTOM_ID, id,
1285                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
1286                       GDI_X, VX + pos->x,
1287                       GDI_Y, VY + pos->y,
1288                       GDI_WIDTH, gfx->width,
1289                       GDI_HEIGHT, gfx->height,
1290                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
1291                       GDI_STATE, GD_BUTTON_UNPRESSED,
1292                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
1293                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
1294                       GDI_DIRECT_DRAW, FALSE,
1295                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
1296                       GDI_CALLBACK_ACTION, HandleTapeButtons,
1297                       GDI_END);
1298
1299     if (gi == NULL)
1300       Error(ERR_EXIT, "cannot create gadget");
1301
1302     tape_gadget[id] = gi;
1303   }
1304 }
1305
1306 void FreeTapeButtons()
1307 {
1308   int i;
1309
1310   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1311     FreeGadget(tape_gadget[i]);
1312 }
1313
1314 void MapTapeEjectButton()
1315 {
1316   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1317   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1318 }
1319
1320 void MapTapeWarpButton()
1321 {
1322   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1323   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1324 }
1325
1326 void MapTapeButtons()
1327 {
1328   int i;
1329
1330   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1331     if (i != TAPE_CTRL_ID_EXTRA)
1332       MapGadget(tape_gadget[i]);
1333
1334   if (tape.recording || tape.playing)
1335     MapTapeWarpButton();
1336
1337   if (tape.show_game_buttons)
1338     MapGameButtons();
1339 }
1340
1341 void UnmapTapeButtons()
1342 {
1343   int i;
1344
1345   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1346     UnmapGadget(tape_gadget[i]);
1347
1348   if (tape.show_game_buttons)
1349     UnmapGameButtons();
1350 }
1351
1352 void RedrawTapeButtons()
1353 {
1354   int i;
1355
1356   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1357     RedrawGadget(tape_gadget[i]);
1358
1359   if (tape.show_game_buttons)
1360     RedrawGameButtons();
1361
1362   // RedrawGadget() may have set REDRAW_ALL if buttons are defined off-area
1363   redraw_mask &= ~REDRAW_ALL;
1364 }
1365
1366 void RedrawOrRemapTapeButtons()
1367 {
1368   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
1369   {
1370     // tape buttons already mapped
1371     RedrawTapeButtons();
1372   }
1373   else
1374   {
1375     UnmapTapeButtons();
1376     MapTapeButtons();
1377   }
1378 }
1379
1380 static void HandleTapeButtonsExt(int id)
1381 {
1382   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
1383     return;
1384
1385   switch (id)
1386   {
1387     case TAPE_CTRL_ID_EJECT:
1388       TapeStop();
1389
1390       if (TAPE_IS_EMPTY(tape))
1391       {
1392         LoadTape(level_nr);
1393
1394         if (TAPE_IS_EMPTY(tape))
1395           Request("No tape for this level!", REQ_CONFIRM);
1396       }
1397       else
1398       {
1399         if (tape.changed)
1400           SaveTapeChecked(level_nr);
1401
1402         TapeErase();
1403       }
1404
1405       DrawCompleteVideoDisplay();
1406       break;
1407
1408     case TAPE_CTRL_ID_EXTRA:
1409       if (tape.playing)
1410       {
1411         tape.pause_before_end = !tape.pause_before_end;
1412
1413         DrawVideoDisplayCurrentState();
1414       }
1415       else if (tape.recording)
1416       {
1417         TapeSingleStep();
1418       }
1419
1420       break;
1421
1422     case TAPE_CTRL_ID_STOP:
1423       TapeStop();
1424
1425       break;
1426
1427     case TAPE_CTRL_ID_PAUSE:
1428       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1429
1430       break;
1431
1432     case TAPE_CTRL_ID_RECORD:
1433       if (TAPE_IS_STOPPED(tape))
1434       {
1435         TapeStartGameRecording();
1436       }
1437       else if (tape.pausing)
1438       {
1439         if (tape.playing)                       /* PLAY -> PAUSE -> RECORD */
1440           TapeAppendRecording();
1441         else
1442           TapeTogglePause(TAPE_TOGGLE_MANUAL);
1443       }
1444
1445       break;
1446
1447     case TAPE_CTRL_ID_PLAY:
1448       if (tape.recording && tape.pausing)       /* PAUSE -> RECORD */
1449       {
1450         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
1451
1452         TapeTogglePause(TAPE_TOGGLE_MANUAL);
1453       }
1454
1455       if (TAPE_IS_EMPTY(tape))
1456         break;
1457
1458       if (TAPE_IS_STOPPED(tape))
1459       {
1460         TapeStartGamePlaying();
1461       }
1462       else if (tape.playing)
1463       {
1464         if (tape.pausing)                       /* PAUSE -> PLAY */
1465         {
1466           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
1467         }
1468         else if (!tape.fast_forward)            /* PLAY -> FFWD */
1469         {
1470           tape.fast_forward = TRUE;
1471         }
1472         else if (!tape.warp_forward)            /* FFWD -> WARP */
1473         {
1474           tape.warp_forward = TRUE;
1475         }
1476         else if (!tape.deactivate_display)      /* WARP -> WARP BLIND */
1477         {
1478           tape.deactivate_display = TRUE;
1479
1480           TapeDeactivateDisplayOn();
1481         }
1482         else                                    /* WARP BLIND -> PLAY */
1483         {
1484           tape.fast_forward = FALSE;
1485           tape.warp_forward = FALSE;
1486           tape.deactivate_display = FALSE;
1487
1488           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1489         }
1490
1491         DrawVideoDisplayCurrentState();
1492       }
1493
1494       break;
1495
1496     default:
1497       break;
1498   }
1499 }
1500
1501 static void HandleTapeButtons(struct GadgetInfo *gi)
1502 {
1503   HandleTapeButtonsExt(gi->custom_id);
1504 }
1505
1506 void HandleTapeButtonKeys(Key key)
1507 {
1508   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
1509   boolean extra_button_is_active = !eject_button_is_active;
1510
1511   if (key == setup.shortcut.tape_eject && eject_button_is_active)
1512     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
1513   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
1514     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
1515   else if (key == setup.shortcut.tape_stop)
1516     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
1517   else if (key == setup.shortcut.tape_pause)
1518     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
1519   else if (key == setup.shortcut.tape_record)
1520     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
1521   else if (key == setup.shortcut.tape_play)
1522     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
1523 }