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