]> Shamusworld >> Repos - apple2/blob - src/apple2.cpp
Added new config icon.
[apple2] / src / apple2.cpp
1 //
2 // Apple 2 SDL Portable Apple Emulator
3 //
4 // by James Hammons
5 // © 2014 Underground Software
6 //
7 // Loosely based on AppleWin by Tom Charlesworth which was based on AppleWin by
8 // Oliver Schmidt which was based on AppleWin by Michael O'Brien. :-) Parts are
9 // also derived from ApplePC. Too bad it was closed source--it could have been
10 // *the* premier Apple II emulator out there.
11 //
12 // JLH = James Hammons <jlhamm@acm.org>
13 //
14 // WHO  WHEN        WHAT
15 // ---  ----------  ------------------------------------------------------------
16 // JLH  11/12/2005  Initial port to SDL
17 // JLH  11/18/2005  Wired up graphic soft switches
18 // JLH  12/02/2005  Setup timer subsystem for more accurate time keeping
19 // JLH  12/12/2005  Added preliminary state saving support
20 // JLH  09/24/2013  Added //e support
21 //
22
23 // STILL TO DO:
24 //
25 // - Port to SDL [DONE]
26 // - GUI goodies
27 // - Weed out unneeded functions [DONE]
28 // - Disk I/O [DONE]
29 // - 128K IIe related stuff [DONE]
30 // - State loading/saving
31 //
32
33 #include "apple2.h"
34
35 #include <SDL2/SDL.h>
36 #include <fstream>
37 #include <string>
38 #include <iomanip>
39 #include <iostream>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <time.h>
43 #include "log.h"
44 #include "video.h"
45 #include "sound.h"
46 #include "settings.h"
47 #include "v65c02.h"
48 #include "applevideo.h"
49 #include "timing.h"
50 #include "floppy.h"
51 #include "firmware.h"
52 #include "mmu.h"
53
54 #include "gui/gui.h"
55
56 // Debug and misc. defines
57
58 #define THREADED_65C02
59 #define CPU_THREAD_OVERFLOW_COMPENSATION
60 #define DEBUG_LC
61 //#define CPU_CLOCK_CHECKING
62 //#define THREAD_DEBUGGING
63 #define SOFT_SWITCH_DEBUGGING
64
65 // Global variables
66
67 uint8_t ram[0x10000], rom[0x10000];                     // RAM & ROM spaces
68 uint8_t ram2[0x10000];                                          // Auxillary RAM
69 //uint8_t diskRom[0x100];                                               // Disk ROM space
70 V65C02REGS mainCPU;                                                     // v65C02 execution context
71 uint8_t appleType = APPLE_TYPE_IIE;
72 FloppyDrive floppyDrive;
73 //bool powerOnState = true;                                     // Virtual power switch
74 bool powerStateChangeRequested = false;
75
76 // Local variables
77
78 uint8_t lastKeyPressed = 0;
79 bool keyDown = false;
80 bool openAppleDown = false;
81 bool closedAppleDown = false;
82 bool store80Mode = false;
83 bool vbl = false;
84 bool slotCXROM = false;
85 bool slotC3ROM = false;
86 bool ramrd = false;
87 bool ramwrt = false;
88 bool altzp = false;
89 bool ioudis = true;
90 bool dhires = false;
91 // Language card state (ROM read, no write)
92 uint8_t lcState = 0x02;
93
94 static bool running = true;                                     // Machine running state flag...
95 static uint32_t startTicks;
96 static bool pauseMode = false;
97 static bool fullscreenDebounce = false;
98 static bool capsLock = false;
99 static bool capsLockDebounce = false;
100
101 // Local functions (technically, they're global...)
102
103 bool LoadImg(char * filename, uint8_t * ram, int size);
104 static void SaveApple2State(const char * filename);
105 static bool LoadApple2State(const char * filename);
106 static void ResetApple2State(void);
107
108 // Local timer callback functions
109
110 static void FrameCallback(void);
111 static void BlinkTimer(void);
112
113 #ifdef THREADED_65C02
114 // Test of threaded execution of 6502
115 static SDL_Thread * cpuThread = NULL;
116 //static SDL_mutex * cpuMutex = NULL;
117 static SDL_cond * cpuCond = NULL;
118 static SDL_sem * mainSem = NULL;
119 static bool cpuFinished = false;
120 static bool cpuSleep = false;
121
122 // NB: Apple //e Manual sez 6502 is running @ 1,022,727 Hz
123
124 // Let's try a thread...
125 /*
126 Here's how it works: Execute 1 frame's worth, then sleep.
127 Other stuff wakes it up
128 */
129 int CPUThreadFunc(void * data)
130 {
131         // Mutex must be locked for conditional to work...
132         // Also, must be created in the thread that uses it...
133         SDL_mutex * cpuMutex = SDL_CreateMutex();
134
135 // decrement mainSem...
136 //SDL_SemWait(mainSem);
137 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
138         float overflow = 0.0;
139 #endif
140
141         do
142         {
143                 if (cpuSleep)
144                         SDL_CondWait(cpuCond, cpuMutex);
145
146 // decrement mainSem...
147 #ifdef THREAD_DEBUGGING
148 WriteLog("CPU: SDL_SemWait(mainSem);\n");
149 #endif
150 SDL_SemWait(mainSem);
151
152 // There are exactly 800 slices of 21.333 cycles per frame, so it works out
153 // evenly.
154 #if 0
155                 uint32_t cycles = 17066;
156 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
157 // ODD! It's closer *without* this overflow compensation. ??? WHY ???
158                 overflow += 0.666666667;
159
160                 if (overflow > 1.0)
161                 {
162                         overflow -= 1.0;
163                         cycles++;
164                 }
165 #endif
166
167 #ifdef THREAD_DEBUGGING
168 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
169 #endif
170                 Execute65C02(&mainCPU, cycles); // how much? 1 frame (after 1 s, off by 40 cycles) not any more--it's off by as much as 240 now!
171
172                 // Adjust the sound routine's last cycle toggled time base
173                 // Also, since we're finished executing, .clock is now valid
174 #ifdef THREAD_DEBUGGING
175 WriteLog("CPU: AdjustLastToggleCycles(mainCPU.clock);\n");
176 #endif
177                 AdjustLastToggleCycles(mainCPU.clock);
178 #else
179 #ifdef THREAD_DEBUGGING
180 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
181 #endif
182                 for(int i=0; i<800; i++)
183                 {
184                         uint32_t cycles = 21;
185                         overflow += 0.333333334;
186
187                         if (overflow > 1.0)
188                         {
189                                 cycles++;
190                                 overflow -= 1.0;
191                         }
192
193                         Execute65C02(&mainCPU, cycles);
194                         WriteSampleToBuffer();
195
196                         // Dunno if this is correct (seems to be close enough)...
197                         vbl = (i < 670 ? true : false);
198                 }
199 #endif
200
201 #ifdef THREAD_DEBUGGING
202 WriteLog("CPU: SDL_mutexP(cpuMutex);\n");
203 #endif
204                 SDL_mutexP(cpuMutex);
205 // increment mainSem...
206 #ifdef THREAD_DEBUGGING
207 WriteLog("CPU: SDL_SemPost(mainSem);\n");
208 #endif
209                 SDL_SemPost(mainSem);
210 #ifdef THREAD_DEBUGGING
211 WriteLog("CPU: SDL_CondWait(cpuCond, cpuMutex);\n");
212 #endif
213                 SDL_CondWait(cpuCond, cpuMutex);
214
215 #ifdef THREAD_DEBUGGING
216 WriteLog("CPU: SDL_mutexV(cpuMutex);\n");
217 #endif
218                 SDL_mutexV(cpuMutex);
219         }
220         while (!cpuFinished);
221
222         SDL_DestroyMutex(cpuMutex);
223
224         return 0;
225 }
226 #endif
227
228
229 #if 1
230 //
231 // Request a change in the power state of the emulated Apple
232 //
233 void SetPowerState(void)
234 {
235 //      powerOnState = state;
236 //      pauseMode = !state;
237
238 //      if (!pauseMode)
239 //      {
240 //printf("Turning on...\n");
241                 // Transitioning from OFF to ON
242 //              mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
243 //              SoundResume();
244 //      }
245 //      else
246 //      {
247 //printf("Turning off...\n");
248                 // Turn it off...
249 //              SoundPause();
250 //      }
251         powerStateChangeRequested = true;
252 }
253 #endif
254
255
256 //
257 // Load a file into RAM/ROM image space
258 //
259 bool LoadImg(char * filename, uint8_t * ram, int size)
260 {
261         FILE * fp = fopen(filename, "rb");
262
263         if (fp == NULL)
264                 return false;
265
266         fread(ram, 1, size, fp);
267         fclose(fp);
268
269         return true;
270 }
271
272
273 static void SaveApple2State(const char * filename)
274 {
275 }
276
277
278 static bool LoadApple2State(const char * filename)
279 {
280         return false;
281 }
282
283
284 static void ResetApple2State(void)
285 {
286         mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
287         keyDown = false;
288         openAppleDown = false;
289         closedAppleDown = false;
290         store80Mode = false;
291         vbl = false;
292         slotCXROM = false;
293         slotC3ROM = false;
294         ramrd = false;
295         ramwrt = false;
296         altzp = false;
297         ioudis = true;
298         dhires = false;
299         lcState = 0x02;
300         SwitchLC();                     // Make sure MMU is in sane state
301         memset(ram, 0, 0x10000);
302         memset(ram2, 0, 0x10000);
303 }
304
305
306 #ifdef CPU_CLOCK_CHECKING
307 uint8_t counter = 0;
308 uint32_t totalCPU = 0;
309 uint64_t lastClock = 0;
310 #endif
311 //
312 // Main loop
313 //
314 int main(int /*argc*/, char * /*argv*/[])
315 {
316         InitLog("./apple2.log");
317         LoadSettings();
318         srand(time(NULL));                                                                      // Initialize RNG
319
320         // Zero out memory
321         memset(ram, 0, 0x10000);
322         memset(rom, 0, 0x10000);
323         memset(ram2, 0, 0x10000);
324
325         // Set up MMU
326         SetupAddressMap();
327
328         // Set up V65C02 execution context
329         memset(&mainCPU, 0, sizeof(V65C02REGS));
330         mainCPU.RdMem = AppleReadMem;
331         mainCPU.WrMem = AppleWriteMem;
332         mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
333
334 //      alternateCharset = true;
335 //      if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
336         if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
337         {
338                 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
339                 return -1;
340         }
341
342 //Load up disk image from config file (for now)...
343         floppyDrive.LoadImage(settings.diskImagePath1, 0);
344         floppyDrive.LoadImage(settings.diskImagePath2, 1);
345 //      floppyDrive.LoadImage("./disks/temp.nib", 1);   // Load temp .nib file into second drive...
346
347         WriteLog("About to initialize video...\n");
348
349         if (!InitVideo())
350         {
351                 std::cout << "Aborting!" << std::endl;
352                 return -1;
353         }
354
355         GUI::Init(sdlRenderer);
356
357         // Have to do this *after* video init but *before* sound init...!
358 //Shouldn't be necessary since we're not doing emulation in the ISR...
359         if (settings.autoStateSaving)
360         {
361                 // Load last state from file...
362                 if (!LoadApple2State(settings.autoStatePath))
363                         WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
364         }
365
366         WriteLog("About to initialize audio...\n");
367         SoundInit();
368         SetupBlurTable();                                                       // Set up the color TV emulation blur table
369         running = true;                                                         // Set running status...
370         InitializeEventList();                                          // Clear the event list before we use it...
371         SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
372         SetCallbackTime(BlinkTimer, 250000);            // Set up blinking at 1/4 s intervals
373         startTicks = SDL_GetTicks();
374
375 #ifdef THREADED_65C02
376         cpuCond = SDL_CreateCond();
377         mainSem = SDL_CreateSemaphore(1);
378         cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
379 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
380 //      SDL_sem * mainMutex = SDL_CreateMutex();
381 #endif
382
383         WriteLog("Entering main loop...\n");
384
385         while (running)
386         {
387                 double timeToNextEvent = GetTimeToNextEvent();
388 #ifndef THREADED_65C02
389                 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
390 #endif
391
392 #ifdef CPU_CLOCK_CHECKING
393 #ifndef THREADED_65C02
394 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
395 #endif
396 #endif
397                 HandleNextEvent();
398         }
399
400 #ifdef THREADED_65C02
401 WriteLog("Main: cpuFinished = true;\n");
402 cpuFinished = true;
403 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
404 //What to do? How do you know when the CPU is sleeping???
405 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
406 //Nope, use a semaphore...
407 WriteLog("Main: SDL_SemWait(mainSem);\n");
408 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
409 #endif
410
411 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
412 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
413 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
414 SDL_WaitThread(cpuThread, NULL);
415 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
416 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
417 SDL_DestroyCond(cpuCond);
418
419 SDL_DestroySemaphore(mainSem);
420
421         if (settings.autoStateSaving)
422         {
423                 // Save state here...
424                 SaveApple2State(settings.autoStatePath);
425         }
426 floppyDrive.SaveImage(0);
427 floppyDrive.SaveImage(1);
428
429         SoundDone();
430         VideoDone();
431         SaveSettings();
432         LogDone();
433
434         return 0;
435 }
436
437
438 /*
439 Apple II keycodes
440 -----------------
441
442 Key     Aln CTL SHF BTH
443 -----------------------
444 space   $A0     $A0     $A0 $A0         No xlation
445 RETURN  $8D     $8D     $8D     $8D             No xlation
446 0               $B0     $B0     $B0     $B0             Need to screen shift+0 (?)
447 1!              $B1 $B1 $A1 $A1         No xlation
448 2"              $B2     $B2     $A2     $A2             No xlation
449 3#              $B3     $B3     $A3     $A3             No xlation
450 4$              $B4     $B4     $A4     $A4             No xlation
451 5%              $B5     $B5     $A5     $A5             No xlation
452 6&              $B6     $B6     $A6     $A6             No xlation
453 7'              $B7     $B7     $A7     $A7             No xlation
454 8(              $B8     $B8     $A8     $A8             No xlation
455 9)              $B9     $B9     $A9     $A9             No xlation
456 :*              $BA     $BA     $AA     $AA             No xlation
457 ;+              $BB     $BB     $AB     $AB             No xlation
458 ,<              $AC     $AC     $BC     $BC             No xlation
459 -=              $AD     $AD     $BD     $BD             No xlation
460 .>              $AE     $AE     $BE     $BE             No xlation
461 /?              $AF     $AF     $BF     $BF             No xlation
462 A               $C1     $81     $C1     $81
463 B               $C2     $82     $C2     $82
464 C               $C3     $83     $C3     $83
465 D               $C4     $84     $C4     $84
466 E               $C5     $85     $C5     $85
467 F               $C6     $86     $C6     $86
468 G               $C7     $87     $C7     $87
469 H               $C8     $88     $C8     $88
470 I               $C9     $89     $C9     $89
471 J               $CA     $8A     $CA     $8A
472 K               $CB     $8B     $CB     $8B
473 L               $CC     $8C     $CC     $8C
474 M               $CD     $8D     $DD     $9D             -> ODD
475 N^              $CE     $8E     $DE     $9E             -> ODD
476 O               $CF     $8F     $CF     $8F
477 P@              $D0     $90     $C0     $80             Need to xlate CTL+SHFT+P & SHFT+P (?)
478 Q               $D1     $91     $D1     $91
479 R               $D2     $92     $D2     $92
480 S               $D3     $93     $D3     $93
481 T               $D4     $94     $D4     $94
482 U               $D5     $95     $D5     $95
483 V               $D6     $96     $D6     $96
484 W               $D7     $97     $D7     $97
485 X               $D8     $98     $D8     $98
486 Y               $D9     $99     $D9     $99
487 Z               $DA     $9A     $DA     $9A
488 <-              $88     $88     $88     $88
489 ->              $95     $95     $95     $95
490 ESC             $9B     $9B     $9B     $9B             No xlation
491
492 */
493 //static uint64_t lastCPUCycles = 0;
494 static uint32_t frameCount = 0;
495 static void FrameCallback(void)
496 {
497         SDL_Event event;
498
499         while (SDL_PollEvent(&event))
500         {
501                 switch (event.type)
502                 {
503 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
504 #if 0
505                 case SDL_TEXTINPUT:
506 //Need to do some key translation here, and screen out non-apple keys as well...
507 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
508 // everything else done separately. this is slightly easier. :-P)
509 //                      if (event.key.keysym.sym == SDLK_TAB)   // Prelim key screening...
510                         if (event.edit.text[0] == '\t') // Prelim key screening...
511                                 break;
512
513                         lastKeyPressed = event.edit.text[0];
514                         keyDown = true;
515
516                         //kludge: should have a caps lock thingy here...
517                         //or all uppercase for ][+...
518 //                      if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
519 //                              lastKeyPressed &= 0xDF;         // Convert to upper case...
520
521                         break;
522 #endif
523                 case SDL_KEYDOWN:
524                         // Use ALT+Q to exit, as well as the usual window decoration method
525                         if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
526                                 running = false;
527
528                         // CTRL+RESET key emulation (mapped to CTRL+`)
529 // This doesn't work...
530 //                      if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
531 //                      if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
532                         if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
533                         {
534 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
535 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
536                                 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
537                                 break;
538                         }
539
540                         if (event.key.keysym.sym == SDLK_RIGHT)
541                                 lastKeyPressed = 0x15, keyDown = true;
542                         else if (event.key.keysym.sym == SDLK_LEFT)
543                                 lastKeyPressed = 0x08, keyDown = true;
544                         else if (event.key.keysym.sym == SDLK_UP)
545                                 lastKeyPressed = 0x0B, keyDown = true;
546                         else if (event.key.keysym.sym == SDLK_DOWN)
547                                 lastKeyPressed = 0x0A, keyDown = true;
548                         else if (event.key.keysym.sym == SDLK_RETURN)
549                                 lastKeyPressed = 0x0D, keyDown = true;
550                         else if (event.key.keysym.sym == SDLK_ESCAPE)
551                                 lastKeyPressed = 0x1B, keyDown = true;
552                         else if (event.key.keysym.sym == SDLK_BACKSPACE)
553                                 lastKeyPressed = 0x7F, keyDown = true;
554
555                         // Fix CTRL+key combo...
556                         if (event.key.keysym.mod & KMOD_CTRL)
557                         {
558                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
559                                 {
560                                         lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
561                                         keyDown = true;
562 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
563                                         break;
564                                 }
565                         }
566
567 #if 1
568                         // Fix SHIFT+key combo...
569                         if (event.key.keysym.mod & KMOD_SHIFT)
570                         {
571                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
572                                 {
573                                         lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
574                                         keyDown = true;
575 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
576                                         break;
577                                 }
578                                 else if (event.key.keysym.sym == SDLK_1)
579                                 {
580                                         lastKeyPressed = '!';
581                                         keyDown = true;
582                                         break;
583                                 }
584                                 else if (event.key.keysym.sym == SDLK_2)
585                                 {
586                                         lastKeyPressed = '@';
587                                         keyDown = true;
588                                         break;
589                                 }
590                                 else if (event.key.keysym.sym == SDLK_3)
591                                 {
592                                         lastKeyPressed = '#';
593                                         keyDown = true;
594                                         break;
595                                 }
596                                 else if (event.key.keysym.sym == SDLK_3)
597                                 {
598                                         lastKeyPressed = '#';
599                                         keyDown = true;
600                                         break;
601                                 }
602                                 else if (event.key.keysym.sym == SDLK_4)
603                                 {
604                                         lastKeyPressed = '$';
605                                         keyDown = true;
606                                         break;
607                                 }
608                                 else if (event.key.keysym.sym == SDLK_5)
609                                 {
610                                         lastKeyPressed = '%';
611                                         keyDown = true;
612                                         break;
613                                 }
614                                 else if (event.key.keysym.sym == SDLK_6)
615                                 {
616                                         lastKeyPressed = '^';
617                                         keyDown = true;
618                                         break;
619                                 }
620                                 else if (event.key.keysym.sym == SDLK_7)
621                                 {
622                                         lastKeyPressed = '&';
623                                         keyDown = true;
624                                         break;
625                                 }
626                                 else if (event.key.keysym.sym == SDLK_8)
627                                 {
628                                         lastKeyPressed = '*';
629                                         keyDown = true;
630                                         break;
631                                 }
632                                 else if (event.key.keysym.sym == SDLK_9)
633                                 {
634                                         lastKeyPressed = '(';
635                                         keyDown = true;
636                                         break;
637                                 }
638                                 else if (event.key.keysym.sym == SDLK_0)
639                                 {
640                                         lastKeyPressed = ')';
641                                         keyDown = true;
642                                         break;
643                                 }
644                                 else if (event.key.keysym.sym == SDLK_MINUS)
645                                 {
646                                         lastKeyPressed = '_';
647                                         keyDown = true;
648                                         break;
649                                 }
650                                 else if (event.key.keysym.sym == SDLK_EQUALS)
651                                 {
652                                         lastKeyPressed = '+';
653                                         keyDown = true;
654                                         break;
655                                 }
656                                 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
657                                 {
658                                         lastKeyPressed = '{';
659                                         keyDown = true;
660                                         break;
661                                 }
662                                 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
663                                 {
664                                         lastKeyPressed = '}';
665                                         keyDown = true;
666                                         break;
667                                 }
668                                 else if (event.key.keysym.sym == SDLK_BACKSLASH)
669                                 {
670                                         lastKeyPressed = '|';
671                                         keyDown = true;
672                                         break;
673                                 }
674                                 else if (event.key.keysym.sym == SDLK_SEMICOLON)
675                                 {
676                                         lastKeyPressed = ':';
677                                         keyDown = true;
678                                         break;
679                                 }
680                                 else if (event.key.keysym.sym == SDLK_QUOTE)
681                                 {
682                                         lastKeyPressed = '"';
683                                         keyDown = true;
684                                         break;
685                                 }
686                                 else if (event.key.keysym.sym == SDLK_COMMA)
687                                 {
688                                         lastKeyPressed = '<';
689                                         keyDown = true;
690                                         break;
691                                 }
692                                 else if (event.key.keysym.sym == SDLK_PERIOD)
693                                 {
694                                         lastKeyPressed = '>';
695                                         keyDown = true;
696                                         break;
697                                 }
698                                 else if (event.key.keysym.sym == SDLK_SLASH)
699                                 {
700                                         lastKeyPressed = '?';
701                                         keyDown = true;
702                                         break;
703                                 }
704                                 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
705                                 {
706                                         lastKeyPressed = '~';
707                                         keyDown = true;
708                                         break;
709                                 }
710                         }
711 #endif
712
713                         // General keys...
714                         if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
715                         {
716                                 lastKeyPressed = event.key.keysym.sym;
717                                 keyDown = true;
718
719                                 // Check for Caps Lock key...
720                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
721                                         lastKeyPressed -= 0x20;
722
723                                 break;
724                         }
725
726                         if (event.key.keysym.sym == SDLK_PAUSE)
727                         {
728                                 pauseMode = !pauseMode;
729
730                                 if (pauseMode)
731                                 {
732                                         SoundPause();
733                                         SpawnMessage("*** PAUSED ***");
734                                 }
735                                 else
736                                 {
737                                         SoundResume();
738                                         SpawnMessage("*** RESUME ***");
739                                 }
740                         }
741
742                         // Paddle buttons 0 & 1
743                         if (event.key.keysym.sym == SDLK_INSERT)
744                                 openAppleDown = true;
745                         if (event.key.keysym.sym == SDLK_PAGEUP)
746                                 closedAppleDown = true;
747
748                         if (event.key.keysym.sym == SDLK_F11)
749                                 dumpDis = !dumpDis;                             // Toggle the disassembly process
750
751 /*else if (event.key.keysym.sym == SDLK_F9)
752 {
753         floppyDrive.CreateBlankImage(0);
754 //      SpawnMessage("Image cleared...");
755 }//*/
756 /*else if (event.key.keysym.sym == SDLK_F10)
757 {
758         floppyDrive.SwapImages();
759 //      SpawnMessage("Image swapped...");
760 }//*/
761
762                         if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
763                                 TogglePalette();
764                         else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
765                                 CycleScreenTypes();
766                         else if (event.key.keysym.sym == SDLK_F5)
767                         {
768                                 VolumeDown();
769                                 char volStr[19] = "[****************]";
770 //                              volStr[GetVolume()] = 0;
771                                 for(int i=GetVolume(); i<16; i++)
772                                         volStr[1 + i] = '-';
773                                 SpawnMessage("Volume: %s", volStr);
774                         }
775                         else if (event.key.keysym.sym == SDLK_F6)
776                         {
777                                 VolumeUp();
778                                 char volStr[19] = "[****************]";
779 //                              volStr[GetVolume()] = 0;
780                                 for(int i=GetVolume(); i<16; i++)
781                                         volStr[1 + i] = '-';
782                                 SpawnMessage("Volume: %s", volStr);
783                         }
784                         else if (event.key.keysym.sym == SDLK_F12)
785                         {
786                                 if (!fullscreenDebounce)
787                                 {
788                                         ToggleFullScreen();
789                                         fullscreenDebounce = true;
790                                 }
791                         }
792
793                         if (event.key.keysym.sym == SDLK_CAPSLOCK)
794                         {
795                                 if (!capsLockDebounce)
796                                 {
797                                         capsLock = !capsLock;
798                                         capsLockDebounce = true;
799                                 }
800                         }
801
802                         break;
803                 case SDL_KEYUP:
804                         if (event.key.keysym.sym == SDLK_F12)
805                                 fullscreenDebounce = false;
806                         if (event.key.keysym.sym == SDLK_CAPSLOCK)
807                                 capsLockDebounce = false;
808
809                         // Paddle buttons 0 & 1
810                         if (event.key.keysym.sym == SDLK_INSERT)
811                                 openAppleDown = false;
812                         if (event.key.keysym.sym == SDLK_PAGEUP)
813                                 closedAppleDown = false;
814
815 //                      if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
816 //                              keyDown = false;
817
818                         break;
819                 case SDL_MOUSEBUTTONDOWN:
820                         GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
821                         break;
822                 case SDL_MOUSEBUTTONUP:
823                         GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
824                         break;
825                 case SDL_MOUSEMOTION:
826                         GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
827                         break;
828                 case SDL_WINDOWEVENT:
829                         if (event.window.event == SDL_WINDOWEVENT_LEAVE)
830                                 GUI::MouseMove(0, 0, 0);
831
832                         break;
833                 case SDL_QUIT:
834                         running = false;
835                 }
836         }
837
838         // Handle power request from the GUI
839         if (powerStateChangeRequested)
840         {
841                 if (GUI::powerOnState)
842                 {
843                         pauseMode = false;
844                         SoundResume();
845                         ResetApple2State();
846                 }
847                 else
848                 {
849                         pauseMode = true;
850                         SoundPause();
851 //NOPE                  SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
852 //                      ResetApple2State();
853                 }
854
855                 powerStateChangeRequested = false;
856         }
857
858 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
859 //      if (!pauseMode)
860         {
861                 RenderVideoFrame();
862         }
863
864         RenderScreenBuffer();
865         GUI::Render(sdlRenderer);
866         SDL_RenderPresent(sdlRenderer);
867         SetCallbackTime(FrameCallback, 16666.66666667);
868
869 #ifdef CPU_CLOCK_CHECKING
870 //We know it's stopped, so we can get away with this...
871 counter++;
872 if (counter == 60)
873 {
874         uint64_t clock = GetCurrentV65C02Clock();
875 //totalCPU += (uint32_t)(clock - lastClock);
876
877         printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
878         lastClock = clock;
879 //      totalCPU = 0;
880         counter = 0;
881 }
882 #endif
883
884 // This is the problem: If you set the interval to 16, it runs faster than
885 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
886 // have it do 16 for one frame, then 17 for two others. Then it should average
887 // out to 1/60s per frame every 3 frames.
888         frameCount = (frameCount + 1) % 3;
889         uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
890
891         // Wait for next frame...
892         while (SDL_GetTicks() - startTicks < waitFrameTime)
893                 SDL_Delay(1);
894
895         startTicks = SDL_GetTicks();
896 #if 0
897         uint64_t cpuCycles = GetCurrentV65C02Clock();
898         uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
899         WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
900         lastCPUCycles = cpuCycles;
901 #endif
902
903 //let's wait, then signal...
904 //works longer, but then still falls behind...
905 #ifdef THREADED_65C02
906         if (!pauseMode)
907                 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
908 #endif
909 }
910
911
912 static void BlinkTimer(void)
913 {
914         flash = !flash;
915         SetCallbackTime(BlinkTimer, 250000);            // Set up blinking at 1/4 sec intervals
916 }
917
918
919 /*
920 Next problem is this: How to have events occur and synchronize with the rest
921 of the threads?
922
923   o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
924     remainder CPU cycles over...)
925
926 One way would be to use a fractional accumulator, then subtract 1 every
927 time it overflows. Like so:
928
929 double overflow = 0;
930 uint32_t time = 20;
931 while (!done)
932 {
933         Execute6808(&soundCPU, time);
934         overflow += 0.289115646;
935         if (overflow > 1.0)
936         {
937                 overflow -= 1.0;
938                 time = 21;
939         }
940         else
941                 time = 20;
942 }
943 */