]> Shamusworld >> Repos - apple2/blob - src/apple2.cpp
9afc35ff980a86eaa591a801461482ccc008fa00
[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         keyDown = false;
287         openAppleDown = false;
288         closedAppleDown = false;
289         store80Mode = false;
290         vbl = false;
291         slotCXROM = false;
292         slotC3ROM = false;
293         ramrd = false;
294         ramwrt = false;
295         altzp = false;
296         ioudis = true;
297         dhires = false;
298         lcState = 0x02;
299 //      SwitchLC();                     // Make sure MMU is in sane state
300 //NOPE, does nothing    SetupAddressMap();
301         ResetMMUPointers();
302
303         // Without this, you can wedge the system :-/
304         memset(ram, 0, 0x10000);
305 //      memset(ram2, 0, 0x10000);
306         mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
307 }
308
309
310 #ifdef CPU_CLOCK_CHECKING
311 uint8_t counter = 0;
312 uint32_t totalCPU = 0;
313 uint64_t lastClock = 0;
314 #endif
315 //
316 // Main loop
317 //
318 int main(int /*argc*/, char * /*argv*/[])
319 {
320         InitLog("./apple2.log");
321         LoadSettings();
322         srand(time(NULL));                                                                      // Initialize RNG
323
324         // Zero out memory
325         memset(ram, 0, 0x10000);
326         memset(rom, 0, 0x10000);
327         memset(ram2, 0, 0x10000);
328
329         // Set up MMU
330         SetupAddressMap();
331         ResetMMUPointers();
332
333         // Set up V65C02 execution context
334         memset(&mainCPU, 0, sizeof(V65C02REGS));
335         mainCPU.RdMem = AppleReadMem;
336         mainCPU.WrMem = AppleWriteMem;
337         mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
338
339 //      alternateCharset = true;
340 //      if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
341         if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
342         {
343                 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
344                 return -1;
345         }
346
347 //Load up disk image from config file (for now)...
348         floppyDrive.LoadImage(settings.diskImagePath1, 0);
349         floppyDrive.LoadImage(settings.diskImagePath2, 1);
350 //      floppyDrive.LoadImage("./disks/temp.nib", 1);   // Load temp .nib file into second drive...
351
352         WriteLog("About to initialize video...\n");
353
354         if (!InitVideo())
355         {
356                 std::cout << "Aborting!" << std::endl;
357                 return -1;
358         }
359
360         GUI::Init(sdlRenderer);
361
362         // Have to do this *after* video init but *before* sound init...!
363 //Shouldn't be necessary since we're not doing emulation in the ISR...
364         if (settings.autoStateSaving)
365         {
366                 // Load last state from file...
367                 if (!LoadApple2State(settings.autoStatePath))
368                         WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
369         }
370
371         WriteLog("About to initialize audio...\n");
372         SoundInit();
373         SetupBlurTable();                                                       // Set up the color TV emulation blur table
374         running = true;                                                         // Set running status...
375         InitializeEventList();                                          // Clear the event list before we use it...
376         SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
377         SetCallbackTime(BlinkTimer, 250000);            // Set up blinking at 1/4 s intervals
378         startTicks = SDL_GetTicks();
379
380 #ifdef THREADED_65C02
381         cpuCond = SDL_CreateCond();
382         mainSem = SDL_CreateSemaphore(1);
383         cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
384 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
385 //      SDL_sem * mainMutex = SDL_CreateMutex();
386 #endif
387
388         WriteLog("Entering main loop...\n");
389
390         while (running)
391         {
392                 double timeToNextEvent = GetTimeToNextEvent();
393 #ifndef THREADED_65C02
394                 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
395 #endif
396
397 #ifdef CPU_CLOCK_CHECKING
398 #ifndef THREADED_65C02
399 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
400 #endif
401 #endif
402                 HandleNextEvent();
403         }
404
405 #ifdef THREADED_65C02
406 WriteLog("Main: cpuFinished = true;\n");
407 cpuFinished = true;
408 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
409 //What to do? How do you know when the CPU is sleeping???
410 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
411 //Nope, use a semaphore...
412 WriteLog("Main: SDL_SemWait(mainSem);\n");
413 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
414 #endif
415
416 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
417 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
418 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
419 SDL_WaitThread(cpuThread, NULL);
420 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
421 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
422 SDL_DestroyCond(cpuCond);
423
424 SDL_DestroySemaphore(mainSem);
425
426         if (settings.autoStateSaving)
427         {
428                 // Save state here...
429                 SaveApple2State(settings.autoStatePath);
430         }
431 floppyDrive.SaveImage(0);
432 floppyDrive.SaveImage(1);
433
434         SoundDone();
435         VideoDone();
436         SaveSettings();
437         LogDone();
438
439         return 0;
440 }
441
442
443 /*
444 Apple II keycodes
445 -----------------
446
447 Key     Aln CTL SHF BTH
448 -----------------------
449 space   $A0     $A0     $A0 $A0         No xlation
450 RETURN  $8D     $8D     $8D     $8D             No xlation
451 0               $B0     $B0     $B0     $B0             Need to screen shift+0 (?)
452 1!              $B1 $B1 $A1 $A1         No xlation
453 2"              $B2     $B2     $A2     $A2             No xlation
454 3#              $B3     $B3     $A3     $A3             No xlation
455 4$              $B4     $B4     $A4     $A4             No xlation
456 5%              $B5     $B5     $A5     $A5             No xlation
457 6&              $B6     $B6     $A6     $A6             No xlation
458 7'              $B7     $B7     $A7     $A7             No xlation
459 8(              $B8     $B8     $A8     $A8             No xlation
460 9)              $B9     $B9     $A9     $A9             No xlation
461 :*              $BA     $BA     $AA     $AA             No xlation
462 ;+              $BB     $BB     $AB     $AB             No xlation
463 ,<              $AC     $AC     $BC     $BC             No xlation
464 -=              $AD     $AD     $BD     $BD             No xlation
465 .>              $AE     $AE     $BE     $BE             No xlation
466 /?              $AF     $AF     $BF     $BF             No xlation
467 A               $C1     $81     $C1     $81
468 B               $C2     $82     $C2     $82
469 C               $C3     $83     $C3     $83
470 D               $C4     $84     $C4     $84
471 E               $C5     $85     $C5     $85
472 F               $C6     $86     $C6     $86
473 G               $C7     $87     $C7     $87
474 H               $C8     $88     $C8     $88
475 I               $C9     $89     $C9     $89
476 J               $CA     $8A     $CA     $8A
477 K               $CB     $8B     $CB     $8B
478 L               $CC     $8C     $CC     $8C
479 M               $CD     $8D     $DD     $9D             -> ODD
480 N^              $CE     $8E     $DE     $9E             -> ODD
481 O               $CF     $8F     $CF     $8F
482 P@              $D0     $90     $C0     $80             Need to xlate CTL+SHFT+P & SHFT+P (?)
483 Q               $D1     $91     $D1     $91
484 R               $D2     $92     $D2     $92
485 S               $D3     $93     $D3     $93
486 T               $D4     $94     $D4     $94
487 U               $D5     $95     $D5     $95
488 V               $D6     $96     $D6     $96
489 W               $D7     $97     $D7     $97
490 X               $D8     $98     $D8     $98
491 Y               $D9     $99     $D9     $99
492 Z               $DA     $9A     $DA     $9A
493 <-              $88     $88     $88     $88
494 ->              $95     $95     $95     $95
495 ESC             $9B     $9B     $9B     $9B             No xlation
496
497 */
498 //static uint64_t lastCPUCycles = 0;
499 static uint32_t frameCount = 0;
500 static void FrameCallback(void)
501 {
502         SDL_Event event;
503
504         while (SDL_PollEvent(&event))
505         {
506                 switch (event.type)
507                 {
508 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
509 #if 0
510                 case SDL_TEXTINPUT:
511 //Need to do some key translation here, and screen out non-apple keys as well...
512 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
513 // everything else done separately. this is slightly easier. :-P)
514 //                      if (event.key.keysym.sym == SDLK_TAB)   // Prelim key screening...
515                         if (event.edit.text[0] == '\t') // Prelim key screening...
516                                 break;
517
518                         lastKeyPressed = event.edit.text[0];
519                         keyDown = true;
520
521                         //kludge: should have a caps lock thingy here...
522                         //or all uppercase for ][+...
523 //                      if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
524 //                              lastKeyPressed &= 0xDF;         // Convert to upper case...
525
526                         break;
527 #endif
528                 case SDL_KEYDOWN:
529                         // Use ALT+Q to exit, as well as the usual window decoration method
530                         if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
531                                 running = false;
532
533                         // CTRL+RESET key emulation (mapped to CTRL+`)
534 // This doesn't work...
535 //                      if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
536 //                      if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
537                         if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
538                         {
539 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
540 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
541                                 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
542                                 break;
543                         }
544
545                         if (event.key.keysym.sym == SDLK_RIGHT)
546                                 lastKeyPressed = 0x15, keyDown = true;
547                         else if (event.key.keysym.sym == SDLK_LEFT)
548                                 lastKeyPressed = 0x08, keyDown = true;
549                         else if (event.key.keysym.sym == SDLK_UP)
550                                 lastKeyPressed = 0x0B, keyDown = true;
551                         else if (event.key.keysym.sym == SDLK_DOWN)
552                                 lastKeyPressed = 0x0A, keyDown = true;
553                         else if (event.key.keysym.sym == SDLK_RETURN)
554                                 lastKeyPressed = 0x0D, keyDown = true;
555                         else if (event.key.keysym.sym == SDLK_ESCAPE)
556                                 lastKeyPressed = 0x1B, keyDown = true;
557                         else if (event.key.keysym.sym == SDLK_BACKSPACE)
558                                 lastKeyPressed = 0x7F, keyDown = true;
559
560                         // Fix CTRL+key combo...
561                         if (event.key.keysym.mod & KMOD_CTRL)
562                         {
563                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
564                                 {
565                                         lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
566                                         keyDown = true;
567 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
568                                         break;
569                                 }
570                         }
571
572 #if 1
573                         // Fix SHIFT+key combo...
574                         if (event.key.keysym.mod & KMOD_SHIFT)
575                         {
576                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
577                                 {
578                                         lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
579                                         keyDown = true;
580 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
581                                         break;
582                                 }
583                                 else if (event.key.keysym.sym == SDLK_1)
584                                 {
585                                         lastKeyPressed = '!';
586                                         keyDown = true;
587                                         break;
588                                 }
589                                 else if (event.key.keysym.sym == SDLK_2)
590                                 {
591                                         lastKeyPressed = '@';
592                                         keyDown = true;
593                                         break;
594                                 }
595                                 else if (event.key.keysym.sym == SDLK_3)
596                                 {
597                                         lastKeyPressed = '#';
598                                         keyDown = true;
599                                         break;
600                                 }
601                                 else if (event.key.keysym.sym == SDLK_3)
602                                 {
603                                         lastKeyPressed = '#';
604                                         keyDown = true;
605                                         break;
606                                 }
607                                 else if (event.key.keysym.sym == SDLK_4)
608                                 {
609                                         lastKeyPressed = '$';
610                                         keyDown = true;
611                                         break;
612                                 }
613                                 else if (event.key.keysym.sym == SDLK_5)
614                                 {
615                                         lastKeyPressed = '%';
616                                         keyDown = true;
617                                         break;
618                                 }
619                                 else if (event.key.keysym.sym == SDLK_6)
620                                 {
621                                         lastKeyPressed = '^';
622                                         keyDown = true;
623                                         break;
624                                 }
625                                 else if (event.key.keysym.sym == SDLK_7)
626                                 {
627                                         lastKeyPressed = '&';
628                                         keyDown = true;
629                                         break;
630                                 }
631                                 else if (event.key.keysym.sym == SDLK_8)
632                                 {
633                                         lastKeyPressed = '*';
634                                         keyDown = true;
635                                         break;
636                                 }
637                                 else if (event.key.keysym.sym == SDLK_9)
638                                 {
639                                         lastKeyPressed = '(';
640                                         keyDown = true;
641                                         break;
642                                 }
643                                 else if (event.key.keysym.sym == SDLK_0)
644                                 {
645                                         lastKeyPressed = ')';
646                                         keyDown = true;
647                                         break;
648                                 }
649                                 else if (event.key.keysym.sym == SDLK_MINUS)
650                                 {
651                                         lastKeyPressed = '_';
652                                         keyDown = true;
653                                         break;
654                                 }
655                                 else if (event.key.keysym.sym == SDLK_EQUALS)
656                                 {
657                                         lastKeyPressed = '+';
658                                         keyDown = true;
659                                         break;
660                                 }
661                                 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
662                                 {
663                                         lastKeyPressed = '{';
664                                         keyDown = true;
665                                         break;
666                                 }
667                                 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
668                                 {
669                                         lastKeyPressed = '}';
670                                         keyDown = true;
671                                         break;
672                                 }
673                                 else if (event.key.keysym.sym == SDLK_BACKSLASH)
674                                 {
675                                         lastKeyPressed = '|';
676                                         keyDown = true;
677                                         break;
678                                 }
679                                 else if (event.key.keysym.sym == SDLK_SEMICOLON)
680                                 {
681                                         lastKeyPressed = ':';
682                                         keyDown = true;
683                                         break;
684                                 }
685                                 else if (event.key.keysym.sym == SDLK_QUOTE)
686                                 {
687                                         lastKeyPressed = '"';
688                                         keyDown = true;
689                                         break;
690                                 }
691                                 else if (event.key.keysym.sym == SDLK_COMMA)
692                                 {
693                                         lastKeyPressed = '<';
694                                         keyDown = true;
695                                         break;
696                                 }
697                                 else if (event.key.keysym.sym == SDLK_PERIOD)
698                                 {
699                                         lastKeyPressed = '>';
700                                         keyDown = true;
701                                         break;
702                                 }
703                                 else if (event.key.keysym.sym == SDLK_SLASH)
704                                 {
705                                         lastKeyPressed = '?';
706                                         keyDown = true;
707                                         break;
708                                 }
709                                 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
710                                 {
711                                         lastKeyPressed = '~';
712                                         keyDown = true;
713                                         break;
714                                 }
715                         }
716 #endif
717
718                         // General keys...
719                         if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
720                         {
721                                 lastKeyPressed = event.key.keysym.sym;
722                                 keyDown = true;
723
724                                 // Check for Caps Lock key...
725                                 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
726                                         lastKeyPressed -= 0x20;
727
728                                 break;
729                         }
730
731                         if (event.key.keysym.sym == SDLK_PAUSE)
732                         {
733                                 pauseMode = !pauseMode;
734
735                                 if (pauseMode)
736                                 {
737                                         SoundPause();
738                                         SpawnMessage("*** PAUSED ***");
739                                 }
740                                 else
741                                 {
742                                         SoundResume();
743                                         SpawnMessage("*** RESUME ***");
744                                 }
745                         }
746
747                         // Paddle buttons 0 & 1
748                         if (event.key.keysym.sym == SDLK_INSERT)
749                                 openAppleDown = true;
750                         if (event.key.keysym.sym == SDLK_PAGEUP)
751                                 closedAppleDown = true;
752
753                         if (event.key.keysym.sym == SDLK_F11)
754                                 dumpDis = !dumpDis;                             // Toggle the disassembly process
755
756 /*else if (event.key.keysym.sym == SDLK_F9)
757 {
758         floppyDrive.CreateBlankImage(0);
759 //      SpawnMessage("Image cleared...");
760 }//*/
761 /*else if (event.key.keysym.sym == SDLK_F10)
762 {
763         floppyDrive.SwapImages();
764 //      SpawnMessage("Image swapped...");
765 }//*/
766
767                         if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
768                                 TogglePalette();
769                         else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
770                                 CycleScreenTypes();
771                         else if (event.key.keysym.sym == SDLK_F5)
772                         {
773                                 VolumeDown();
774                                 char volStr[19] = "[****************]";
775 //                              volStr[GetVolume()] = 0;
776                                 for(int i=GetVolume(); i<16; i++)
777                                         volStr[1 + i] = '-';
778                                 SpawnMessage("Volume: %s", volStr);
779                         }
780                         else if (event.key.keysym.sym == SDLK_F6)
781                         {
782                                 VolumeUp();
783                                 char volStr[19] = "[****************]";
784 //                              volStr[GetVolume()] = 0;
785                                 for(int i=GetVolume(); i<16; i++)
786                                         volStr[1 + i] = '-';
787                                 SpawnMessage("Volume: %s", volStr);
788                         }
789                         else if (event.key.keysym.sym == SDLK_F12)
790                         {
791                                 if (!fullscreenDebounce)
792                                 {
793                                         ToggleFullScreen();
794                                         fullscreenDebounce = true;
795                                 }
796                         }
797
798                         if (event.key.keysym.sym == SDLK_CAPSLOCK)
799                         {
800                                 if (!capsLockDebounce)
801                                 {
802                                         capsLock = !capsLock;
803                                         capsLockDebounce = true;
804                                 }
805                         }
806
807                         break;
808                 case SDL_KEYUP:
809                         if (event.key.keysym.sym == SDLK_F12)
810                                 fullscreenDebounce = false;
811                         if (event.key.keysym.sym == SDLK_CAPSLOCK)
812                                 capsLockDebounce = false;
813
814                         // Paddle buttons 0 & 1
815                         if (event.key.keysym.sym == SDLK_INSERT)
816                                 openAppleDown = false;
817                         if (event.key.keysym.sym == SDLK_PAGEUP)
818                                 closedAppleDown = false;
819
820 //                      if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
821 //                              keyDown = false;
822
823                         break;
824                 case SDL_MOUSEBUTTONDOWN:
825                         GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
826                         break;
827                 case SDL_MOUSEBUTTONUP:
828                         GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
829                         break;
830                 case SDL_MOUSEMOTION:
831                         GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
832                         break;
833                 case SDL_WINDOWEVENT:
834                         if (event.window.event == SDL_WINDOWEVENT_LEAVE)
835                                 GUI::MouseMove(0, 0, 0);
836
837                         break;
838                 case SDL_QUIT:
839                         running = false;
840                 }
841         }
842
843         // Handle power request from the GUI
844         if (powerStateChangeRequested)
845         {
846                 if (GUI::powerOnState)
847                 {
848                         pauseMode = false;
849                         SoundResume();
850                         ResetApple2State();
851                 }
852                 else
853                 {
854                         pauseMode = true;
855                         SoundPause();
856 //NOPE                  SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
857 //                      ResetApple2State();
858                 }
859
860                 powerStateChangeRequested = false;
861         }
862
863 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
864 //      if (!pauseMode)
865         {
866                 RenderVideoFrame();
867         }
868
869         RenderScreenBuffer();
870         GUI::Render(sdlRenderer);
871         SDL_RenderPresent(sdlRenderer);
872         SetCallbackTime(FrameCallback, 16666.66666667);
873
874 #ifdef CPU_CLOCK_CHECKING
875 //We know it's stopped, so we can get away with this...
876 counter++;
877 if (counter == 60)
878 {
879         uint64_t clock = GetCurrentV65C02Clock();
880 //totalCPU += (uint32_t)(clock - lastClock);
881
882         printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
883         lastClock = clock;
884 //      totalCPU = 0;
885         counter = 0;
886 }
887 #endif
888
889 // This is the problem: If you set the interval to 16, it runs faster than
890 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
891 // have it do 16 for one frame, then 17 for two others. Then it should average
892 // out to 1/60s per frame every 3 frames.
893         frameCount = (frameCount + 1) % 3;
894         uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
895
896         // Wait for next frame...
897         while (SDL_GetTicks() - startTicks < waitFrameTime)
898                 SDL_Delay(1);
899
900         startTicks = SDL_GetTicks();
901 #if 0
902         uint64_t cpuCycles = GetCurrentV65C02Clock();
903         uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
904         WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
905         lastCPUCycles = cpuCycles;
906 #endif
907
908 //let's wait, then signal...
909 //works longer, but then still falls behind...
910 #ifdef THREADED_65C02
911         if (!pauseMode)
912                 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
913 #endif
914 }
915
916
917 static void BlinkTimer(void)
918 {
919         flash = !flash;
920         SetCallbackTime(BlinkTimer, 250000);            // Set up blinking at 1/4 sec intervals
921 }
922
923
924 /*
925 Next problem is this: How to have events occur and synchronize with the rest
926 of the threads?
927
928   o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
929     remainder CPU cycles over...)
930
931 One way would be to use a fractional accumulator, then subtract 1 every
932 time it overflows. Like so:
933
934 double overflow = 0;
935 uint32_t time = 20;
936 while (!done)
937 {
938         Execute6808(&soundCPU, time);
939         overflow += 0.289115646;
940         if (overflow > 1.0)
941         {
942                 overflow -= 1.0;
943                 time = 21;
944         }
945         else
946                 time = 20;
947 }
948 */