forked from audetto/AppleWin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Disk.cpp
2252 lines (1826 loc) · 69.8 KB
/
Disk.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
AppleWin : An Apple //e emulator for Windows
Copyright (C) 1994-1996, Michael O'Brien
Copyright (C) 1999-2001, Oliver Schmidt
Copyright (C) 2002-2005, Tom Charlesworth
Copyright (C) 2006-2019, Tom Charlesworth, Michael Pohoreski, Nick Westgate
AppleWin is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
AppleWin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with AppleWin; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Description: Disk
*
* Author: Various
*
* In comments, UTAIIe is an abbreviation for a reference to "Understanding the Apple //e" by James Sather
*/
#include "StdAfx.h"
#include "Disk.h"
#include "SaveState_Structs_v1.h"
#include "Interface.h"
#include "Core.h"
#include "CPU.h"
#include "DiskImage.h"
#include "Log.h"
#include "Memory.h"
#include "Registry.h"
#include "SaveState.h"
#include "YamlHelper.h"
#include "../resource/resource.h"
// About m_enhanceDisk:
// . In general m_enhanceDisk==false is used for authentic disk access speed, whereas m_enhanceDisk==true is for enhanced speed.
// Details:
// . if false: Used by ImageReadTrack() to skew the sectors in a track (for .do, .dsk, .po 5.25" images).
// . if true && m_floppyMotorOn, then this is a condition for full-speed (unthrottled) emulation mode.
// . if false && I/O ReadWrite($C0EC) && drive is spinning, then advance the track buffer's nibble index (to simulate spinning).
// Also m_enhanceDisk is persisted to the save-state, so it's an attribute of the DiskII interface card.
// NB. Non-standard 4&4, with Vol=0x00 and Chk=0x00 (only a few match, eg. Wasteland, Legacy of the Ancients, Planetfall, Border Zone & Wizardry). [*1]
const BYTE Disk2InterfaceCard::m_T00S00Pattern[] = {0xD5,0xAA,0x96,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xDE};
Disk2InterfaceCard::Disk2InterfaceCard(UINT slot) :
Card(CT_Disk2, slot)
{
if (m_slot != 5 && m_slot != 6) // fixme
throw std::string("Card: wrong slot");
ResetSwitches();
m_floppyLatch = 0;
m_saveDiskImage = true; // Save the DiskImage name to Registry
m_diskLastCycle = 0;
m_diskLastReadLatchCycle = 0;
m_enhanceDisk = true;
m_is13SectorFirmware = false;
ResetLogicStateSequencer();
// if created by user in Config->Disk, then MemInitializeIO() won't be called
if (GetCxRomPeripheral())
InitializeIO(GetCxRomPeripheral()); // During regular start-up, Initialize() will be called later by MemInitializeIO()
// Debug:
#if LOG_DISK_NIBBLES_USE_RUNTIME_VAR
m_bLogDisk_NibblesRW = false;
#endif
#if LOG_DISK_NIBBLES_WRITE
m_uWriteLastCycle = 0;
m_uSyncFFCount = 0;
#endif
}
Disk2InterfaceCard::~Disk2InterfaceCard(void)
{
EjectDiskInternal(DRIVE_1);
EjectDiskInternal(DRIVE_2);
// if destroyed by user in Config->Disk, then ensure that old object's reference is removed
UnregisterIoHandler(m_slot);
}
bool Disk2InterfaceCard::GetEnhanceDisk(void) { return m_enhanceDisk; }
void Disk2InterfaceCard::SetEnhanceDisk(bool bEnhanceDisk) { m_enhanceDisk = bEnhanceDisk; }
int Disk2InterfaceCard::GetCurrentDrive(void) { return m_currDrive; }
int Disk2InterfaceCard::GetCurrentTrack(void) { return ImagePhaseToTrack(m_floppyDrive[m_currDrive].m_disk.m_imagehandle, m_floppyDrive[m_currDrive].m_phasePrecise, false); }
float Disk2InterfaceCard::GetCurrentPhase(void) { return m_floppyDrive[m_currDrive].m_phasePrecise; }
int Disk2InterfaceCard::GetCurrentOffset(void) { return m_floppyDrive[m_currDrive].m_disk.m_byte; }
BYTE Disk2InterfaceCard::GetCurrentLSSBitMask(void) { return m_floppyDrive[m_currDrive].m_disk.m_bitMask; }
double Disk2InterfaceCard::GetCurrentExtraCycles(void) { return m_floppyDrive[m_currDrive].m_disk.m_extraCycles; }
int Disk2InterfaceCard::GetTrack(const int drive) { return ImagePhaseToTrack(m_floppyDrive[drive].m_disk.m_imagehandle, m_floppyDrive[drive].m_phasePrecise, false); }
std::string Disk2InterfaceCard::GetCurrentTrackString(void)
{
const UINT trackInt = (UINT)(m_floppyDrive[m_currDrive].m_phasePrecise / 2);
const float trackFrac = (m_floppyDrive[m_currDrive].m_phasePrecise / 2) - (float)trackInt;
char szInt[8] = "";
sprintf(szInt, "%02X", trackInt); // "$NN"
char szFrac[8] = "";
sprintf(szFrac, "%.02f", trackFrac); // "0.nn"
return std::string(szInt) + std::string(szFrac+1);
}
std::string Disk2InterfaceCard::GetCurrentPhaseString(void)
{
const UINT phaseInt = (UINT)(m_floppyDrive[m_currDrive].m_phasePrecise);
const float phaseFrac = m_floppyDrive[m_currDrive].m_phasePrecise - (float)phaseInt;
char szInt[8] = "";
sprintf(szInt, "%02X", phaseInt); // "$NN"
char szFrac[8] = "";
sprintf(szFrac, "%.02f", phaseFrac); // "0.nn"
return std::string(szInt) + std::string(szFrac+1);
}
LPCTSTR Disk2InterfaceCard::GetCurrentState(void)
{
if (m_floppyDrive[m_currDrive].m_disk.m_imagehandle == NULL)
return "Empty";
if (!m_floppyMotorOn)
{
if (m_floppyDrive[m_currDrive].m_spinning > 0)
return "Off (spinning)";
else
return "Off";
}
else if (m_seqFunc.writeMode)
{
if (m_floppyDrive[m_currDrive].m_disk.m_bWriteProtected)
return "Writing (write protected)";
else
return "Writing";
}
else
{
/*if (m_seqFunc.loadMode)
{
if (m_floppyDrive[m_currDrive].disk.bWriteProtected)
return "Reading write protect state (write protected)";
else
return "Reading write protect state (not write protected)";
}
else*/
return "Reading";
}
}
//===========================================================================
void Disk2InterfaceCard::LoadLastDiskImage(const int drive)
{
_ASSERT(drive == DRIVE_1 || drive == DRIVE_2);
const std::string regKey = (drive == DRIVE_1)
? REGVALUE_LAST_DISK_1
: REGVALUE_LAST_DISK_2;
char pathname[MAX_PATH];
std::string& regSection = RegGetConfigSlotSection(m_slot);
if (RegLoadString(regSection.c_str(), regKey.c_str(), TRUE, pathname, MAX_PATH, TEXT("")) && (pathname[0] != 0))
{
m_saveDiskImage = false;
ImageError_e error = InsertDisk(drive, pathname, IMAGE_USE_FILES_WRITE_PROTECT_STATUS, IMAGE_DONT_CREATE);
m_saveDiskImage = true;
if (error != eIMAGE_ERROR_NONE)
{
NotifyInvalidImage(drive, pathname, error);
EjectDisk(drive);
}
}
}
//===========================================================================
void Disk2InterfaceCard::SaveLastDiskImage(const int drive)
{
_ASSERT(drive == DRIVE_1 || drive == DRIVE_2);
if (!m_saveDiskImage)
return;
std::string& regSection = RegGetConfigSlotSection(m_slot);
RegSaveValue(regSection.c_str(), REGVALUE_CARD_TYPE, TRUE, CT_Disk2);
const std::string regKey = (drive == DRIVE_1)
? REGVALUE_LAST_DISK_1
: REGVALUE_LAST_DISK_2;
const std::string& pathName = DiskGetFullPathName(drive);
RegSaveString(regSection.c_str(), regKey.c_str(), TRUE, pathName);
//
// For now, only update 'Starting Directory' for slot6 & drive1
// . otherwise you'll get inconsistent results if you set drive1, then drive2 (and the images were in different folders)
if (m_slot != SLOT6 || drive != DRIVE_1)
return;
TCHAR szPathName[MAX_PATH];
StringCbCopy(szPathName, MAX_PATH, pathName.c_str());
TCHAR* slash = _tcsrchr(szPathName, PATH_SEPARATOR);
if (slash != NULL)
{
slash[1] = '\0';
RegSaveString(REG_PREFS, REGVALUE_PREF_START_DIR, 1, szPathName);
}
}
//===========================================================================
// Called by ControlMotor() & Enable()
void Disk2InterfaceCard::CheckSpinning(const bool stateChanged, const ULONG uExecutedCycles)
{
bool modeChanged = m_floppyMotorOn && !m_floppyDrive[m_currDrive].m_spinning;
if (m_floppyMotorOn && IsDriveConnected(m_currDrive))
m_floppyDrive[m_currDrive].m_spinning = SPINNING_CYCLES;
if (modeChanged)
GetFrame().FrameDrawDiskLEDS();
if (modeChanged)
{
// Set m_diskLastCycle when motor changes: not spinning (ie. off for 1 sec) -> on
m_diskLastCycle = g_nCumulativeCycles;
}
if (m_floppyMotorOn && stateChanged)
{
// Set m_motorOnCycle when: motor changes to on, or the other drive is enabled (and motor is on)
m_floppyDrive[m_currDrive].m_motorOnCycle = g_nCumulativeCycles;
}
}
//===========================================================================
bool Disk2InterfaceCard::IsDriveValid(const int drive)
{
return (drive >= 0 && drive < NUM_DRIVES);
}
//===========================================================================
void Disk2InterfaceCard::AllocTrack(const int drive, const UINT minSize/*=NIBBLES_PER_TRACK*/)
{
FloppyDisk* pFloppy = &m_floppyDrive[drive].m_disk;
const UINT maxNibblesPerTrack = ImageGetMaxNibblesPerTrack(m_floppyDrive[drive].m_disk.m_imagehandle);
pFloppy->m_trackimage = new BYTE[ MAX(minSize,maxNibblesPerTrack) ];
}
//===========================================================================
void Disk2InterfaceCard::ReadTrack(const int drive, ULONG uExecutedCycles)
{
if (!IsDriveValid( drive ))
return;
FloppyDrive* pDrive = &m_floppyDrive[ drive ];
FloppyDisk* pFloppy = &pDrive->m_disk;
if (ImagePhaseToTrack(pFloppy->m_imagehandle, pDrive->m_phasePrecise, false) >= ImageGetNumTracks(pFloppy->m_imagehandle))
{
_ASSERT(0); // What can cause this? Add a comment to replace this assert.
// Boot with DOS 3.3 Master in D1
// Create a blank disk in D2
// INIT HELLO,D2
// RUN HELLO
// F2 to reboot DOS 3.3 Master
// RUN HELLO,D2
pFloppy->m_trackimagedata = false;
return;
}
if (!pFloppy->m_trackimage)
AllocTrack( drive );
if (pFloppy->m_trackimage && pFloppy->m_imagehandle)
{
const UINT32 currentPosition = pFloppy->m_byte;
const UINT32 currentTrackLength = pFloppy->m_nibbles;
ImageReadTrack(
pFloppy->m_imagehandle,
pDrive->m_phasePrecise,
pFloppy->m_trackimage,
&pFloppy->m_nibbles,
&pFloppy->m_bitCount,
m_enhanceDisk);
if (!ImageIsWOZ(pFloppy->m_imagehandle) || (currentTrackLength == 0))
{
pFloppy->m_byte = 0;
}
else
{
_ASSERT(pFloppy->m_nibbles && pFloppy->m_bitCount);
if (pFloppy->m_nibbles == 0 || pFloppy->m_bitCount == 0)
{
pFloppy->m_nibbles = 1;
pFloppy->m_bitCount = 8;
}
pFloppy->m_byte = (currentPosition * pFloppy->m_nibbles) / currentTrackLength; // Ref: WOZ-1.01
if (pFloppy->m_byte == (pFloppy->m_nibbles-1)) // Last nibble may not be complete, so advance by 1 nibble
pFloppy->m_byte = 0;
pFloppy->m_bitOffset = pFloppy->m_byte*8;
pFloppy->m_bitMask = 1 << 7;
pFloppy->m_extraCycles = 0.0;
pDrive->m_headWindow = 0;
}
pFloppy->m_trackimagedata = (pFloppy->m_nibbles != 0);
}
}
//===========================================================================
void Disk2InterfaceCard::EjectDiskInternal(const int drive)
{
FloppyDisk* pFloppy = &m_floppyDrive[drive].m_disk;
if (pFloppy->m_imagehandle)
{
FlushCurrentTrack(drive);
ImageClose(pFloppy->m_imagehandle);
pFloppy->m_imagehandle = NULL;
}
if (pFloppy->m_trackimage)
{
delete [] pFloppy->m_trackimage;
pFloppy->m_trackimage = NULL;
pFloppy->m_trackimagedata = false;
}
pFloppy->m_imagename.clear();
pFloppy->m_fullname.clear();
pFloppy->m_strFilenameInZip = "";
}
void Disk2InterfaceCard::EjectDisk(const int drive)
{
if (!IsDriveValid(drive))
return;
EjectDiskInternal(drive);
Snapshot_UpdatePath();
SaveLastDiskImage(drive);
GetFrame().Video_ResetScreenshotCounter("");
}
void Disk2InterfaceCard::UnplugDrive(const int drive)
{
if (!IsDriveValid(drive))
return;
EjectDisk(drive);
m_floppyDrive[drive].m_isConnected = false;
}
//===========================================================================
void Disk2InterfaceCard::WriteTrack(const int drive)
{
FloppyDrive* pDrive = &m_floppyDrive[ drive ];
FloppyDisk* pFloppy = &pDrive->m_disk;
if (ImagePhaseToTrack(pFloppy->m_imagehandle, pDrive->m_phasePrecise, false) >= ImageGetNumTracks(pFloppy->m_imagehandle))
{
_ASSERT(0); // What can cause this? Add a comment to replace this assert.
return;
}
if (pFloppy->m_bWriteProtected)
return;
if (pFloppy->m_trackimage && pFloppy->m_imagehandle)
{
#if LOG_DISK_TRACKS
LOG_DISK("track $%s write\r\n", GetCurrentTrackString().c_str());
#endif
ImageWriteTrack(
pFloppy->m_imagehandle,
pDrive->m_phasePrecise,
pFloppy->m_trackimage,
pFloppy->m_nibbles);
}
pFloppy->m_trackimagedirty = false;
}
void Disk2InterfaceCard::FlushCurrentTrack(const int drive)
{
FloppyDisk* pFloppy = &m_floppyDrive[drive].m_disk;
if (pFloppy->m_trackimage && pFloppy->m_trackimagedirty)
WriteTrack(drive);
}
//===========================================================================
void Disk2InterfaceCard::Boot(void)
{
// THIS FUNCTION RELOADS A PROGRAM IMAGE IF ONE IS LOADED IN DRIVE ONE.
// IF A DISK IMAGE OR NO IMAGE IS LOADED IN DRIVE ONE, IT DOES NOTHING.
if (m_floppyDrive[0].m_disk.m_imagehandle && ImageBoot(m_floppyDrive[0].m_disk.m_imagehandle))
m_floppyMotorOn = 0;
}
//===========================================================================
void __stdcall Disk2InterfaceCard::ControlMotor(WORD, WORD address, BYTE, BYTE, ULONG uExecutedCycles)
{
BOOL newState = address & 1;
bool stateChanged = (newState != m_floppyMotorOn);
if (stateChanged)
{
m_floppyMotorOn = newState;
m_formatTrack.DriveNotWritingTrack();
}
// NB. Motor off doesn't reset the Command Decoder like reset. (UTAIIe figures 9.7 & 9.8 chip C2)
// - so it doesn't reset this state: m_seqFunc, m_magnetStates
#if LOG_DISK_MOTOR
LOG_DISK("%08X: motor %s\r\n", (UINT32)g_nCumulativeCycles, (m_floppyMotorOn) ? "on" : "off");
#endif
CheckSpinning(stateChanged, uExecutedCycles);
}
//===========================================================================
void __stdcall Disk2InterfaceCard::ControlStepper(WORD, WORD address, BYTE, BYTE, ULONG uExecutedCycles)
{
FloppyDrive* pDrive = &m_floppyDrive[m_currDrive];
FloppyDisk* pFloppy = &pDrive->m_disk;
if (!m_floppyMotorOn) // GH#525
{
if (!pDrive->m_spinning)
{
#if LOG_DISK_PHASES
LOG_DISK("stepper accessed whilst motor is off and not spinning\r\n");
#endif
return;
}
#if LOG_DISK_PHASES
LOG_DISK("stepper accessed whilst motor is off, but still spinning\r\n");
#endif
}
// update phases (magnet states)
{
const int phase = (address >> 1) & 3;
const int phase_bit = (1 << phase);
// update the magnet states
if (address & 1)
m_magnetStates |= phase_bit; // phase on
else
m_magnetStates &= ~phase_bit; // phase off
}
#if LOG_DISK_PHASES
const ULONG cycleDelta = (ULONG)(g_nCumulativeCycles - pDrive->m_lastStepperCycle);
#endif
pDrive->m_lastStepperCycle = g_nCumulativeCycles;
// check for any stepping effect from a magnet
// - move only when the magnet opposite the cog is off
// - move in the direction of an adjacent magnet if one is on
// - do not move if both adjacent magnets are on (ie. quarter track)
// momentum and timing are not accounted for ... maybe one day!
int direction = 0;
if (m_magnetStates & (1 << ((pDrive->m_phase + 1) & 3)))
direction += 1;
if (m_magnetStates & (1 << ((pDrive->m_phase + 3) & 3)))
direction -= 1;
// Only calculate quarterDirection for WOZ, as NIB/DSK don't support half phases.
int quarterDirection = 0;
if (ImageIsWOZ(pFloppy->m_imagehandle))
{
if ((m_magnetStates == 0xC || // 1100
m_magnetStates == 0x6 || // 0110
m_magnetStates == 0x3 || // 0011
m_magnetStates == 0x9)) // 1001
{
quarterDirection = direction;
direction = 0;
}
}
pDrive->m_phase = MAX(0, MIN(79, pDrive->m_phase + direction));
float newPhasePrecise = (float)(pDrive->m_phase) + (float)quarterDirection * 0.5f;
if (newPhasePrecise < 0)
newPhasePrecise = 0;
// apply magnet step, if any
if (newPhasePrecise != pDrive->m_phasePrecise)
{
FlushCurrentTrack(m_currDrive);
pDrive->m_phasePrecise = newPhasePrecise;
pFloppy->m_trackimagedata = false;
m_formatTrack.DriveNotWritingTrack();
GetFrame().FrameDrawDiskStatus(); // Show track status (GH#201)
}
#if LOG_DISK_PHASES
LOG_DISK("%08X: track $%s magnet-states %d%d%d%d phase %d %s address $%4X last-stepper %.3fms\r\n",
(UINT32)g_nCumulativeCycles,
GetCurrentTrackString().c_str(),
(m_magnetStates >> 3) & 1,
(m_magnetStates >> 2) & 1,
(m_magnetStates >> 1) & 1,
(m_magnetStates >> 0) & 1,
(address >> 1) & 3, // phase
(address & 1) ? "on " : "off",
address,
((float)cycleDelta)/(CLK_6502_NTSC/1000.0));
#endif
}
//===========================================================================
void Disk2InterfaceCard::Destroy(void)
{
m_saveDiskImage = false;
EjectDisk(DRIVE_1);
m_saveDiskImage = false;
EjectDisk(DRIVE_2);
m_saveDiskImage = true;
}
//===========================================================================
void __stdcall Disk2InterfaceCard::Enable(WORD, WORD address, BYTE, BYTE, ULONG uExecutedCycles)
{
WORD newDrive = address & 1;
bool stateChanged = (newDrive != m_currDrive);
m_currDrive = newDrive;
#if LOG_DISK_ENABLE_DRIVE
LOG_DISK("%08X: enable drive: %d\r\n", (UINT32)g_nCumulativeCycles, m_currDrive);
#endif
m_floppyDrive[!m_currDrive].m_spinning = 0;
m_floppyDrive[!m_currDrive].m_writelight = 0;
CheckSpinning(stateChanged, uExecutedCycles);
}
//===========================================================================
// Return the filename
// . Used by Drive Buttons' tooltips
const std::string & Disk2InterfaceCard::GetFullDiskFilename(const int drive)
{
if (!m_floppyDrive[drive].m_disk.m_strFilenameInZip.empty())
return m_floppyDrive[drive].m_disk.m_strFilenameInZip;
return GetFullName(drive);
}
// Return the file or zip name
// . Used by Property Sheet Page (Disk)
const std::string & Disk2InterfaceCard::GetFullName(const int drive)
{
return m_floppyDrive[drive].m_disk.m_fullname;
}
// Return the imagename
// . Used by Drive Button's icons & Property Sheet Page (Save snapshot)
const std::string & Disk2InterfaceCard::GetBaseName(const int drive)
{
return m_floppyDrive[drive].m_disk.m_imagename;
}
void Disk2InterfaceCard::GetFilenameAndPathForSaveState(std::string& filename, std::string& path)
{
filename = "";
path = "";
for (UINT i=DRIVE_1; i<=DRIVE_2; i++)
{
if (IsDriveEmpty(i))
continue;
filename = GetBaseName(i);
std::string pathname = DiskGetFullPathName(i);
int idx = pathname.find_last_of(PATH_SEPARATOR);
if (idx >= 0 && idx+1 < (int)pathname.length()) // path exists?
{
path = pathname.substr(0, idx+1);
return;
}
_ASSERT(0);
break;
}
}
const std::string & Disk2InterfaceCard::DiskGetFullPathName(const int drive)
{
return ImageGetPathname(m_floppyDrive[drive].m_disk.m_imagehandle);
}
//===========================================================================
Disk_Status_e Disk2InterfaceCard::GetDriveLightStatus(const int drive)
{
if (IsDriveValid( drive ))
{
FloppyDrive* pDrive = &m_floppyDrive[ drive ];
if (pDrive->m_spinning)
{
if (pDrive->m_disk.m_bWriteProtected)
return DISK_STATUS_PROT;
if (pDrive->m_writelight)
return DISK_STATUS_WRITE;
else
return DISK_STATUS_READ;
}
else
{
return DISK_STATUS_OFF;
}
}
return DISK_STATUS_OFF;
}
void Disk2InterfaceCard::GetLightStatus(Disk_Status_e *pDisk1Status, Disk_Status_e *pDisk2Status)
{
if (pDisk1Status)
*pDisk1Status = GetDriveLightStatus(DRIVE_1);
if (pDisk2Status)
*pDisk2Status = GetDriveLightStatus(DRIVE_2);
}
//===========================================================================
// Pre: pathname likely to include path (but can also just be filename)
ImageError_e Disk2InterfaceCard::InsertDisk(const int drive, const std::string& pathname, const bool bForceWriteProtected, const bool bCreateIfNecessary)
{
FloppyDrive* pDrive = &m_floppyDrive[drive];
FloppyDisk* pFloppy = &pDrive->m_disk;
if (pFloppy->m_imagehandle)
EjectDisk(drive);
// Reset the disk's attributes, but preserve the drive's attributes (GH#138/Platoon, GH#640)
// . Changing the disk (in the drive) doesn't affect the drive's attributes.
pFloppy->clear();
const DWORD dwAttributes = GetFileAttributes(pathname.c_str());
if (dwAttributes == INVALID_FILE_ATTRIBUTES)
pFloppy->m_bWriteProtected = false; // Assume this is a new file to create (so it must be write-enabled to allow it to be formatted)
else
pFloppy->m_bWriteProtected = bForceWriteProtected ? true : (dwAttributes & FILE_ATTRIBUTE_READONLY);
// Check if image is being used by the other drive, and if so remove it in order so it can be swapped
{
const std::string & pszOtherPathname = DiskGetFullPathName(!drive);
char szCurrentPathname[MAX_PATH];
DWORD uNameLen = GetFullPathName(pathname.c_str(), MAX_PATH, szCurrentPathname, NULL);
if (uNameLen == 0 || uNameLen >= MAX_PATH)
strcpy_s(szCurrentPathname, MAX_PATH, pathname.c_str());
if (!strcmp(pszOtherPathname.c_str(), szCurrentPathname))
{
EjectDisk(!drive);
GetFrame().FrameRefreshStatus(DRAW_LEDS | DRAW_BUTTON_DRIVES | DRAW_DISK_STATUS);
}
}
ImageError_e Error = ImageOpen(pathname,
&pFloppy->m_imagehandle,
&pFloppy->m_bWriteProtected,
bCreateIfNecessary,
pFloppy->m_strFilenameInZip);
if (Error == eIMAGE_ERROR_NONE && ImageIsMultiFileZip(pFloppy->m_imagehandle))
{
TCHAR szText[100+MAX_PATH];
StringCbPrintf(szText, sizeof(szText), "Only the first file in a multi-file zip is supported\nUse disk image '%s' ?", pFloppy->m_strFilenameInZip.c_str());
int nRes = GetFrame().FrameMessageBox(szText, TEXT("Multi-Zip Warning"), MB_ICONWARNING | MB_YESNO | MB_SETFOREGROUND);
if (nRes == IDNO)
{
EjectDisk(drive);
Error = eIMAGE_ERROR_REJECTED_MULTI_ZIP;
}
}
if (Error == eIMAGE_ERROR_NONE)
{
GetImageTitle(pathname.c_str(), pFloppy->m_imagename, pFloppy->m_fullname);
Snapshot_UpdatePath();
GetFrame().Video_ResetScreenshotCounter(pFloppy->m_imagename);
if (g_nAppMode == MODE_LOGO)
InitFirmware(GetCxRomPeripheral());
}
else
{
GetFrame().Video_ResetScreenshotCounter("");
}
SaveLastDiskImage(drive);
return Error;
}
//===========================================================================
bool Disk2InterfaceCard::IsConditionForFullSpeed(void)
{
return m_floppyMotorOn && m_enhanceDisk;
}
//===========================================================================
void Disk2InterfaceCard::NotifyInvalidImage(const int drive, LPCTSTR pszImageFilename, const ImageError_e Error)
{
TCHAR szBuffer[MAX_PATH + 128];
switch (Error)
{
case eIMAGE_ERROR_UNABLE_TO_OPEN:
case eIMAGE_ERROR_UNABLE_TO_OPEN_GZ:
case eIMAGE_ERROR_UNABLE_TO_OPEN_ZIP:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to open the file %s."),
pszImageFilename);
break;
case eIMAGE_ERROR_BAD_SIZE:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to use the file %s\nbecause the ")
TEXT("disk image is an unsupported size."),
pszImageFilename);
break;
case eIMAGE_ERROR_BAD_FILE:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to use the file %s\nbecause the ")
TEXT("OS can't access it."),
pszImageFilename);
break;
case eIMAGE_ERROR_UNSUPPORTED:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to use the file %s\nbecause the ")
TEXT("disk image format is not recognized."),
pszImageFilename);
break;
case eIMAGE_ERROR_UNSUPPORTED_HDV:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to use the file %s\n")
TEXT("because this UniDisk 3.5/Apple IIGS/hard-disk image is not supported.\n")
TEXT("Try inserting as a hard-disk image instead."),
pszImageFilename);
break;
case eIMAGE_ERROR_GZ:
case eIMAGE_ERROR_ZIP:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to use the compressed file %s\nbecause the ")
TEXT("compressed disk image is corrupt/unsupported."),
pszImageFilename);
break;
case eIMAGE_ERROR_FAILED_TO_GET_PATHNAME:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unable to GetFullPathName() for the file: %s."),
pszImageFilename);
break;
case eIMAGE_ERROR_ZEROLENGTH_WRITEPROTECTED:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Unsupported zero-length write-protected file: %s."),
pszImageFilename);
break;
case eIMAGE_ERROR_FAILED_TO_INIT_ZEROLENGTH:
StringCbPrintf(
szBuffer,
MAX_PATH + 128,
TEXT("Failed to resize the zero-length file: %s."),
pszImageFilename);
break;
default:
// IGNORE OTHER ERRORS SILENTLY
return;
}
GetFrame().FrameMessageBox(
szBuffer,
g_pAppTitle.c_str(),
MB_ICONEXCLAMATION | MB_SETFOREGROUND);
}
//===========================================================================
bool Disk2InterfaceCard::GetProtect(const int drive)
{
if (!IsDriveValid(drive))
return true;
return m_floppyDrive[drive].m_disk.m_bWriteProtected;
}
//===========================================================================
void Disk2InterfaceCard::SetProtect(const int drive, const bool bWriteProtect)
{
if (!IsDriveValid(drive))
return;
m_floppyDrive[drive].m_disk.m_bWriteProtected = bWriteProtect;
}
//===========================================================================
bool Disk2InterfaceCard::IsDriveEmpty(const int drive)
{
if (!IsDriveValid(drive))
return true;
return m_floppyDrive[drive].m_disk.m_imagehandle == NULL;
}
//===========================================================================
bool Disk2InterfaceCard::IsWozImageInDrive(const int drive)
{
if (!IsDriveValid(drive))
return false;
return ImageIsWOZ(m_floppyDrive[drive].m_disk.m_imagehandle);
}
//===========================================================================
#if LOG_DISK_NIBBLES_WRITE
bool Disk2InterfaceCard::LogWriteCheckSyncFF(ULONG& uCycleDelta)
{
bool bIsSyncFF = false;
if (m_uWriteLastCycle == 0) // Reset to 0 when write mode is enabled
{
uCycleDelta = 0;
if (m_floppyLatch == 0xFF)
{
m_uSyncFFCount = 0;
bIsSyncFF = true;
}
}
else
{
uCycleDelta = (ULONG) (g_nCumulativeCycles - m_uWriteLastCycle);
if (m_floppyLatch == 0xFF && uCycleDelta > 32)
{
m_uSyncFFCount++;
bIsSyncFF = true;
}
}
m_uWriteLastCycle = g_nCumulativeCycles;
return bIsSyncFF;
}
#endif
//===========================================================================
void Disk2InterfaceCard::UpdateLatchForEmptyDrive(FloppyDrive* pDrive)
{
if (!pDrive->m_isConnected)
{
m_floppyLatch = 0x80; // GH#864
return;
}
// Drive connected
if ((g_nCumulativeCycles - pDrive->m_motorOnCycle) < MOTOR_ON_UNTIL_LSS_STABLE_CYCLES)
m_floppyLatch = 0x80; // GH#864
else
m_floppyLatch = rand() & 0xFF; // GH#748
}
void __stdcall Disk2InterfaceCard::ReadWrite(WORD pc, WORD addr, BYTE bWrite, BYTE d, ULONG uExecutedCycles)
{
FloppyDrive* pDrive = &m_floppyDrive[m_currDrive];
FloppyDisk* pFloppy = &pDrive->m_disk;
if (!pFloppy->m_trackimagedata && pFloppy->m_imagehandle)
ReadTrack(m_currDrive, uExecutedCycles);
if (!pFloppy->m_trackimagedata)
return UpdateLatchForEmptyDrive(pDrive);
// Improve precision of "authentic" drive mode - GH#125
UINT uSpinNibbleCount = 0;
if (!m_enhanceDisk && pDrive->m_spinning)
{
const ULONG nCycleDiff = (ULONG) (g_nCumulativeCycles - m_diskLastCycle);
m_diskLastCycle = g_nCumulativeCycles;
if (nCycleDiff > 40)
{
// 40 cycles for a write of a 10-bit 0xFF sync byte
uSpinNibbleCount = nCycleDiff >> 5; // ...but divide by 32 (not 40)
ULONG uWrapOffset = uSpinNibbleCount % pFloppy->m_nibbles;
pFloppy->m_byte += uWrapOffset;
if (pFloppy->m_byte >= pFloppy->m_nibbles)
pFloppy->m_byte -= pFloppy->m_nibbles;
#if LOG_DISK_NIBBLES_SPIN
UINT uCompleteRevolutions = uSpinNibbleCount / pFloppy->m_nibbles;
LOG_DISK("spin: revs=%d, nibbles=%d\r\n", uCompleteRevolutions, uWrapOffset);
#endif
}
}
if (!m_seqFunc.writeMode)
{
// Don't change latch if drive off after 1 second drive-off delay (UTAIIe page 9-13)
// "DRIVES OFF forces the data register to hold its present state." (UTAIIe page 9-12)
// Note: Sherwood Forest sets shift mode and reads with the drive off.
if (!pDrive->m_spinning) // GH#599
return;
const ULONG nReadCycleDiff = (ULONG) (g_nCumulativeCycles - m_diskLastReadLatchCycle);
// Support partial nibble read if disk reads are very close: (GH#582)
// . 6 cycles (1st->2nd read) for DOS 3.3 / $BD34: "read with delays to see if disk is spinning." (Beneath Apple DOS)
// . 6 cycles (1st->2nd read) for Curse of the Azure Bonds (loop to see if disk is spinning)
// . 25 cycles or higher fails for Legacy of the Ancients (GH#733)
// . 31 cycles is the max for a partial 8-bit nibble
const ULONG kReadAccessThreshold = 6; // Same for enhanced/authentic modes