diff --git a/js/cards/disk2.ts b/js/cards/disk2.ts index 7e44cbc..1b16d0d 100644 --- a/js/cards/disk2.ts +++ b/js/cards/disk2.ts @@ -3,14 +3,32 @@ import type { byte, Card, nibble, - ReadonlyUint8Array + ReadonlyUint8Array, } from '../types'; import { - DISK_PROCESSED, DriveNumber, DRIVE_NUMBERS, FloppyDisk, - FloppyFormat, FormatWorkerMessage, - FormatWorkerResponse, isNibbleDisk, isNoFloppyDisk, isWozDisk, JSONDisk, MassStorage, - MassStorageData, NibbleDisk, NibbleFormat, NoFloppyDisk, NO_DISK, PROCESS_BINARY, PROCESS_JSON, PROCESS_JSON_DISK, SupportedSectors, WozDisk + FormatWorkerMessage, + FormatWorkerResponse, + NibbleFormat, + DISK_PROCESSED, + DRIVE_NUMBERS, + DriveNumber, + JSONDisk, + PROCESS_BINARY, + PROCESS_JSON_DISK, + PROCESS_JSON, + MassStorage, + MassStorageData, + SupportedSectors, + FloppyDisk, + FloppyFormat, + WozDisk, + NibbleDisk, + isNibbleDisk, + isWozDisk, + NoFloppyDisk, + isNoFloppyDisk, + NO_DISK, } from '../formats/types'; import { @@ -18,11 +36,11 @@ import { createDiskFromJsonDisk } from '../formats/create_disk'; -import { jsonDecode, jsonEncode, readSector, _D13O, _DO, _PO } from '../formats/format_utils'; import { toHex } from '../util'; +import { jsonDecode, jsonEncode, readSector, _D13O, _DO, _PO } from '../formats/format_utils'; +import { BOOTSTRAP_ROM_16, BOOTSTRAP_ROM_13 } from '../roms/cards/disk2'; import Apple2IO from '../apple2io'; -import { BOOTSTRAP_ROM_13, BOOTSTRAP_ROM_16 } from '../roms/cards/disk2'; /** Softswitch locations */ const LOC = { @@ -114,16 +132,15 @@ const SEQUENCER_ROM_16 = [ const SEQUENCER_ROM: Record> = { 13: SEQUENCER_ROM_13, 16: SEQUENCER_ROM_16, -} as const; +}; /** Contents of the P5 ROM at 0xCnXX. */ const BOOTSTRAP_ROM: Record = { 13: BOOTSTRAP_ROM_13, 16: BOOTSTRAP_ROM_16, -} as const; +}; type LssClockCycle = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; -type LssState = nibble; type Phase = 0 | 1 | 2 | 3; /** @@ -158,7 +175,7 @@ const PHASE_DELTA = [ /** * State of the controller. */ -interface ControllerState { + interface ControllerState { /** Sectors supported by the controller. */ sectors: SupportedSectors; @@ -166,7 +183,7 @@ interface ControllerState { on: boolean; /** The active drive. */ - driveNo: DriveNumber; + drive: DriveNumber; /** The 8-cycle LSS clock. */ clock: LssClockCycle; @@ -184,32 +201,18 @@ interface ControllerState { bus: byte; } -/** Interface for drivers for various disk types. */ -interface DiskDriver { - tick(): void; - onQ6Low(): void; - onQ6High(readMode: boolean): void; - onDriveOn(): void; - onDriveOff(): void; - clampTrack(): void; - getState(): DriverState; - setState(state: DriverState): void; -} - -type DriverState = EmptyDriverState | NibbleDiskDriverState | WozDiskDriverState; - /** Callbacks triggered by events of the drive or controller. */ export interface Callbacks { /** Called when a drive turns on or off. */ - driveLight: (driveNo: DriveNumber, on: boolean) => void; + driveLight: (drive: DriveNumber, on: boolean) => void; /** * Called when a disk has been written to. For performance and integrity, * this is only called when the drive stops spinning or is removed from * the drive. */ - dirty: (driveNo: DriveNumber, dirty: boolean) => void; + dirty: (drive: DriveNumber, dirty: boolean) => void; /** Called when a disk is inserted or removed from the drive. */ - label: (driveNo: DriveNumber, name?: string, side?: string) => void; + label: (drive: DriveNumber, name?: string, side?: string) => void; } /** Common information for Nibble and WOZ disks. */ @@ -228,7 +231,6 @@ interface Drive { interface DriveState { disk: FloppyDisk; - driver: DriverState; readOnly: boolean; track: byte; head: byte; @@ -240,7 +242,7 @@ interface DriveState { // TODO(flan): It's unclear whether reusing ControllerState here is a good idea. interface State { drives: DriveState[]; - driver: DriverState[]; + skip: number; controllerState: ControllerState; } @@ -253,7 +255,7 @@ function getDiskState(disk: FloppyDisk): FloppyDisk { const { encoding, metadata, readOnly } = disk; return { encoding, - metadata: { ...metadata }, + metadata: {...metadata}, readOnly, }; } @@ -294,223 +296,61 @@ function getDiskState(disk: FloppyDisk): FloppyDisk { throw new Error('Unknown drive state'); } -interface EmptyDriverState { } +/** + * Emulates the 16-sector and 13-sector versions of the Disk ][ drive and controller. + */ +export default class DiskII implements Card, MassStorage { -class EmptyDriver implements DiskDriver { - constructor(private readonly drive: Drive) { } - - tick(): void { - // do nothing - } - - onQ6Low(): void { - // do nothing - } - - onQ6High(_readMode: boolean): void { - // do nothing - } - - onDriveOn(): void { - // do nothing - } - - onDriveOff(): void { - // do nothing - } - - clampTrack(): void { - // For empty drives, the emulator clamps the track to 0 to 34, - // but real Disk II drives can seek past track 34 by at least a - // half track, usually a full track. Some 3rd party drives can - // seek to track 39. - if (this.drive.track < 0) { - this.drive.track = 0; + private drives: Record = { + 1: { // Drive 1 + track: 0, + head: 0, + phase: 0, + readOnly: false, + dirty: false, + }, + 2: { // Drive 2 + track: 0, + head: 0, + phase: 0, + readOnly: false, + dirty: false, } - if (this.drive.track > 34) { - this.drive.track = 34; + }; + + private disks: Record = { + 1: { + encoding: NO_DISK, + readOnly: false, + metadata: { name: 'Disk 1' }, + }, + 2: { + encoding: NO_DISK, + readOnly: false, + metadata: { name: 'Disk 2' }, } - } + }; - getState() { - return {}; - } + private state: ControllerState; - setState(_state: EmptyDriverState): void { - // do nothing - } -} - -abstract class BaseDiskDriver implements DiskDriver { - constructor( - protected readonly driveNo: DriveNumber, - protected readonly drive: Drive, - protected readonly disk: NibbleDisk | WozDisk, - protected readonly controller: ControllerState) { } - - /** Called frequently to ensure the disk is spinning. */ - abstract tick(): void; - - /** Called when Q6 is set LOW. */ - abstract onQ6Low(): void; - - /** Called when Q6 is set HIGH. */ - abstract onQ6High(readMode: boolean): void; - - /** - * Called when drive is turned on. This is guaranteed to be called - * only when the associated drive is toggled from off to on. This - * is also guaranteed to be called when a new disk is inserted when - * the drive is already on. - */ - abstract onDriveOn(): void; - - /** - * Called when drive is turned off. This is guaranteed to be called - * only when the associated drive is toggled from on to off. - */ - abstract onDriveOff(): void; - - debug(..._args: unknown[]) { - // debug(...args); - } - - /** - * Called every time the head moves to clamp the track to a valid - * range. - */ - abstract clampTrack(): void; - - isOn(): boolean { - return this.controller.on && this.controller.driveNo === this.driveNo; - } - - isWriteProtected(): boolean { - return this.drive.readOnly; - } - - abstract getState(): DriverState; - - abstract setState(state: DriverState): void; -} - -interface NibbleDiskDriverState { - skip: number; - nibbleCount: number; -} - -class NibbleDiskDriver extends BaseDiskDriver { /** * When `1`, the next nibble will be available for read; when `0`, * the card is pretending to wait for data to be shifted in by the * sequencer. */ - private skip: number = 0; - /** Number of nibbles reads since the drive was turned on. */ - private nibbleCount: number = 0; + private skip = 0; + /** Drive off timeout id or null. */ + private offTimeout: number | null = null; + /** Current drive object. Must only be set by `updateActiveDrive()`. */ + private curDrive: Drive; + /** Current disk object. Must only be set by `updateActiveDrive()`. */ + private curDisk: FloppyDisk; - constructor( - driveNo: DriveNumber, - drive: Drive, - readonly disk: NibbleDisk, - controller: ControllerState, - private readonly onDirty: () => void) { - super(driveNo, drive, disk, controller); - } + /** Nibbles read this on cycle */ + private nibbleCount = 0; - tick(): void { - // do nothing - } - - onQ6Low(): void { - const drive = this.drive; - const disk = this.disk; - if (this.isOn() && (this.skip || this.controller.q7)) { - const track = disk.tracks[drive.track >> 2]; - if (track && track.length) { - if (drive.head >= track.length) { - drive.head = 0; - } - - if (this.controller.q7) { - const writeProtected = disk.readOnly; - if (!writeProtected) { - track[drive.head] = this.controller.bus; - drive.dirty = true; - this.onDirty(); - } - } else { - this.controller.latch = track[drive.head]; - this.nibbleCount++; - } - - ++drive.head; - } - } else { - this.controller.latch = 0; - } - this.skip = (++this.skip % 2); - } - - onQ6High(readMode: boolean): void { - const drive = this.drive; - if (readMode && !this.controller.q7) { - const writeProtected = drive.readOnly; - if (writeProtected) { - this.controller.latch = 0xff; - this.debug('Setting readOnly'); - } else { - this.controller.latch >>= 1; - this.debug('Clearing readOnly'); - } - } - } - - onDriveOn(): void { - this.nibbleCount = 0; - } - - onDriveOff(): void { - this.debug('nibbles read', this.nibbleCount); - } - - clampTrack(): void { - // For NibbleDisks, the emulator clamps the track to the available - // range. - if (this.drive.track < 0) { - this.drive.track = 0; - } - const lastTrack = 35 * 4 - 1; - if (this.drive.track > lastTrack) { - this.drive.track = lastTrack; - } - } - - getState(): NibbleDiskDriverState { - const { skip, nibbleCount } = this; - return { skip, nibbleCount }; - } - - setState(state: NibbleDiskDriverState) { - this.skip = state.skip; - this.nibbleCount = state.nibbleCount; - } -} - -interface WozDiskDriverState { - clock: LssClockCycle; - state: LssState; - lastCycles: number; - zeros: number; -} - -class WozDiskDriver extends BaseDiskDriver { - /** Logic state sequencer clock cycle. */ - private clock: LssClockCycle; - /** Logic state sequencer state. */ - private state: LssState; /** Current CPU cycle count. */ - private lastCycles: number = 0; + private lastCycles = 0; /** * Number of zeros read in a row. The Disk ][ can only read two zeros in a * row reliably; above that and the drive starts reporting garbage. See @@ -518,30 +358,47 @@ class WozDiskDriver extends BaseDiskDriver { */ private zeros = 0; - constructor( - driveNo: DriveNumber, - drive: Drive, - readonly disk: WozDisk, - controller: ControllerState, - private readonly onDirty: () => void, - private readonly io: Apple2IO) { - super(driveNo, drive, disk, controller); + private worker: Worker; - // From the example in UtA2e, p. 9-29, col. 1, para. 1., this is - // essentially the start of the sequencer loop and produces - // correctly synced nibbles immediately. Starting at state 0 - // would introduce a spurrious 1 in the latch at the beginning, - // which requires reading several more sync bytes to sync up. - this.state = 2; - this.clock = 0; - } + /** Builds a new Disk ][ card. */ + constructor(private io: Apple2IO, private callbacks: Callbacks, private sectors: SupportedSectors = 16) { + this.debug('Disk ]['); - onDriveOn(): void { this.lastCycles = this.io.cycles(); + this.state = { + sectors, + bus: 0, + latch: 0, + drive: 1, + on: false, + q6: false, + q7: false, + clock: 0, + // From the example in UtA2e, p. 9-29, col. 1, para. 1., this is + // essentially the start of the sequencer loop and produces + // correctly synced nibbles immediately. Starting at state 0 + // would introduce a spurrious 1 in the latch at the beginning, + // which requires reading several more sync bytes to sync up. + state: 2, + }; + + this.updateActiveDrive(); + + this.initWorker(); } - onDriveOff(): void { - // nothing + /** Updates the active drive based on the controller state. */ + private updateActiveDrive() { + this.curDrive = this.drives[this.state.drive]; + this.curDisk = this.disks[this.state.drive]; + } + + private debug(..._args: unknown[]) { + // debug(..._args); + } + + public head(): number { + return this.curDrive.head; } /** @@ -586,27 +443,22 @@ class WozDiskDriver extends BaseDiskDriver { let workCycles = (cycles - this.lastCycles) * 2; this.lastCycles = cycles; - const drive = this.drive; - const disk = this.disk; - const controller = this.controller; - - // TODO(flan): Improve unformatted track behavior. The WOZ - // documentation suggests using an empty track of 6400 bytes - // (51,200 bits). + if (!isWozDisk(this.curDisk)) { + return; + } const track = - disk.rawTracks[disk.trackMap[drive.track]] || [0]; + this.curDisk.rawTracks[this.curDisk.trackMap[this.curDrive.track]] || [0]; + + const state = this.state; while (workCycles-- > 0) { let pulse: number = 0; - if (this.clock === 4) { - pulse = track[drive.head]; + if (state.clock === 4) { + pulse = track[this.curDrive.head]; if (!pulse) { // More than 2 zeros can not be read reliably. - // TODO(flan): Revisit with the new MC3470 - // suggested 4-bit window behavior. if (++this.zeros > 2) { - const r = Math.random(); - pulse = r >= 0.5 ? 1 : 0; + pulse = Math.random() >= 0.5 ? 1 : 0; } } else { this.zeros = 0; @@ -615,197 +467,91 @@ class WozDiskDriver extends BaseDiskDriver { let idx = 0; idx |= pulse ? 0x00 : 0x01; - idx |= controller.latch & 0x80 ? 0x02 : 0x00; - idx |= controller.q6 ? 0x04 : 0x00; - idx |= controller.q7 ? 0x08 : 0x00; - idx |= this.state << 4; + idx |= state.latch & 0x80 ? 0x02 : 0x00; + idx |= state.q6 ? 0x04 : 0x00; + idx |= state.q7 ? 0x08 : 0x00; + idx |= state.state << 4; - const command = SEQUENCER_ROM[controller.sectors][idx]; + const command = SEQUENCER_ROM[this.sectors][idx]; - this.debug(`clock: ${this.clock} state: ${toHex(this.state)} pulse: ${pulse} command: ${toHex(command)} q6: ${controller.q6} latch: ${toHex(controller.latch)}`); + this.debug(`clock: ${state.clock} state: ${toHex(state.state)} pulse: ${pulse} command: ${toHex(command)} q6: ${state.q6} latch: ${toHex(state.latch)}`); switch (command & 0xf) { case 0x0: // CLR - controller.latch = 0; + state.latch = 0; break; case 0x8: // NOP break; case 0x9: // SL0 - controller.latch = (controller.latch << 1) & 0xff; + state.latch = (state.latch << 1) & 0xff; break; case 0xA: // SR - controller.latch >>= 1; - if (this.isWriteProtected()) { - controller.latch |= 0x80; + state.latch >>= 1; + if (this.curDrive.readOnly) { + state.latch |= 0x80; } break; case 0xB: // LD - controller.latch = controller.bus; - this.debug('Loading', toHex(controller.latch), 'from bus'); + state.latch = state.bus; + this.debug('Loading', toHex(state.latch), 'from bus'); break; case 0xD: // SL1 - controller.latch = ((controller.latch << 1) | 0x01) & 0xff; + state.latch = ((state.latch << 1) | 0x01) & 0xff; break; default: this.debug(`unknown command: ${toHex(command & 0xf)}`); } - this.state = (command >> 4 & 0xF) as LssState; + state.state = (command >> 4 & 0xF) as nibble; - if (this.clock === 4) { - if (this.isOn()) { - if (controller.q7) { - // TODO(flan): This assumes that writes are happening in - // a "friendly" way, namely where the track was originally - // written. To do this correctly, the virtual head should - // actually keep track of the current quarter track plus - // the one on each side. Then, when writing, it should - // check that all three are actually the same rawTrack. If - // they aren't, then the trackMap has to be updated as - // well. - track[drive.head] = this.state & 0x8 ? 0x01 : 0x00; - this.debug('Wrote', this.state & 0x8 ? 0x01 : 0x00); - drive.dirty = true; - this.onDirty(); + if (state.clock === 4) { + if (state.on) { + if (state.q7) { + track[this.curDrive.head] = state.state & 0x8 ? 0x01 : 0x00; + this.debug('Wrote', state.state & 0x8 ? 0x01 : 0x00); } - if (++drive.head >= track.length) { - drive.head = 0; + if (++this.curDrive.head >= track.length) { + this.curDrive.head = 0; } } } - if (++this.clock > 7) { - this.clock = 0; + if (++state.clock > 7) { + state.clock = 0; } } } - tick(): void { - this.moveHead(); - } - - onQ6High(_readMode: boolean): void { - // nothing? - } - - onQ6Low(): void { - // nothing? - } - - clampTrack(): void { - // For NibbleDisks, the emulator clamps the track to the available - // range. - if (this.drive.track < 0) { - this.drive.track = 0; + // Only called for non-WOZ disks + private readWriteNext() { + if (!isNibbleDisk(this.curDisk)) { + return; } - const lastTrack = this.disk.trackMap.length - 1; - if (this.drive.track > lastTrack) { - this.drive.track = lastTrack; + const state = this.state; + if (state.on && (this.skip || state.q7)) { + const track = this.curDisk.tracks[this.curDrive.track >> 2]; + if (track && track.length) { + if (this.curDrive.head >= track.length) { + this.curDrive.head = 0; + } + + if (state.q7) { + if (!this.curDrive.readOnly) { + track[this.curDrive.head] = state.bus; + if (!this.curDrive.dirty) { + this.updateDirty(state.drive, true); + } + } + } else { + state.latch = track[this.curDrive.head]; + } + + ++this.curDrive.head; + } + } else { + state.latch = 0; } - } - - getState(): WozDiskDriverState { - const { clock, state, lastCycles, zeros } = this; - return { clock, state, lastCycles, zeros }; - } - - setState(state: WozDiskDriverState) { - this.clock = state.clock; - this.state = state.state; - this.lastCycles = state.lastCycles; - this.zeros = state.zeros; - } -} - -/** - * Emulates the 16-sector and 13-sector versions of the Disk ][ drive and controller. - */ -export default class DiskII implements Card, MassStorage { - - private drives: Record = { - 1: { // Drive 1 - track: 0, - head: 0, - phase: 0, - readOnly: false, - dirty: false, - }, - 2: { // Drive 2 - track: 0, - head: 0, - phase: 0, - readOnly: false, - dirty: false, - } - }; - - private disks: Record = { - 1: { - encoding: NO_DISK, - readOnly: false, - metadata: { name: 'Disk 1' }, - }, - 2: { - encoding: NO_DISK, - readOnly: false, - metadata: { name: 'Disk 2' }, - } - }; - - private driver: Record = { - 1: new EmptyDriver(this.drives[1]), - 2: new EmptyDriver(this.drives[2]), - }; - - private state: ControllerState; - - /** Drive off timeout id or null. */ - private offTimeout: number | null = null; - /** Current drive object. Must only be set by `updateActiveDrive()`. */ - private curDrive: Drive; - /** Current driver object. Must only be set by `updateAcivetDrive()`. */ - private curDriver: DiskDriver; - - private worker: Worker; - - /** Builds a new Disk ][ card. */ - constructor(private io: Apple2IO, private callbacks: Callbacks, private sectors: SupportedSectors = 16) { - this.debug('Disk ]['); - - this.state = { - sectors, - bus: 0, - latch: 0, - driveNo: 1, - on: false, - q6: false, - q7: false, - clock: 0, - // From the example in UtA2e, p. 9-29, col. 1, para. 1., this is - // essentially the start of the sequencer loop and produces - // correctly synced nibbles immediately. Starting at state 0 - // would introduce a spurrious 1 in the latch at the beginning, - // which requires reading several more sync bytes to sync up. - state: 2, - }; - - this.updateActiveDrive(); - - this.initWorker(); - } - - /** Updates the active drive based on the controller state. */ - private updateActiveDrive() { - this.curDrive = this.drives[this.state.driveNo]; - this.curDriver = this.driver[this.state.driveNo]; - } - - private debug(..._args: unknown[]) { - // debug(..._args); - } - - public head(): number { - return this.curDrive.head; + this.skip = (++this.skip % 2); } /** @@ -833,7 +579,21 @@ export default class DiskII implements Card, MassStorage { this.curDrive.phase = phase; } - this.curDriver.clampTrack(); + // The emulator clamps the track to the valid track range available + // in the image, but real Disk II drives can seek past track 34 by + // at least a half track, usually a full track. Some 3rd party + // drives can seek to track 39. + const maxTrack = isNibbleDisk(this.curDisk) + ? this.curDisk.tracks.length * 4 - 1 + : (isWozDisk(this.curDisk) + ? this.curDisk.trackMap.length - 1 + : 0); + if (this.curDrive.track > maxTrack) { + this.curDrive.track = maxTrack; + } + if (this.curDrive.track < 0x0) { + this.curDrive.track = 0x0; + } // debug( // 'Drive', _drive, 'track', toHex(_cur.track >> 2) + '.' + (_cur.track & 0x3), @@ -880,8 +640,8 @@ export default class DiskII implements Card, MassStorage { this.offTimeout = window.setTimeout(() => { this.debug('Drive Off'); state.on = false; - this.callbacks.driveLight(state.driveNo, false); - this.curDriver.onDriveOff(); + this.callbacks.driveLight(state.drive, false); + this.debug('nibbles read', this.nibbleCount); }, 1000); } } @@ -894,15 +654,16 @@ export default class DiskII implements Card, MassStorage { } if (!state.on) { this.debug('Drive On'); + this.nibbleCount = 0; state.on = true; - this.callbacks.driveLight(state.driveNo, true); - this.curDriver.onDriveOn(); + this.lastCycles = this.io.cycles(); + this.callbacks.driveLight(state.drive, true); } break; case LOC.DRIVE1: // 0x0a this.debug('Disk 1'); - state.driveNo = 1; + state.drive = 1; this.updateActiveDrive(); if (state.on) { this.callbacks.driveLight(2, false); @@ -911,7 +672,7 @@ export default class DiskII implements Card, MassStorage { break; case LOC.DRIVE2: // 0x0b this.debug('Disk 2'); - state.driveNo = 2; + state.drive = 2; this.updateActiveDrive(); if (state.on) { this.callbacks.driveLight(1, false); @@ -921,12 +682,30 @@ export default class DiskII implements Card, MassStorage { case LOC.DRIVEREAD: // 0x0c (Q6L) Shift state.q6 = false; - this.curDriver.onQ6Low(); + if (state.q7) { + this.debug('clearing _q6/SHIFT'); + } + if (isNibbleDisk(this.curDisk)) { + this.readWriteNext(); + } break; case LOC.DRIVEWRITE: // 0x0d (Q6H) LOAD state.q6 = true; - this.curDriver.onQ6High(readMode); + if (state.q7) { + this.debug('setting _q6/LOAD'); + } + if (isNibbleDisk(this.curDisk)) { + if (readMode && !state.q7) { + if (this.curDrive.readOnly) { + state.latch = 0xff; + this.debug('Setting readOnly'); + } else { + state.latch = state.latch >> 1; + this.debug('Clearing readOnly'); + } + } + } break; case LOC.DRIVEREADMODE: // 0x0e (Q7L) @@ -942,7 +721,7 @@ export default class DiskII implements Card, MassStorage { break; } - this.tick(); + this.moveHead(); if (readMode) { // According to UtAIIe, p. 9-13 to 9-14, any even address can be @@ -950,6 +729,9 @@ export default class DiskII implements Card, MassStorage { // also cause conflicts with the disk controller commands. if ((off & 0x01) === 0) { result = state.latch; + if (result & 0x80) { + this.nibbleCount++; + } } else { result = 0; } @@ -962,10 +744,10 @@ export default class DiskII implements Card, MassStorage { return result; } - private updateDirty(driveNo: DriveNumber, dirty: boolean) { - this.drives[driveNo].dirty = dirty; + private updateDirty(drive: DriveNumber, dirty: boolean) { + this.drives[drive].dirty = dirty; if (this.callbacks.dirty) { - this.callbacks.dirty(driveNo, dirty); + this.callbacks.dirty(drive, dirty); } } @@ -984,38 +766,36 @@ export default class DiskII implements Card, MassStorage { reset() { const state = this.state; if (state.on) { - this.callbacks.driveLight(state.driveNo, false); + this.callbacks.driveLight(state.drive, false); state.q7 = false; state.on = false; - state.driveNo = 1; + state.drive = 1; } this.updateActiveDrive(); } tick() { - this.curDriver.tick(); + this.moveHead(); } - private getDriveState(driveNo: DriveNumber): DriveState { - const curDrive = this.drives[driveNo]; - const curDisk = this.disks[driveNo]; - const curDriver = this.driver[driveNo]; + private getDriveState(drive: DriveNumber): DriveState { + const curDrive = this.drives[drive]; + const curDisk = this.disks[drive]; const { readOnly, track, head, phase, dirty } = curDrive; return { disk: getDiskState(curDisk), - driver: curDriver.getState(), readOnly, track, head, phase, dirty, - }; + }; } getState(): State { const result = { drives: [] as DriveState[], - driver: [] as DriverState[], + skip: this.skip, controllerState: { ...this.state }, }; result.drives[1] = this.getDriveState(1); @@ -1024,22 +804,21 @@ export default class DiskII implements Card, MassStorage { return result; } - private setDriveState(driveNo: DriveNumber, state: DriveState) { + private setDriveState(drive: DriveNumber, state: DriveState) { const { track, head, phase, readOnly, dirty } = state; - this.drives[driveNo] = { + this.drives[drive] = { track, head, phase, readOnly, dirty, }; - const disk = getDiskState(state.disk); - this.setDiskInternal(driveNo, disk); - this.driver[driveNo].setState(state.driver); + this.disks[drive] = getDiskState(state.disk); } - + setState(state: State) { + this.skip = state.skip; this.state = { ...state.controllerState }; for (const d of DRIVE_NUMBERS) { this.setDriveState(d, state.drives[d]); @@ -1064,8 +843,8 @@ export default class DiskII implements Card, MassStorage { } /** Reads the given track and physical sector. */ - rwts(driveNo: DriveNumber, track: byte, sector: byte) { - const curDisk = this.disks[driveNo]; + rwts(disk: DriveNumber, track: byte, sector: byte) { + const curDisk = this.disks[disk]; if (!isNibbleDisk(curDisk)) { throw new Error('Can\'t read WOZ disks'); } @@ -1074,12 +853,12 @@ export default class DiskII implements Card, MassStorage { /** Sets the data for `drive` from `disk`, which is expected to be JSON. */ // TODO(flan): This implementation is not very safe. - setDisk(driveNo: DriveNumber, jsonDisk: JSONDisk) { + setDisk(drive: DriveNumber, jsonDisk: JSONDisk) { if (this.worker) { const message: FormatWorkerMessage = { type: PROCESS_JSON_DISK, payload: { - driveNo: driveNo, + drive, jsonDisk }, }; @@ -1088,39 +867,39 @@ export default class DiskII implements Card, MassStorage { } else { const disk = createDiskFromJsonDisk(jsonDisk); if (disk) { - this.insertDisk(driveNo, disk); + this.insertDisk(drive, disk); return true; } } return false; } - getJSON(driveNo: DriveNumber, pretty: boolean = false) { - const curDisk = this.disks[driveNo]; + getJSON(drive: DriveNumber, pretty: boolean = false) { + const curDisk = this.disks[drive]; if (!isNibbleDisk(curDisk)) { throw new Error('Can\'t save WOZ disks to JSON'); } return jsonEncode(curDisk, pretty); } - setJSON(driveNo: DriveNumber, json: string) { + setJSON(drive: DriveNumber, json: string) { if (this.worker) { const message: FormatWorkerMessage = { type: PROCESS_JSON, payload: { - driveNo: driveNo, + drive, json }, }; this.worker.postMessage(message); } else { const disk = jsonDecode(json); - this.insertDisk(driveNo, disk); + this.insertDisk(drive, disk); } return true; } - setBinary(driveNo: DriveNumber, name: string, fmt: FloppyFormat, rawData: ArrayBuffer) { + setBinary(drive: DriveNumber, name: string, fmt: FloppyFormat, rawData: ArrayBuffer) { const readOnly = false; const volume = 254; const options = { @@ -1134,7 +913,7 @@ export default class DiskII implements Card, MassStorage { const message: FormatWorkerMessage = { type: PROCESS_BINARY, payload: { - driveNo: driveNo, + drive, fmt, options, } @@ -1145,7 +924,7 @@ export default class DiskII implements Card, MassStorage { } else { const disk = createDisk(fmt, options); if (disk) { - this.insertDisk(driveNo, disk); + this.insertDisk(drive, disk); return true; } } @@ -1165,7 +944,7 @@ export default class DiskII implements Card, MassStorage { switch (data.type) { case DISK_PROCESSED: { - const { driveNo: drive, disk } = data.payload; + const { drive, disk } = data.payload; if (disk) { this.insertDisk(drive, disk); } @@ -1178,39 +957,13 @@ export default class DiskII implements Card, MassStorage { } } - private setDiskInternal(driveNo: DriveNumber, disk: FloppyDisk) { - this.disks[driveNo] = disk; - if (isNoFloppyDisk(disk)) { - this.driver[driveNo] = new EmptyDriver(this.drives[driveNo]); - } else if (isNibbleDisk(disk)) { - this.driver[driveNo] = - new NibbleDiskDriver( - driveNo, - this.drives[driveNo], - disk, - this.state, - () => this.updateDirty(driveNo, true)); - } else if (isWozDisk(disk)) { - this.driver[driveNo] = - new WozDiskDriver( - driveNo, - this.drives[driveNo], - disk, - this.state, - () => this.updateDirty(driveNo, true), - this.io); - } else { - throw new Error(`Unknown disk format ${disk.encoding}`); - } + private insertDisk(drive: DriveNumber, disk: FloppyDisk) { + this.disks[drive] = disk; + this.drives[drive].head = 0; this.updateActiveDrive(); - } - - private insertDisk(driveNo: DriveNumber, disk: FloppyDisk) { - this.setDiskInternal(driveNo, disk); - this.drives[driveNo].head = 0; const { name, side } = disk.metadata; - this.updateDirty(driveNo, this.drives[driveNo].dirty); - this.callbacks.label(driveNo, name, side); + this.updateDirty(drive, true); + this.callbacks.label(drive, name, side); } /** @@ -1223,8 +976,8 @@ export default class DiskII implements Card, MassStorage { * an error will be thrown. Using `ext == 'nib'` will always return * an image. */ - getBinary(driveNo: DriveNumber, ext?: Exclude): MassStorageData | null { - const curDisk = this.disks[driveNo]; + getBinary(drive: DriveNumber, ext?: Exclude): MassStorageData | null { + const curDisk = this.disks[drive]; if (!isNibbleDisk(curDisk)) { return null; } @@ -1271,8 +1024,8 @@ export default class DiskII implements Card, MassStorage { } // TODO(flan): Does not work with WOZ or D13 disks - getBase64(driveNo: DriveNumber) { - const curDisk = this.disks[driveNo]; + getBase64(drive: DriveNumber) { + const curDisk = this.disks[drive]; if (!isNibbleDisk(curDisk)) { return null; } diff --git a/js/cards/smartport.ts b/js/cards/smartport.ts index 1ffb93a..1137e14 100644 --- a/js/cards/smartport.ts +++ b/js/cards/smartport.ts @@ -18,9 +18,9 @@ export interface SmartPortOptions { } export interface Callbacks { - driveLight: (driveNo: DriveNumber, on: boolean) => void; - dirty: (driveNo: DriveNumber, dirty: boolean) => void; - label: (driveNo: DriveNumber, name?: string, side?: string) => void; + driveLight: (drive: DriveNumber, on: boolean) => void; + dirty: (drive: DriveNumber, dirty: boolean) => void; + label: (drive: DriveNumber, name?: string, side?: string) => void; } class Address { @@ -152,15 +152,15 @@ export default class SmartPort implements Card, MassStorage, Restor // debug.apply(this, arguments); } - private driveLight(driveNo: DriveNumber) { - if (!this.busy[driveNo]) { - this.busy[driveNo] = true; - this.callbacks?.driveLight(driveNo, true); + private driveLight(drive: DriveNumber) { + if (!this.busy[drive]) { + this.busy[drive] = true; + this.callbacks?.driveLight(drive, true); } - clearTimeout(this.busyTimeout[driveNo]); - this.busyTimeout[driveNo] = setTimeout(() => { - this.busy[driveNo] = false; - this.callbacks?.driveLight(driveNo, false); + clearTimeout(this.busyTimeout[drive]); + this.busyTimeout[drive] = setTimeout(() => { + this.busy[drive] = false; + this.callbacks?.driveLight(drive, false); }, 100); } @@ -168,7 +168,7 @@ export default class SmartPort implements Card, MassStorage, Restor * dumpBlock */ - dumpBlock(driveNo: DriveNumber, block: number) { + dumpBlock(drive: DriveNumber, block: number) { let result = ''; let b; let jdx; @@ -176,7 +176,7 @@ export default class SmartPort implements Card, MassStorage, Restor for (let idx = 0; idx < 32; idx++) { result += toHex(idx << 4, 4) + ': '; for (jdx = 0; jdx < 16; jdx++) { - b = this.disks[driveNo].blocks[block][idx * 16 + jdx]; + b = this.disks[drive].blocks[block][idx * 16 + jdx]; if (jdx === 8) { result += ' '; } @@ -184,7 +184,7 @@ export default class SmartPort implements Card, MassStorage, Restor } result += ' '; for (jdx = 0; jdx < 16; jdx++) { - b = this.disks[driveNo].blocks[block][idx * 16 + jdx] & 0x7f; + b = this.disks[drive].blocks[block][idx * 16 + jdx] & 0x7f; if (jdx === 8) { result += ' '; } @@ -203,9 +203,9 @@ export default class SmartPort implements Card, MassStorage, Restor * getDeviceInfo */ - getDeviceInfo(state: CpuState, driveNo: DriveNumber) { - if (this.disks[driveNo]) { - const blocks = this.disks[driveNo].blocks.length; + getDeviceInfo(state: CpuState, drive: DriveNumber) { + if (this.disks[drive]) { + const blocks = this.disks[drive].blocks.length; state.x = blocks & 0xff; state.y = blocks >> 8; @@ -221,23 +221,23 @@ export default class SmartPort implements Card, MassStorage, Restor * readBlock */ - readBlock(state: CpuState, driveNo: DriveNumber, block: number, buffer: Address) { - this.debug(`read drive=${driveNo}`); + readBlock(state: CpuState, drive: DriveNumber, block: number, buffer: Address) { + this.debug(`read drive=${drive}`); this.debug(`read buffer=${buffer.toString()}`); this.debug(`read block=$${toHex(block)}`); - if (!this.disks[driveNo]?.blocks.length) { - debug('Drive', driveNo, 'is empty'); + if (!this.disks[drive]?.blocks.length) { + debug('Drive', drive, 'is empty'); state.a = DEVICE_OFFLINE; state.s |= flags.C; return; } // debug('read', '\n' + dumpBlock(drive, block)); - this.driveLight(driveNo); + this.driveLight(drive); for (let idx = 0; idx < 512; idx++) { - buffer.writeByte(this.disks[driveNo].blocks[block][idx]); + buffer.writeByte(this.disks[drive].blocks[block][idx]); buffer = buffer.inc(1); } @@ -249,30 +249,30 @@ export default class SmartPort implements Card, MassStorage, Restor * writeBlock */ - writeBlock(state: CpuState, driveNo: DriveNumber, block: number, buffer: Address) { - this.debug(`write drive=${driveNo}`); + writeBlock(state: CpuState, drive: DriveNumber, block: number, buffer: Address) { + this.debug(`write drive=${drive}`); this.debug(`write buffer=${buffer.toString()}`); this.debug(`write block=$${toHex(block)}`); - if (!this.disks[driveNo]?.blocks.length) { - debug('Drive', driveNo, 'is empty'); + if (!this.disks[drive]?.blocks.length) { + debug('Drive', drive, 'is empty'); state.a = DEVICE_OFFLINE; state.s |= flags.C; return; } - if (this.disks[driveNo].readOnly) { - debug('Drive', driveNo, 'is write protected'); + if (this.disks[drive].readOnly) { + debug('Drive', drive, 'is write protected'); state.a = WRITE_PROTECTED; state.s |= flags.C; return; } // debug('write', '\n' + dumpBlock(drive, block)); - this.driveLight(driveNo); + this.driveLight(drive); for (let idx = 0; idx < 512; idx++) { - this.disks[driveNo].blocks[block][idx] = buffer.readByte(); + this.disks[drive].blocks[block][idx] = buffer.readByte(); buffer = buffer.inc(1); } state.a = 0; @@ -283,25 +283,25 @@ export default class SmartPort implements Card, MassStorage, Restor * formatDevice */ - formatDevice(state: CpuState, driveNo: DriveNumber) { - if (!this.disks[driveNo]?.blocks.length) { - debug('Drive', driveNo, 'is empty'); + formatDevice(state: CpuState, drive: DriveNumber) { + if (!this.disks[drive]?.blocks.length) { + debug('Drive', drive, 'is empty'); state.a = DEVICE_OFFLINE; state.s |= flags.C; return; } - if (this.disks[driveNo].readOnly) { - debug('Drive', driveNo, 'is write protected'); + if (this.disks[drive].readOnly) { + debug('Drive', drive, 'is write protected'); state.a = WRITE_PROTECTED; state.s |= flags.C; return; } - for (let idx = 0; idx < this.disks[driveNo].blocks.length; idx++) { - this.disks[driveNo].blocks[idx] = new Uint8Array(); + for (let idx = 0; idx < this.disks[drive].blocks.length; idx++) { + this.disks[drive].blocks[idx] = new Uint8Array(); for (let jdx = 0; jdx < 512; jdx++) { - this.disks[driveNo].blocks[idx][jdx] = 0; + this.disks[drive].blocks[idx][jdx] = 0; } } @@ -549,18 +549,18 @@ export default class SmartPort implements Card, MassStorage, Restor ); } - setBinary(driveNo: DriveNumber, name: string, fmt: BlockFormat, rawData: ArrayBuffer) { + setBinary(drive: DriveNumber, name: string, fmt: BlockFormat, rawData: ArrayBuffer) { let volume = 254; let readOnly = false; if (fmt === '2mg') { const header = read2MGHeader(rawData); - this.metadata[driveNo] = header; + this.metadata[drive] = header; const { bytes, offset } = header; volume = header.volume; readOnly = header.readOnly; rawData = rawData.slice(offset, offset + bytes); } else { - this.metadata[driveNo] = null; + this.metadata[drive] = null; } const options = { rawData, @@ -569,9 +569,9 @@ export default class SmartPort implements Card, MassStorage, Restor volume, }; - this.ext[driveNo] = fmt; - this.disks[driveNo] = createBlockDisk(fmt, options); - this.callbacks?.label(driveNo, name); + this.ext[drive] = fmt; + this.disks[drive] = createBlockDisk(fmt, options); + this.callbacks?.label(drive, name); return true; } diff --git a/js/components/BlockDisk.tsx b/js/components/BlockDisk.tsx index 17a5119..18053d9 100644 --- a/js/components/BlockDisk.tsx +++ b/js/components/BlockDisk.tsx @@ -63,19 +63,19 @@ export const BlockDisk = ({ smartPort, number, on, name }: BlockDiskProps) => { void; } -export const BlockFileModal = ({ smartPort, driveNo: number, onClose, isOpen } : BlockFileModalProps) => { +export const BlockFileModal = ({ smartPort, number, onClose, isOpen } : BlockFileModalProps) => { const [handles, setHandles] = useState(); const [busy, setBusy] = useState(false); const [empty, setEmpty] = useState(true); diff --git a/js/components/DiskDragTarget.tsx b/js/components/DiskDragTarget.tsx index 6afea68..6494795 100644 --- a/js/components/DiskDragTarget.tsx +++ b/js/components/DiskDragTarget.tsx @@ -6,7 +6,7 @@ import { spawn } from './util/promises'; export interface DiskDragTargetProps extends JSX.HTMLAttributes { storage: MassStorage | undefined; - driveNo?: DriveNumber; + drive?: DriveNumber; formats: typeof FLOPPY_FORMATS | typeof BLOCK_FORMATS | typeof DISK_FORMATS; @@ -16,7 +16,7 @@ export interface DiskDragTargetProps extends JSX.HTMLAttributes { event.preventDefault(); event.stopPropagation(); - const targetDrive = driveNo ?? 1; //TODO(whscullin) Maybe pick available drive + const targetDrive = drive ?? 1; //TODO(whscullin) Maybe pick available drive const dt = event.dataTransfer; if (dt?.files.length === 1 && storage) { @@ -87,7 +87,7 @@ export const DiskDragTarget = ({ div.removeEventListener('drop', onDrop); }; } - }, [driveNo, dropRef, formats, onError, storage]); + }, [drive, dropRef, formats, onError, storage]); return (
diff --git a/js/components/DiskII.tsx b/js/components/DiskII.tsx index 442ea4d..400aa83 100644 --- a/js/components/DiskII.tsx +++ b/js/components/DiskII.tsx @@ -65,13 +65,13 @@ export const DiskII = ({ disk2, number, on, name, side }: DiskIIProps) => { - + ; - driveNo: DriveNumber; + number: DriveNumber; onClose: (closeBox?: boolean) => void; } -export const DownloadModal = ({ massStorage, driveNo, onClose, isOpen } : DownloadModalProps) => { +export const DownloadModal = ({ massStorage, number, onClose, isOpen } : DownloadModalProps) => { const [href, setHref] = useState(''); const [downloadName, setDownloadName] = useState(''); const doCancel = useCallback(() => onClose(true), [onClose]); useEffect(() => { if (isOpen) { - const storageData = massStorage.getBinary(driveNo); + const storageData = massStorage.getBinary(number); if (storageData) { const { ext, data } = storageData; const { name } = storageData.metadata; @@ -37,7 +37,7 @@ export const DownloadModal = ({ massStorage, driveNo, onClose, isOpen } : Downlo setHref(''); setDownloadName(''); } - }, [isOpen, driveNo, massStorage]); + }, [isOpen, number, massStorage]); return ( <> diff --git a/js/components/Drives.tsx b/js/components/Drives.tsx index 6a617f5..c44d6e2 100644 --- a/js/components/Drives.tsx +++ b/js/components/Drives.tsx @@ -10,7 +10,7 @@ import { ErrorModal } from './ErrorModal'; import { ProgressModal } from './ProgressModal'; import { loadHttpUnknownFile, getHashParts, loadJSON, SmartStorageBroker } from './util/files'; import { useHash } from './hooks/useHash'; -import { DISK_FORMATS, DRIVE_NUMBERS, SupportedSectors } from 'js/formats/types'; +import { DISK_FORMATS, DriveNumber, SupportedSectors } from 'js/formats/types'; import { spawn, Ready } from './util/promises'; import styles from './css/Drives.module.css'; @@ -90,9 +90,9 @@ export const Drives = ({ cpu, io, sectors, enhanced, ready }: DrivesProps) => { const hashParts = getHashParts(hash); const controllers: AbortController[] = []; let loading = 0; - for (const driveNo of DRIVE_NUMBERS) { - if (hashParts && hashParts[driveNo]) { - const hashPart = decodeURIComponent(hashParts[driveNo]); + for (const drive of [1, 2] as DriveNumber[]) { + if (hashParts && hashParts[drive]) { + const hashPart = decodeURIComponent(hashParts[drive]); const isHttp = hashPart.match(/^https?:/i); const isJson = hashPart.match(/\.json$/i); if (isHttp && !isJson) { @@ -101,7 +101,7 @@ export const Drives = ({ cpu, io, sectors, enhanced, ready }: DrivesProps) => { try { await loadHttpUnknownFile( smartStorageBroker, - driveNo, + drive, hashPart, signal, onProgress); @@ -116,7 +116,7 @@ export const Drives = ({ cpu, io, sectors, enhanced, ready }: DrivesProps) => { })); } else { const url = isHttp ? hashPart : `json/disks/${hashPart}.json`; - loadJSON(disk2, driveNo, url).catch((e) => setError(e)); + loadJSON(disk2, drive, url).catch((e) => setError(e)); } } } diff --git a/js/components/FileModal.tsx b/js/components/FileModal.tsx index bc1eb82..3a636d7 100644 --- a/js/components/FileModal.tsx +++ b/js/components/FileModal.tsx @@ -28,7 +28,7 @@ export type NibbleFileCallback = ( interface FileModalProps { isOpen: boolean; disk2: DiskII; - driveNo: DriveNumber; + number: DriveNumber; onClose: (closeBox?: boolean) => void; } @@ -38,7 +38,7 @@ interface IndexEntry { category: string; } -export const FileModal = ({ disk2, driveNo, onClose, isOpen }: FileModalProps) => { +export const FileModal = ({ disk2, number, onClose, isOpen }: FileModalProps) => { const [busy, setBusy] = useState(false); const [empty, setEmpty] = useState(true); const [category, setCategory] = useState(); @@ -69,13 +69,13 @@ export const FileModal = ({ disk2, driveNo, onClose, isOpen }: FileModalProps) = try { if (handles?.length === 1) { - hashParts[driveNo] = ''; - await loadLocalNibbleFile(disk2, driveNo, await handles[0].getFile()); + hashParts[number] = ''; + await loadLocalNibbleFile(disk2, number, await handles[0].getFile()); } if (filename) { const name = filename.match(/\/([^/]+).json$/) || ['', '']; - hashParts[driveNo] = name[1]; - await loadJSON(disk2, driveNo, filename); + hashParts[number] = name[1]; + await loadJSON(disk2, number, filename); } } catch (e) { setError(e); @@ -86,7 +86,7 @@ export const FileModal = ({ disk2, driveNo, onClose, isOpen }: FileModalProps) = } setHashParts(hashParts); - }, [disk2, filename, driveNo, onClose, handles, hash]); + }, [disk2, filename, number, onClose, handles, hash]); const onChange = useCallback((handles: FileSystemFileHandle[]) => { setEmpty(handles.length === 0); diff --git a/js/components/debugger/Disks.tsx b/js/components/debugger/Disks.tsx index 7ffea55..b2f535c 100644 --- a/js/components/debugger/Disks.tsx +++ b/js/components/debugger/Disks.tsx @@ -235,7 +235,7 @@ const Catalog = ({ dos, setFileData }: CatalogProps) => { */ interface DiskInfoProps { massStorage: MassStorage; - driveNo: DriveNumber; + drive: DriveNumber; setFileData: (fileData: FileData) => void; } @@ -250,9 +250,9 @@ interface DiskInfoProps { * @param drive The drive number * @returns DiskInfo component */ -const DiskInfo = ({ massStorage, driveNo, setFileData }: DiskInfoProps) => { +const DiskInfo = ({ massStorage, drive, setFileData }: DiskInfoProps) => { const disk = useMemo(() => { - const massStorageData = massStorage.getBinary(driveNo, 'po'); + const massStorageData = massStorage.getBinary(drive, 'po'); if (massStorageData) { const { data, readOnly, ext } = massStorageData; const { name } = massStorageData.metadata; @@ -265,7 +265,7 @@ const DiskInfo = ({ massStorage, driveNo, setFileData }: DiskInfoProps) => { volume: 254, }); } else if (data.byteLength < 800 * 1024) { - const doData = massStorage.getBinary(driveNo, 'do'); + const doData = massStorage.getBinary(drive, 'do'); if (doData) { if (isMaybeDOS33(doData)) { disk = createDiskFromDOS({ @@ -288,7 +288,7 @@ const DiskInfo = ({ massStorage, driveNo, setFileData }: DiskInfoProps) => { return disk; } return null; - }, [massStorage, driveNo]); + }, [massStorage, drive]); if (disk) { try { @@ -409,11 +409,11 @@ export const Disks = ({ apple2 }: DisksProps) => {
{card.constructor.name} - 1
- +
{card.constructor.name} - 2
- +
))} diff --git a/js/components/util/files.ts b/js/components/util/files.ts index b4caac1..d365c35 100644 --- a/js/components/util/files.ts +++ b/js/components/util/files.ts @@ -48,7 +48,7 @@ export const getNameAndExtension = (url: string) => { export const loadLocalFile = ( storage: MassStorage, formats: typeof FLOPPY_FORMATS | typeof BLOCK_FORMATS | typeof DISK_FORMATS, - driveNo: DriveNumber, + number: DriveNumber, file: File, ) => { return new Promise((resolve, reject) => { @@ -58,7 +58,7 @@ export const loadLocalFile = ( const { name, ext } = getNameAndExtension(file.name); if (includes(formats, ext)) { initGamepad(); - if (storage.setBinary(driveNo, name, ext, result)) { + if (storage.setBinary(number, name, ext, result)) { resolve(true); } else { reject(`Unable to load ${name}`); @@ -76,12 +76,12 @@ export const loadLocalFile = ( * selection form element to be loaded. * * @param smartPort SmartPort object - * @param driveNo Drive number + * @param number Drive number * @param file Browser File object to load * @returns true if successful */ -export const loadLocalBlockFile = (smartPort: SmartPort, driveNo: DriveNumber, file: File) => { - return loadLocalFile(smartPort, BLOCK_FORMATS, driveNo, file); +export const loadLocalBlockFile = (smartPort: SmartPort, number: DriveNumber, file: File) => { + return loadLocalFile(smartPort, BLOCK_FORMATS, number, file); }; /** @@ -89,12 +89,12 @@ export const loadLocalBlockFile = (smartPort: SmartPort, driveNo: DriveNumber, f * selection form element to be loaded. * * @param disk2 Disk2 object - * @param driveNo Drive number + * @param number Drive number * @param file Browser File object to load * @returns true if successful */ -export const loadLocalNibbleFile = (disk2: Disk2, driveNo: DriveNumber, file: File) => { - return loadLocalFile(disk2, FLOPPY_FORMATS, driveNo, file); +export const loadLocalNibbleFile = (disk2: Disk2, number: DriveNumber, file: File) => { + return loadLocalFile(disk2, FLOPPY_FORMATS, number, file); }; /** @@ -103,13 +103,13 @@ export const loadLocalNibbleFile = (disk2: Disk2, driveNo: DriveNumber, file: Fi * as the emulator. * * @param disk2 Disk2 object - * @param driveNo Drive number + * @param number Drive number * @param url URL, relative or absolute to JSON file * @returns true if successful */ export const loadJSON = async ( disk2: Disk2, - driveNo: DriveNumber, + number: DriveNumber, url: string, ) => { const response = await fetch(url); @@ -120,7 +120,7 @@ export const loadJSON = async ( if (!includes(FLOPPY_FORMATS, data.type)) { throw new Error(`Type "${data.type}" not recognized.`); } - disk2.setDisk(driveNo, data); + disk2.setDisk(number, data); initGamepad(data.gamepad); }; @@ -166,13 +166,13 @@ export const loadHttpFile = async ( * as the emulator. * * @param smartPort SmartPort object - * @param driveNo Drive number + * @param number Drive number * @param url URL, relative or absolute to JSON file * @returns true if successful */ export const loadHttpBlockFile = async ( smartPort: SmartPort, - driveNo: DriveNumber, + number: DriveNumber, url: string, signal?: AbortSignal, onProgress?: ProgressCallback @@ -182,7 +182,7 @@ export const loadHttpBlockFile = async ( throw new Error(`Extension "${ext}" not recognized.`); } const data = await loadHttpFile(url, signal, onProgress); - smartPort.setBinary(driveNo, name, ext, data); + smartPort.setBinary(number, name, ext, data); initGamepad(); return true; @@ -194,55 +194,55 @@ export const loadHttpBlockFile = async ( * as the emulator. * * @param disk2 Disk2 object - * @param driveNo Drive number + * @param number Drive number * @param url URL, relative or absolute to JSON file * @returns true if successful */ export const loadHttpNibbleFile = async ( disk2: Disk2, - driveNo: DriveNumber, + number: DriveNumber, url: string, signal?: AbortSignal, onProgress?: ProgressCallback ) => { if (url.endsWith('.json')) { - return loadJSON(disk2, driveNo, url); + return loadJSON(disk2, number, url); } const { name, ext } = getNameAndExtension(url); if (!includes(FLOPPY_FORMATS, ext)) { throw new Error(`Extension "${ext}" not recognized.`); } const data = await loadHttpFile(url, signal, onProgress); - disk2.setBinary(driveNo, name, ext, data); + disk2.setBinary(number, name, ext, data); initGamepad(); return loadHttpFile(url, signal, onProgress); }; export const loadHttpUnknownFile = async ( smartStorageBroker: SmartStorageBroker, - driveNo: DriveNumber, + number: DriveNumber, url: string, signal?: AbortSignal, onProgress?: ProgressCallback, ) => { const data = await loadHttpFile(url, signal, onProgress); const { name, ext } = getNameAndExtension(url); - smartStorageBroker.setBinary(driveNo, name, ext, data); + smartStorageBroker.setBinary(number, name, ext, data); }; export class SmartStorageBroker implements MassStorage { constructor(private disk2: Disk2, private smartPort: SmartPort) {} - setBinary(driveNo: DriveNumber, name: string, ext: string, data: ArrayBuffer): boolean { + setBinary(drive: DriveNumber, name: string, ext: string, data: ArrayBuffer): boolean { if (includes(DISK_FORMATS, ext)) { if (data.byteLength >= 800 * 1024) { if (includes(BLOCK_FORMATS, ext)) { - this.smartPort.setBinary(driveNo, name, ext, data); + this.smartPort.setBinary(drive, name, ext, data); } else { throw new Error(`Unable to load "${name}"`); } } else if (includes(FLOPPY_FORMATS, ext)) { - this.disk2.setBinary(driveNo, name, ext, data); + this.disk2.setBinary(drive, name, ext, data); } else { throw new Error(`Unable to load "${name}"`); } diff --git a/js/formats/types.ts b/js/formats/types.ts index 73fe547..a3553b9 100644 --- a/js/formats/types.ts +++ b/js/formats/types.ts @@ -234,7 +234,7 @@ export const PROCESS_JSON = 'PROCESS_JSON'; export interface ProcessBinaryMessage { type: typeof PROCESS_BINARY; payload: { - driveNo: DriveNumber; + drive: DriveNumber; fmt: FloppyFormat; options: DiskOptions; }; @@ -244,7 +244,7 @@ export interface ProcessBinaryMessage { export interface ProcessJsonDiskMessage { type: typeof PROCESS_JSON_DISK; payload: { - driveNo: DriveNumber; + drive: DriveNumber; jsonDisk: JSONDisk; }; } @@ -253,7 +253,7 @@ export interface ProcessJsonDiskMessage { export interface ProcessJsonMessage { type: typeof PROCESS_JSON; payload: { - driveNo: DriveNumber; + drive: DriveNumber; json: string; }; } @@ -272,7 +272,7 @@ export const DISK_PROCESSED = 'DISK_PROCESSED'; export interface DiskProcessedResponse { type: typeof DISK_PROCESSED; payload: { - driveNo: DriveNumber; + drive: DriveNumber; disk: FloppyDisk | null; }; } diff --git a/js/ui/apple2.ts b/js/ui/apple2.ts index db081d5..498b5dc 100644 --- a/js/ui/apple2.ts +++ b/js/ui/apple2.ts @@ -84,7 +84,7 @@ let joystick: JoyStick; let system: System; let keyboard: KeyBoard; let io: Apple2IO; -let driveNo: DriveNumber = 1; +let _currentDrive: DriveNumber = 1; let _e: boolean; let ready: Promise<[void, void]>; @@ -103,13 +103,14 @@ export function compileApplesoftProgram(program: string) { } export function openLoad(driveString: string, event: MouseEvent) { - driveNo = parseInt(driveString, 10) as DriveNumber; - if (event.metaKey && includes(DRIVE_NUMBERS, driveNo)) { + const drive = parseInt(driveString, 10) as DriveNumber; + _currentDrive = drive; + if (event.metaKey && includes(DRIVE_NUMBERS, drive)) { openLoadHTTP(); } else { - if (disk_cur_cat[driveNo]) { + if (disk_cur_cat[drive]) { const element = document.querySelector('#category_select')!; - element.value = disk_cur_cat[driveNo]; + element.value = disk_cur_cat[drive]; selectCategory(); } MicroModal.show('load-modal'); @@ -117,27 +118,27 @@ export function openLoad(driveString: string, event: MouseEvent) { } export function openSave(driveString: string, event: MouseEvent) { - const driveNo = parseInt(driveString, 10) as DriveNumber; + const drive = parseInt(driveString, 10) as DriveNumber; const mimeType = 'application/octet-stream'; - const storageData = _disk2.getBinary(driveNo); + const storageData = _disk2.getBinary(drive); const a = document.querySelector('#local_save_link')!; if (!storageData) { - alert(`No data from drive ${driveNo}`); + alert(`No data from drive ${drive}`); return; } const { data } = storageData; const blob = new Blob([data], { 'type': mimeType }); a.href = window.URL.createObjectURL(blob); - a.download = driveLights.label(driveNo) + '.dsk'; + a.download = driveLights.label(drive) + '.dsk'; if (event.metaKey) { - dumpDisk(driveNo); + dumpDisk(drive); } else { const saveName = document.querySelector('#save_name')!; - saveName.value = driveLights.label(driveNo); + saveName.value = driveLights.label(drive); MicroModal.show('save-modal'); } } @@ -153,12 +154,12 @@ export function openAlert(msg: string) { * Drag and Drop */ -export function handleDragOver(_driveNo: number, event: DragEvent) { +export function handleDragOver(_drive: number, event: DragEvent) { event.preventDefault(); event.dataTransfer!.dropEffect = 'copy'; } -export function handleDragEnd(_driveNo: number, event: DragEvent) { +export function handleDragEnd(_drive: number, event: DragEvent) { const dt = event.dataTransfer!; if (dt.items) { for (let i = 0; i < dt.items.length; i++) { @@ -169,23 +170,23 @@ export function handleDragEnd(_driveNo: number, event: DragEvent) { } } -export function handleDrop(driveNo: number, event: DragEvent) { +export function handleDrop(drive: number, event: DragEvent) { event.preventDefault(); event.stopPropagation(); - if (driveNo < 1) { + if (drive < 1) { if (!_disk2.getMetadata(1)) { - driveNo = 1; + drive = 1; } else if (!_disk2.getMetadata(2)) { - driveNo = 2; + drive = 2; } else { - driveNo = 1; + drive = 1; } } const dt = event.dataTransfer!; if (dt.files.length === 1) { const runOnLoad = event.shiftKey; - doLoadLocal(driveNo as DriveNumber, dt.files[0], { runOnLoad }); + doLoadLocal(drive as DriveNumber, dt.files[0], { runOnLoad }); } else if (dt.files.length === 2) { doLoadLocal(1, dt.files[0]); doLoadLocal(2, dt.files[1]); @@ -194,7 +195,7 @@ export function handleDrop(driveNo: number, event: DragEvent) { if (dt.items[idx].type === 'text/uri-list') { dt.items[idx].getAsString(function (url) { const parts = hup().split('|'); - parts[driveNo - 1] = url; + parts[drive - 1] = url; document.location.hash = parts.join('|'); }); } @@ -227,7 +228,7 @@ function loadingStop() { } } -export function loadAjax(driveNo: DriveNumber, url: string) { +export function loadAjax(drive: DriveNumber, url: string) { loadingStart(); fetch(url).then(function (response: Response) { @@ -240,7 +241,7 @@ export function loadAjax(driveNo: DriveNumber, url: string) { if (data.type === 'binary') { loadBinary(data ); } else if (includes(DISK_FORMATS, data.type)) { - loadDisk(driveNo, data); + loadDisk(drive, data); } initGamepad(data.gamepad); loadingStop(); @@ -268,7 +269,7 @@ export function doLoad(event: MouseEvent|KeyboardEvent) { const files = localFile.files; if (files && files.length === 1) { const runOnLoad = event.shiftKey; - doLoadLocal(driveNo, files[0], { runOnLoad }); + doLoadLocal(_currentDrive, files[0], { runOnLoad }); } else if (url) { let filename; MicroModal.close('load-modal'); @@ -277,7 +278,7 @@ export function doLoad(event: MouseEvent|KeyboardEvent) { if (filename === '__manage') { openManage(); } else { - loadLocalStorage(driveNo, filename); + loadLocalStorage(_currentDrive, filename); } } else { const r1 = /json\/disks\/(.*).json$/.exec(url); @@ -287,7 +288,7 @@ export function doLoad(event: MouseEvent|KeyboardEvent) { filename = url; } const parts = hup().split('|'); - parts[driveNo - 1] = filename; + parts[_currentDrive - 1] = filename; document.location.hash = parts.join('|'); } } @@ -296,7 +297,7 @@ export function doLoad(event: MouseEvent|KeyboardEvent) { export function doSave() { const saveName = document.querySelector('#save_name')!; const name = saveName.value; - saveLocalStorage(driveNo, name); + saveLocalStorage(_currentDrive, name); MicroModal.close('save-modal'); window.setTimeout(() => openAlert('Saved'), 0); } @@ -312,7 +313,7 @@ interface LoadOptions { runOnLoad?: boolean; } -function doLoadLocal(driveNo: DriveNumber, file: File, options: Partial = {}) { +function doLoadLocal(drive: DriveNumber, file: File, options: Partial = {}) { const parts = file.name.split('.'); const ext = parts[parts.length - 1].toLowerCase(); const matches = file.name.match(CIDERPRESS_EXTENSION); @@ -321,7 +322,7 @@ function doLoadLocal(driveNo: DriveNumber, file: File, options: Partial= 800 * 1024) { if ( includes(BLOCK_FORMATS, ext) && - _massStorage.setBinary(driveNo, name, ext, result) + _massStorage.setBinary(drive, name, ext, result) ) { initGamepad(); } else { @@ -392,7 +393,7 @@ function doLoadLocalDisk(driveNo: DriveNumber, file: File) { } else { if ( includes(FLOPPY_FORMATS, ext) && - _disk2.setBinary(driveNo, name, ext, result) + _disk2.setBinary(drive, name, ext, result) ) { initGamepad(); } else { @@ -405,7 +406,7 @@ function doLoadLocalDisk(driveNo: DriveNumber, file: File) { fileReader.readAsArrayBuffer(file); } -export function doLoadHTTP(driveNo: DriveNumber, url?: string) { +export function doLoadHTTP(drive: DriveNumber, url?: string) { if (!url) { MicroModal.close('http-modal'); } @@ -453,13 +454,13 @@ export function doLoadHTTP(driveNo: DriveNumber, url?: string) { if (includes(DISK_FORMATS, ext)) { if (data.byteLength >= 800 * 1024) { if (includes(BLOCK_FORMATS, ext)) { - _massStorage.setBinary(driveNo, name, ext, data); + _massStorage.setBinary(drive, name, ext, data); initGamepad(); } } else { if ( includes(FLOPPY_FORMATS, ext) && - _disk2.setBinary(driveNo, name, ext, data) + _disk2.setBinary(drive, name, ext, data) ) { initGamepad(); } @@ -546,11 +547,11 @@ function updateSoundButton(on: boolean) { } } -function dumpDisk(driveNo: DriveNumber) { +function dumpDisk(drive: DriveNumber) { const wind = window.open('', '_blank')!; - wind.document.title = driveLights.label(driveNo); + wind.document.title = driveLights.label(drive); wind.document.write('
');
-    wind.document.write(_disk2.getJSON(driveNo, true));
+    wind.document.write(_disk2.getJSON(drive, true));
     wind.document.write('
'); wind.document.close(); } @@ -585,7 +586,7 @@ export function selectCategory() { option.value = file.filename; option.innerText = name; diskSelect.append(option); - if (disk_cur_name[driveNo] === name) { + if (disk_cur_name[_currentDrive] === name) { option.selected = true; } } @@ -602,7 +603,7 @@ export function clickDisk(event: MouseEvent|KeyboardEvent) { } /** Called to load disks from the local catalog. */ -function loadDisk(driveNo: DriveNumber, disk: JSONDisk) { +function loadDisk(drive: DriveNumber, disk: JSONDisk) { let name = disk.name; const category = disk.category!; // all disks in the local catalog have a category @@ -610,10 +611,10 @@ function loadDisk(driveNo: DriveNumber, disk: JSONDisk) { name += ' - ' + disk.disk; } - disk_cur_cat[driveNo] = category; - disk_cur_name[driveNo] = name; + disk_cur_cat[drive] = category; + disk_cur_name[drive] = name; - _disk2.setDisk(driveNo, disk); + _disk2.setDisk(drive, disk); initGamepad(disk.gamepad); } @@ -653,16 +654,16 @@ type LocalDiskIndex = { [name: string]: string; }; -function saveLocalStorage(driveNo: DriveNumber, name: string) { +function saveLocalStorage(drive: DriveNumber, name: string) { const diskIndex = JSON.parse(window.localStorage.getItem('diskIndex') || '{}') as LocalDiskIndex; - const json = _disk2.getJSON(driveNo); + const json = _disk2.getJSON(drive); diskIndex[name] = json; window.localStorage.setItem('diskIndex', JSON.stringify(diskIndex)); - driveLights.label(driveNo, name); - driveLights.dirty(driveNo, false); + driveLights.label(drive, name); + driveLights.dirty(drive, false); updateLocalStorage(); } @@ -676,12 +677,12 @@ function deleteLocalStorage(name: string) { updateLocalStorage(); } -function loadLocalStorage(driveNo: DriveNumber, name: string) { +function loadLocalStorage(drive: DriveNumber, name: string) { const diskIndex = JSON.parse(window.localStorage.getItem('diskIndex') || '{}') as LocalDiskIndex; if (diskIndex[name]) { - _disk2.setJSON(driveNo, diskIndex[name]); - driveLights.label(driveNo, name); - driveLights.dirty(driveNo, false); + _disk2.setJSON(drive, diskIndex[name]); + driveLights.label(drive, name); + driveLights.dirty(drive, false); } } diff --git a/js/ui/drive_lights.ts b/js/ui/drive_lights.ts index 396a652..04399a9 100644 --- a/js/ui/drive_lights.ts +++ b/js/ui/drive_lights.ts @@ -2,8 +2,8 @@ import { Callbacks } from '../cards/disk2'; import type { DriveNumber } from '../formats/types'; export default class DriveLights implements Callbacks { - public driveLight(driveNo: DriveNumber, on: boolean) { - const disk = document.querySelector(`#disk${driveNo}`); + public driveLight(drive: DriveNumber, on: boolean) { + const disk = document.querySelector(`#disk${drive}`); if (disk) { disk.style.backgroundImage = on ? 'url(css/red-on-16.png)' : @@ -11,12 +11,12 @@ export default class DriveLights implements Callbacks { } } - public dirty(_driveNo: DriveNumber, _dirty: boolean) { + public dirty(_drive: DriveNumber, _dirty: boolean) { // document.querySelector('#disksave' + drive).disabled = !dirty; } - public label(driveNo: DriveNumber, label?: string, side?: string) { - const labelElement = document.querySelector(`#disk-label${driveNo}`); + public label(drive: DriveNumber, label?: string, side?: string) { + const labelElement = document.querySelector(`#disk-label${drive}`); let labelText = ''; if (labelElement) { labelText = labelElement.innerText; diff --git a/test/js/cards/disk2.spec.ts b/test/js/cards/disk2.spec.ts index a0938ce..9e31cd0 100644 --- a/test/js/cards/disk2.spec.ts +++ b/test/js/cards/disk2.spec.ts @@ -66,8 +66,8 @@ describe('DiskII', () => { const state = diskII.getState(); // These are just arbitrary changes, not an exhaustive list of fields. - (state.drives[1].driver as {skip:number}).skip = 1; - state.controllerState.driveNo = 2; + state.skip = 1; + state.controllerState.drive = 2; state.controllerState.latch = 0x42; state.controllerState.on = true; state.controllerState.q7 = true; @@ -97,7 +97,7 @@ describe('DiskII', () => { expect(callbacks.label).toHaveBeenCalledWith(2, 'Disk 2', undefined); expect(callbacks.dirty).toHaveBeenCalledTimes(2); - expect(callbacks.dirty).toHaveBeenCalledWith(1, false); + expect(callbacks.dirty).toHaveBeenCalledWith(1, true); expect(callbacks.dirty).toHaveBeenCalledWith(2, false); }); @@ -760,11 +760,11 @@ class TestDiskReader { nibbles = 0; diskII: DiskII; - constructor(driveNo: DriveNumber, label: string, image: ArrayBufferLike, apple2IO: Apple2IO, callbacks: Callbacks) { + constructor(drive: DriveNumber, label: string, image: ArrayBufferLike, apple2IO: Apple2IO, callbacks: Callbacks) { mocked(apple2IO).cycles.mockImplementation(() => this.cycles); this.diskII = new DiskII(apple2IO, callbacks); - this.diskII.setBinary(driveNo, label, 'woz', image); + this.diskII.setBinary(drive, label, 'woz', image); } readNibble(): byte { @@ -824,7 +824,7 @@ class TestDiskReader { rawTracks() { // NOTE(flan): Hack to access private properties. - const disk = (this.diskII as unknown as { disks: WozDisk[] }).disks[1]; + const disk = (this.diskII as unknown as { curDisk: WozDisk }).curDisk; const result: Uint8Array[] = []; for (let i = 0; i < disk.rawTracks.length; i++) { result[i] = disk.rawTracks[i].slice(0); diff --git a/workers/format.worker.ts b/workers/format.worker.ts index e8c95ad..21df0e0 100644 --- a/workers/format.worker.ts +++ b/workers/format.worker.ts @@ -19,7 +19,7 @@ debug('Worker loaded'); addEventListener('message', (message: MessageEvent) => { debug('Worker started', message.type); const data = message.data; - const { driveNo } = data.payload; + const { drive } = data.payload; let disk: FloppyDisk | null = null; switch (data.type) { @@ -45,7 +45,7 @@ addEventListener('message', (message: MessageEvent) => { const response: DiskProcessedResponse = { type: DISK_PROCESSED, payload: { - driveNo, + drive, disk } };